<?php
add_filter( 'wp_enqueue_scripts', 'pre_menu_indicator' );

function pre_menu_indicator() {	
	if (is_menu_page()) {		
		$menu_mapping = array(	'requests' => 984,
								'expired' => 983,
								'appointment' => 1812,
		);
		
		$user = wp_get_current_user();
		$rows = db_count_snipes($user);
		
		// APPOINTMENTS_OLD TO COMPARE	
		$appointments_old = get_user_meta( $user->ID, 'appointments_old', true );
		php_console_log('appointments_old: ' . $appointments_old);
		
		foreach ($menu_mapping as $category => $menu_id) {
			$indicator = $rows[0][$category];
			
			// NEW APPOINTMENT MODAL CHECK
			if ($category === 'appointment') {				
				// NEW APPOINTMENT?
				if ($indicator > $appointments_old) {
					php_console_log('We have a new appointment');
					
					// SAVE NUMBER OF APPOINTMENTS
					update_user_meta( $user->ID, 'appointments_old', $indicator );
					
					// NEW APPOINTMENT MODAL
					redirect('http://zinomedia.de/terminsnipe/?fa=1');
				}
				else {
					php_console_log('No new appointment');
					
					// SAVE NUMBER OF APPOINTMENTS
					update_user_meta( $user->ID, 'appointments_old', $indicator );
				}
			}
			
			append_indicator($menu_id, $indicator);
		}
	}
}

function db_count_snipes($user) {
	$wpdb = connect_to_server('zinomedia');
	$rows = $wpdb->get_results(	"
								SELECT
									  (
									   SELECT
											 COUNT(*)
									   FROM
										   reg_users
										   INNER JOIN request ON request.USER_ID = reg_users.ID
									   WHERE
											reg_users.WP_ID = $user->ID AND
											request.EXPIRED = 0
									  ) AS requests,
									  (
									   SELECT
											 COUNT(*)
									   FROM
										   reg_users
										   INNER JOIN request ON request.USER_ID = reg_users.ID
									   WHERE
											reg_users.WP_ID = $user->ID AND
											request.EXPIRED = 1
									  ) AS expired,
									  (
									   SELECT
											 COUNT(*)
									   FROM
										   reg_users
										   INNER JOIN appointments ON appointments.USER_ID = reg_users.ID
									   WHERE
											reg_users.WP_ID = $user->ID
									  ) AS appointment
								", ARRAY_A );	
	return $rows;
}

function append_indicator($menu_id, $indicator) {
	?>			
	<script>
	// START JAVASCRIPT
		document.addEventListener("DOMContentLoaded", function(event) {
			var a = '#menu-item-' + "<?php echo $menu_id ?>" + ' a';
			if (typeof a !== "undefined") {
				var icon = jQuery(a + ' span i')[0].outerHTML;			
				var text = jQuery(a).text();
				jQuery(a + ' span')[0].innerHTML = icon + text + ' (' + "<?php echo $indicator ?>" + ')';
			}
		});
	// END JAVASCRIPT
	</script>				
	<?php
}