<?php
add_filter( 'wp_enqueue_scripts', 'my_failed_request_logged_out' );
function my_failed_request_logged_out() {	
	if(page_id() === 222 && isset($_GET["frlo"])) {
		// CHECK IF ALL PARAMETER ARE PRESENT
		if(	isset($_GET['SWITCH_TERMINTYPE']) &&
		   	isset($_GET['SERVICE_ID']) &&
		   	isset($_GET['WOCHENTAG_START']) && 
		   	isset($_GET['UHRZEIT_START']) &&
		   	isset($_GET['WOCHENTAG_END']) && 
		   	isset($_GET['UHRZEIT_END']) &&
		   	isset($_GET['SWITCH_STANDORTE']) && 
		   	isset($_GET['STANDORTE']) &&
		   	isset($_GET['WP_ID']) &&
		   	isset($_GET['event']) )
		{						
			// PRINT PARAMETER
			foreach ($_GET as $k=>$v) {
				php_console_log('k: ' . $k . ' v: ' . $v);
			}
			
			// DIENSTLEISTUNG
			$wpdb = connect_to_server('zinomedia');
			$dienstleistung = $wpdb->get_var('SELECT NAME FROM services WHERE ID = ' . $_GET['SERVICE_ID']);
			php_console_log('Dienstleistung: ' . $dienstleistung );			

			// DATETIMES
			if (isset($_GET['SWITCH_TERMINTYPE']) && $_GET['SWITCH_TERMINTYPE'] == 'zeitraum') {
				$datetime_from = create_date($_GET['WOCHENTAG_START'], $_GET['UHRZEIT_START']);
				$datetime_to = create_date($_GET['WOCHENTAG_END'], $_GET['UHRZEIT_END']);
			}
			else if (isset($_GET['SWITCH_TERMINTYPE']) && $_GET['SWITCH_TERMINTYPE'] == 'sofort') {
				$timestamp = time();
				$dt = new DateTime("now", new DateTimeZone('Europe/Berlin'));
				$dt->setTimestamp($timestamp);
				$datetime_from = $dt->format('Y-m-d H:i:s');
				$datetime_to = create_date($_GET['WOCHENTAG_END'], $_GET['UHRZEIT_END']);
			}
			
			// BUERGERAEMTER			
			$buergeraemter = create_buergeraemter();				
			
			// CREATE APPOINTMENT
			php_console_log('datetime_from after: ' . $datetime_from);
			php_console_log('datetime_to after: ' . $datetime_to);
			$data = array( 
				'category' => 'request-failed-logged-out',
				'request' => array(
									'BUERGERAEMTER'   	=> $buergeraemter,
									'WP_ID'	=> $_GET['WP_ID'],																	
									'SERVICE_ID' => $_GET['SERVICE_ID'],
									'DIENSTLEISTUNG' => $dienstleistung,
									'DATETIME_FROM' => $datetime_from,
									'DATETIME_TO' => $datetime_to,
				),
			);
			$post_content = create_post_content($data);
			$post_content = trim(preg_replace('/\s+/', ' ', $post_content));
			
			// PUT APPOINTMENT ON PAGE
			js_manipulate_html($post_content);
		}
		else {
			php_console_log('Not all GET data present');
			close_modal();
		}		
	}
}

function close_modal() {	
	?>
		<script>
		// START JAVASCRIPT		
		document.addEventListener("DOMContentLoaded", function(event) {					
			jQuery('.uabb-close-icon').ready(function() {
				jQuery('.uabb-close-icon').click();	
			});
		});
		// END JAVASCRIPT
		</script>
	<?php
}

function create_buergeraemter() {
	$wpdb = connect_to_server('zinomedia');
	
	// SWITCH berlinweit OR standorte-auswaehlen
	if (isset($_GET['SWITCH_STANDORTE']) && $_GET['SWITCH_STANDORTE'] == 'berlinweit') {
		// GET VENUE NAMES FROM DB
		$rows = $wpdb->get_results(	"
									Select
										venues.NAME
									From
										services Inner Join
										mapping_services On mapping_services.SERVICE_ID = services.ID Inner Join
										venues On mapping_services.VENUE_ID = venues.ID
									Where
										services.ID = $_GET[SERVICE_ID]
									", ARRAY_N );
		
		// ACCUMULATE TO ONE ARRAY
		$buergeraemter = array();
		foreach ($rows as $array) {
			array_push($buergeraemter, $array[0]);
		}
	}
	else if (isset($_GET['SWITCH_STANDORTE']) && $_GET['SWITCH_STANDORTE'] == 'standorte-auswaehlen') {
		// CREATE ARRAY WITH VENUE_IDs FROM STRING
		$buergeraemter_get = explode(',',$_GET['STANDORTE']);
		
		// CREATE SQL QUERY STRING WITH VENUE IDs
		$i = 0;
		$len = count($buergeraemter_get);
		foreach ($buergeraemter_get as $venue_id) {
			$venue_query .= 'venues.ID = ' . $venue_id;
			if ($i !== $len - 1) {
				// last
				$venue_query .=  ' Or ';
			}
			$i++;
		}
		
		// GET VENUE NAMES FROM DB
		$rows = $wpdb->get_results(	"
									Select venues.NAME From venues Where ($venue_query)
									", ARRAY_N );

		// ACCUMULATE TO ONE ARRAY
		$buergeraemter = array();
		foreach ($rows as $array) {
			array_push($buergeraemter, $array[0]);
		}
	}
	
	return $buergeraemter;
}

function create_date($day, $time) {
	$datetime = $day . ' ' . $time;		
	if (strpos($time, '-') !== false) {
		$format = 'Y-m-d H-i';
	}
	else {
		$format = 'Y-m-d H';	
	}			
	$datetime = DateTime::createFromFormat($format, $datetime);
	$datetime = $datetime->format('Y-m-d H:i:s');
	
	return $datetime;
}

function js_manipulate_html($post_content) {	
	?>
		<script>
		// START JAVASCRIPT		
		document.addEventListener("DOMContentLoaded", function(event) {
			jQuery('#dein-termin .fl-html')[0].innerHTML = '<?php echo $post_content ?>';		
			
			// JQUERY FOR APPOINTMENT
			var maxRows = 5;
			jQuery('.paginated-table').each(function () {
				var cTable = jQuery(this);
				var cRows = cTable.find('tr:gt(0)');
				var cRowCount = cRows.size();

				if (cRowCount > 10) {
					jQuery(".paginated-table-div").css({"height": "260px"});
				}
				else if (cRowCount <= 10) {
					jQuery(".prev-table,.next-table").hide();
				}

				if (cRowCount < maxRows) {
					return;
				}

				cRows.each(function (i) {
					jQuery(this).find('td:first').text(function (j, val) {
						return (i + 1) + " - " + val;
					});
				});

				cRows.filter(':gt(' + (maxRows - 1) + ')').hide();

				var cPrev = jQuery('.prev-table');
				var cNext = jQuery('.next-table');

				cPrev.addClass('disabled');

				cPrev.click(function () {
					console.log('prev clicked');
					var cFirstVisible = cRows.index(cRows.filter(':visible'));

					if (cPrev.hasClass('disabled')) {
						return false;
					}

					cRows.hide();
					if (cFirstVisible - maxRows - 1 > 0) {
						cRows.filter(':lt(' + cFirstVisible + '):gt(' + (cFirstVisible - maxRows - 1) + ')').show();
					} else {
						cRows.filter(':lt(' + cFirstVisible + ')').show();
					}

					if (cFirstVisible - maxRows <= 0) {
						cPrev.addClass('disabled');
					}

					cNext.removeClass('disabled');

					return false;
				});

				cNext.click(function () {
					var cFirstVisible = cRows.index(cRows.filter(':visible'));

					if (cNext.hasClass('disabled')) {
						return false;
					}

					cRows.hide();
					cRows.filter(':lt(' + (cFirstVisible + 2 * maxRows) + '):gt(' + (cFirstVisible + maxRows - 1) + ')').show();

					if (cFirstVisible + 2 * maxRows >= cRows.size()) {
						cNext.addClass('disabled');
					}

					cPrev.removeClass('disabled');

					return false;
				});

			});
			
		});
		// END JAVASCRIPT
		</script>
	<?php
}