<?php

require_once ABSPATH . 'wp-load.php';

global $wp_session;

require_once plugin_dir_path(__FILE__) . '../classes/class.settings.php';

$oSettings = new settings();
$sSettings = $wp_session['session_data']['sSettings'];

$aSettings = array();

$aSettings["form_action"] 					= !empty($_POST["form_action"]) 				? filter_var($_POST["form_action"]) 				: false;
$aSettings["authentication_key"] 			= isset($_POST["authentication_key"]) 			? filter_var($_POST["authentication_key"]) 			: $sSettings['settings']['authentication_key'];
$aSettings["position_video_in_gallery"]		= isset($_POST["position_video_in_gallery"]) 	? filter_var($_POST["position_video_in_gallery"]) 	: $sSettings['settings']['position_video_in_gallery'];
$aSettings["items_per_row"] 				= isset($_POST["items_per_row"]) 				? filter_var($_POST["items_per_row"]) 				: $sSettings['settings']['items_per_row'];
$aSettings["items_per_page"] 				= isset($_POST["items_per_page"]) 				? filter_var($_POST["items_per_page"]) 				: $sSettings['settings']['items_per_page'];
$aSettings["items_per_page_no_filter"] 		= isset($_POST["items_per_page_no_filter"]) 	? filter_var($_POST["items_per_page_no_filter"]) 	: $sSettings['settings']['items_per_page_no_filter'];
$aSettings["button_bg_color"] 				= isset($_POST["button_bg_color"]) 				? filter_var($_POST["button_bg_color"]) 			: $sSettings['settings']['button_bg_color'];
$aSettings["button_text_color"] 			= isset($_POST["button_text_color"]) 			? filter_var($_POST["button_text_color"]) 			: $sSettings['settings']['button_text_color'];
$aSettings["object_bg_color"] 				= isset($_POST["object_bg_color"]) 				? filter_var($_POST["object_bg_color"]) 			: $sSettings['settings']['object_bg_color'];
$aSettings["object_text_color"] 			= isset($_POST["object_text_color"]) 			? filter_var($_POST["object_text_color"]) 			: $sSettings['settings']['object_text_color'];
$aSettings["bg_color"] 						= isset($_POST["bg_color"]) 					? filter_var($_POST["bg_color"]) 					: $sSettings['settings']['bg_color'];
$aSettings["text_color"] 					= isset($_POST["text_color"]) 					? filter_var($_POST["text_color"]) 					: $sSettings['settings']['text_color'];
$aSettings["ovis-userid"] 					= isset($_POST["ovis-userid"]) 					? filter_var($_POST["ovis-userid"]) 				: false;
$aSettings["ovis-username"] 				= isset($_POST["ovis-username"]) 				? filter_var($_POST["ovis-username"]) 				: false;
$aSettings["ovis-uniqueid"] 				= isset($_POST["ovis-uniqueid"]) 				? filter_var($_POST["ovis-uniqueid"]) 				: false;
$aSettings["ovis_custom_css"] 				= isset($_POST["ovis_custom_css"]) 				? filter_var($_POST["ovis_custom_css"]) 			: false;

/**
 * Clear cache
 */
if($aSettings["form_action"] == 'flush_ovis_cache') {

	$saved = false;

	if($oSettings->clear_cache()) {
		$saved = 'cleared';
	}

	do_action('ovis_clean_cache', false);

	echo $saved;
}


/**
 * Trade-in image
 */
if($aSettings["form_action"] == 'inruil_image') {
	
	$sHash = date('U');
	$sHash .= '-'.uniqid('inruil_image_', true);
	$sHash .= bin2hex(openssl_random_pseudo_bytes(32));
	
	$sHash = hash('sha256',$sHash);
	
	if(!empty($_FILES['files']) && is_array($_FILES['files'])) {

		if(!empty($_FILES['files']['tmp_name']) && is_array($_FILES['files']['tmp_name'])) {
			
			foreach($_FILES['files']['tmp_name'] as $key=>$value) {
				$sFileName = $_FILES['files']['name'][$key];
				$extension = pathinfo($sFileName, PATHINFO_EXTENSION);
				move_uploaded_file($value, ABSPATH . 'wp-content/cache/ovis/' . $sHash . '.' . $extension);
			}
		}
	}


	$oReturn = new stdclass();
	$oReturn->filename = $sHash . '.' . $extension;
	$oReturn->url = $sHash;
	
	header('Content-Type: application/json');
	echo json_encode($oReturn);
	exit;
}


/**
 * Save settings
 */
if($aSettings["form_action"] == 'save') {
	$saved = false;

	if($oSettings->save_settings($aSettings)) {
		$saved = 'saved';
	}

	echo $saved;
} 


/**
 * Save appearance
 */
if($aSettings["form_action"] == 'save-appearance') {
	$saved = false;
	
	$aTextsToSave = array();
	$aTextsToSave['label_verhuuraanvraag'] = array();
	$aTextsToSave['label_verhuuraanvraag']['nl'] = isset($_POST["label_verhuuraanvraag"]["nl"]) ? filter_var($_POST["label_verhuuraanvraag"]["nl"]) : $sSettings['settings']['rental_button_default']['nl'];
	$aTextsToSave['label_verhuuraanvraag']['en'] = isset($_POST["label_verhuuraanvraag"]["en"]) ? filter_var($_POST["label_verhuuraanvraag"]["en"]) : $sSettings['settings']['rental_button_default']['en'];
	$aTextsToSave['label_verhuuraanvraag']['de'] = isset($_POST["label_verhuuraanvraag"]["de"]) ? filter_var($_POST["label_verhuuraanvraag"]["de"]) : $sSettings['settings']['rental_button_default']['de'];
	$aTextsToSave['label_verhuuraanvraag']['fr'] = isset($_POST["label_verhuuraanvraag"]["fr"]) ? filter_var($_POST["label_verhuuraanvraag"]["fr"]) : $sSettings['settings']['rental_button_default']['fr'];

	$aTextsToSave['label_verhuuropmerking'] = array();
	$aTextsToSave['label_verhuuropmerking']['nl'] = isset($_POST["label_verhuuropmerking"]["nl"]) ? filter_var(($_POST["label_verhuuropmerking"]["nl"])) : $sSettings['settings']['rental_opmerking_default']['nl'];
	$aTextsToSave['label_verhuuropmerking']['en'] = isset($_POST["label_verhuuropmerking"]["en"]) ? filter_var(($_POST["label_verhuuropmerking"]["en"])) : $sSettings['settings']['rental_opmerking_default']['en'];
	$aTextsToSave['label_verhuuropmerking']['de'] = isset($_POST["label_verhuuropmerking"]["de"]) ? filter_var(($_POST["label_verhuuropmerking"]["de"])) : $sSettings['settings']['rental_opmerking_default']['de'];
	$aTextsToSave['label_verhuuropmerking']['fr'] = isset($_POST["label_verhuuropmerking"]["fr"]) ? filter_var(($_POST["label_verhuuropmerking"]["fr"])) : $sSettings['settings']['rental_opmerking_default']['fr'];
	
	$aTextsToSave['label_koopknop'] = array();
	$aTextsToSave['label_koopknop']['nl'] = isset($_POST["label_koopknop"]["nl"]) ? filter_var(($_POST["label_koopknop"]["nl"])) : $sSettings['settings']['koopknop_default']['nl'];
	$aTextsToSave['label_koopknop']['en'] = isset($_POST["label_koopknop"]["en"]) ? filter_var(($_POST["label_koopknop"]["en"])) : $sSettings['settings']['koopknop_default']['en'];
	$aTextsToSave['label_koopknop']['de'] = isset($_POST["label_koopknop"]["de"]) ? filter_var(($_POST["label_koopknop"]["de"])) : $sSettings['settings']['koopknop_default']['de'];
	$aTextsToSave['label_koopknop']['fr'] = isset($_POST["label_koopknop"]["fr"]) ? filter_var(($_POST["label_koopknop"]["fr"])) : $sSettings['settings']['koopknop_default']['fr'];
	
	$aSettings["ovis_custom_css"] 	= isset($_POST["custom_css"]) ? base64_encode(serialize($_POST["custom_css"])) : '';
	$aSettings["ovis_texts"] 		= base64_encode(serialize($aTextsToSave));
	$aSettings["ovis_anchor"] 		= isset($_POST["ovis_anchor"]) ? $_POST["ovis_anchor"] : '';
	
	if($oSettings->save_appearance($aSettings)) {
		$saved = 'saved';
	}

	echo $saved;
}


if($aSettings["form_action"] == 'save-language') {

	$oResponse = new stdclass();
	$oResponse->success = true;
	$oResponse->language = $_POST['language'];
	$oResponse->unique_id = $_POST['unique_id'];
	$result = addDataToSession(array('ovis-language'), $_POST['language'] . '_' .strtoupper($_POST['language']));
	$oResponse->result = $result;
	$oResponse->session = $wp_session['session_data'];

	header('Content-Type: application/json');
	echo json_encode($oResponse);
	wp_die();
}


/**
 * Get unavailable rental days
 */
if($aSettings["form_action"] == 'get-blocked-days') {

	$arr = new stdclass();
	$arr->item = $_POST['ovis-blocked-object'];
	$arr->blocked = '';

	require_once plugin_dir_path(__FILE__) . '../classes/class.data.php';

	$oObjectData = new data($sSettings, 'minimal');

	$aBlockedDates = $oObjectData->getBlockedDates($_POST['ovis-blocked-object']);

	$aMonthHistory = array();

	$currentDay = date('d');
	$currentMonth = date('m');
	$currentYear = date('Y');

	if($currentDay > 1) {
		
		$begin = new DateTime( $currentYear.'-'.$currentMonth.'-01');
		$end   = new DateTime( $currentYear.'-'.$currentMonth.'-'.$currentDay );

		for($i=$begin; $i<$end; $i->modify('+1 day')) {
			$aMonthHistory[] = $i->format('d-m-Y');
		}
	}

	$sBlockedDaysSelect = '';

	if(!empty($aBlockedDates) && is_array($aBlockedDates)) {

		$sDateToCheck = false;
		
		foreach($aBlockedDates as $aBlockedDate) {

			if($aBlockedDate >= date('Y-m-d')) {
				$sBlockedDay = date('d-m-Y',strtotime($aBlockedDate));
				$sBlockedDayNext = date('Y-m-d', strtotime('-1 day', strtotime($sBlockedDay)));
				$sFirst = false;

				if(empty($sDateToCheck)) {
					$sFirst = true;
				} else {

					if(!in_array($sBlockedDayNext,$aBlockedDates)) {
						$sLast = true;
					} else {
						
						if(!empty($sLast)) {
							$sFirst = true;
						}
						
						$sLast = false;
					}
				}

				$sDateToCheck = $sBlockedDay;

				if(!in_array($sBlockedDay,$aMonthHistory)) {
					if(!empty($sFirst)) {
						$sBlockedDaysSelect .= '\'ChangeDayLast'.date('d-m-Y',strtotime($aBlockedDate)).'\',';
					} elseif(!empty($sLast)) {
						$sBlockedDaysSelect .= '\'ChangeDayFirst'.date('d-m-Y',strtotime($aBlockedDate)).'\',';
					} else {
						$sBlockedDaysSelect .= '\''.date('d-m-Y',strtotime($aBlockedDate)).'\',';
					}
				}
			}
		}
	}

	if(!empty($aMonthHistory) && is_array($aMonthHistory)) {
		foreach($aMonthHistory as $aMonthHistoryDay) {
			$sBlockedDaysSelect .= '\'History'.$aMonthHistoryDay.'\',';
		}
	}
	
	if(!empty($sBlockedDaysSelect)) {
		$arr->blocked = $sBlockedDaysSelect;
	}

	header('Content-Type: application/json');
	echo json_encode($arr);
	wp_die();
}


/* parse contact-request */

/**
 * Contact 
 */
if($aSettings["form_action"] == 'contact-aanbieder') {

	$arr = new stdclass();
	$arr->item = $_POST['ovis-contact-object'];
	$arr->errors = array();
	
	if(empty($_POST['ovis-contact-object'])) {
		$arr->status = 'error';
		$arr->errors['object'] = true;
	} else {
		
		if(!empty($_POST['ovis-contact-email'])) {
			$arr->status = 'error';
			$arr->errors['captcha'] = true;
		}
		
		if(empty($_POST['ovis-contact-name'])) {
			$arr->errors['name'] = true;
		}
		
		if(!empty($_POST['ovis-contact-subject']) && ($_POST['ovis-contact-subject'] == 'proefrit' || $_POST['ovis-contact-subject'] == 'afspraak' || $_POST['ovis-contact-subject'] == 'bezichtiging')) {
			
			if(empty($_POST['ovis-contact-date'])) {
				$arr->errors['date'] = true;
			}
			
			if(empty($_POST['ovis-contact-date'])) {
				$arr->errors['time'] = true;
			}
		}
		
		if(empty($_POST['ovis-contact-contactperson']) || !is_email($_POST['ovis-contact-contactperson'])) {
			$arr->errors['sender'] = true;
		}
		
		if(empty($_POST['ovis-contact-phone'])) {
			$arr->errors['phone'] = true;
		}
		if(empty($_POST['ovis-contact-message'])) {
			$arr->errors['message'] = true;
		}
		
		if(empty($arr->errors)) {
			$arr->status = 'succes';
		} else {
			$arr->status = 'error';
		}
	}
	
	/* post to OVIS */
	if($arr->status == 'succes') {
		
		require_once(plugin_dir_path(__FILE__) . '../classes/class.contact.php');
		$oContact = new contact($sSettings);
		$oContact->postContactRequest($_POST);
		
		if($oContact->bPostError && !empty($oContact->aPostErrors)) {
			$arr->status = 'error';

			foreach($oContact->aPostErrors as $sErrorKey => $sError) {
				
				switch($sErrorKey) {
					case 'missing-field-category':
					case 'unknown-category':$arr->errors['soort'] = true;
						break;
					case 'missing-field-email':
					case 'invalid-format-email':
						$arr->errors['sender'] = true;
						break;
					case 'missing-field-phonenumber':
						$arr->errors['phone'] = true;
						break;
					case 'missing-field-name':
						$arr->errors['name'] = true;
						break;
					case 'missingfield-message':
						$arr->errors['message'] = true;
						break;
					default:
						$arr->errors['general'][] = $sErrorKey;
						break;
				}
			}
		}
	}
	
	header('Content-Type: application/json');
	echo json_encode($arr);
	wp_die();
}

/* parse rental-request */
if($aSettings["form_action"] == 'verhuur-aanvraag') {
	
	$arr = new stdclass();
	$arr->item = $_POST['ovis-contact-object'];
	$arr->errors = array();
	
	if(empty($_POST['ovis-contact-object'])) {
		$arr->status = 'error';
		$arr->errors['object'] = true;
	} else {
		
		if(!empty($_POST['ovis-contact-email'])) {
			$arr->status = 'error';
			$arr->errors['captcha'] = true;
		}
		if(empty($_POST['ovis-contact-periodevan'])) {
			$arr->errors['periodevan'] = true;
		}
		if(empty($_POST['ovis-contact-periodetot'])) {
			$arr->errors['periodetot'] = true;
		}
		if(empty($_POST['ovis-contact-name'])) {
			$arr->errors['name'] = true;
		}
		if(empty($_POST['ovis-contact-adres'])) {
			$arr->errors['adres'] = true;
		}
		if(empty($_POST['ovis-contact-housenumber'])) {
			$arr->errors['housenumber'] = true;
		}
		if(empty($_POST['ovis-contact-zipcode'])) {
			$arr->errors['zipcode'] = true;
		}
		if(empty($_POST['ovis-contact-city'])) {
			$arr->errors['city'] = true;
		}
		if(empty($_POST['ovis-contact-phone'])) {
			$arr->errors['phone'] = true;
		}
		if(empty($_POST['ovis-contact-contactperson']) || !is_email($_POST['ovis-contact-contactperson'])) {
			$arr->errors['sender'] = true;
		}
		
		if(empty($arr->errors)) {
			$arr->status = 'succes';
		} else {
			$arr->status = 'error';
		}
	}
	
	if($arr->status == 'succes') {
		
		require_once(plugin_dir_path(__FILE__) . '../classes/class.contact.php');
		$oContact = new contact($sSettings);
		$oContact->postRentalRequest($_POST);

		if($oContact->bPostError && !empty($oContact->aPostErrors)) {
			$arr->status = 'error';

			foreach($oContact->aPostErrors as $sErrorKey => $sError) {
				
				switch($sErrorKey) {
					case 'missing-field-category':
					case 'unknown-category':
						$arr->errors['soort'] = true;
						break;
					case 'missing-field-email':
					case 'invalid-format-email':
						$arr->errors['sender'] = true;
						break;
					case 'missing-field-phonenumber':
						$arr->errors['phone'] = true;
						break;
					case 'invalid-format-numberofpersons':
						$arr->errors['persons'] = true;
						break;
					case 'missing-field-name':
						$arr->errors['name'] = true;
						break;
					default:
						$arr->errors['general'][] = $sErrorKey;
						break;
				}
			}
		}
	}
	
	header('Content-Type: application/json');
	echo json_encode($arr);
	wp_die();
}
	
/* parse trade-in-request */
if($aSettings["form_action"] == 'inruil-voorstel') {
	
	$arr = new stdclass();
	$arr->item = $_POST['ovis-contact-object'];
	$arr->errors = array();
	
	if(empty($_POST['ovis-contact-object'])) {
		$arr->status = 'error';
		$arr->errors['object'] = true;
	} else {
		
		if(!empty($_POST['ovis-contact-email'])) {
			$arr->status = 'error';
			$arr->errors['captcha'] = true;
		}
		
		if(empty($_POST['ovis-contact-soort']) || $_POST['ovis-contact-soort'] == 'nb') {
			$arr->errors['soort'] = true;
		}
		if(empty($_POST['ovis-contact-name'])) {
			$arr->errors['name'] = true;
		}
		if(empty($_POST['ovis-contact-contactperson']) || !is_email($_POST['ovis-contact-contactperson'])) {
			$arr->errors['sender'] = true;
		}
		if(empty($_POST['ovis-contact-phone'])) {
			$arr->errors['phone'] = true;
		}			
		if(empty($_POST['ovis-contact-merk'])) {
			$arr->errors['merk'] = true;
		}
		if(empty($_POST['ovis-contact-model'])) {
			$arr->errors['model'] = true;
		}
		if(empty($_POST['ovis-contact-bouwjaar']) || $_POST['ovis-contact-bouwjaar'] == 'nb') {
			$arr->errors['bouwjaar'] = true;
		}
		if(empty($_POST['ovis-contact-conditie']) || $_POST['ovis-contact-conditie'] == 'nb') {
			$arr->errors['conditie'] = true;
		}
		if(empty($_POST['ovis-contact-schade']) || $_POST['ovis-contact-schade'] == 'nb') {
			$arr->errors['schade'] = true;
		}
		if(empty($_POST['ovis-contact-staatbekleding']) || $_POST['ovis-contact-staatbekleding'] == 'nb') {
			$arr->errors['staatbekleding'] = true;
		}
		if(empty($_POST['ovis-contact-staatbanden']) || $_POST['ovis-contact-staatbanden'] == 'nb') {
			$arr->errors['staatbanden'] = true;
		}
		
		if((!empty($_POST['ovis-contact-soort']) && $_POST['ovis-contact-soort'] == 'kampeerauto')) {
			if(empty($_POST['ovis-contact-kenteken'])) {
				$arr->errors['kenteken'] = true;
			}
			if(empty($_POST['ovis-contact-kilometerstand'])) {
				$arr->errors['kilometerstand'] = true;
			}
		}

		if(!empty($_POST['ovis-required-image']) && $_POST['ovis-required-image'] == 'yes' && empty($_POST['file_base64'])) {
			$arr->errors['images'] = true;
		}

		// if( !isset($_POST['file_base64']) || empty($_POST['file_base64']) ) {
		// 	$arr->errors['images'] = true;
		// }


		
		if(empty($arr->errors)) {
			$arr->status = 'succes';
		} else {
			$arr->status = 'error';
		}
	}
	
	/* post to OVIS */
	if($arr->status == 'succes') {
		
		require_once(plugin_dir_path(__FILE__) . '../classes/class.contact.php');
		$oContact = new contact($sSettings);
		$oContact->postTradeinrequestRequest($_POST);
		
		if($oContact->bPostError && !empty($oContact->aPostErrors)) {
			$arr->status = 'error';

			foreach($oContact->aPostErrors as $sErrorKey => $sError) {
				
				switch($sErrorKey) {
					case 'missing-field-category':
					case 'unknown-category':
						$arr->errors['soort'] = true;
						break;
					case 'missing-field-email':
					case 'invalid-format-email':
						$arr->errors['sender'] = true;
						break;
					case 'missing-field-phonenumber':
						$arr->errors['phone'] = true;
						break;
					case 'missing-field-name':
						$arr->errors['name'] = true;
						break;
					default:
						$arr->errors['general'][] = $sErrorKey;
						break;
				}
			}
		}
	}
	
	header('Content-Type: application/json');
	echo json_encode($arr);
	wp_die();
}