<?php
/*
* date last modified 03-10-2017
* Edited by PI-Digi Logical Solutions
* HTML Files - manage_staff.html.php
* Mysql Tables - tbl_admin, tbl_user, tbl_admin_type
*/
require_once('./includes/functions.php'); # general functions

function sendIosTechPush($title, $body, $token, $show_in) {
	
	// Put your device token here (without spaces):
	$deviceToken = str_replace(" ", "", $token);
	// Put your private key's passphrase here:
	$passphrase = 'swaroop';
	//// Put your alert message here:
	$message = $title." - ".$body;

	$ctx = stream_context_create();
	//stream_context_set_option($ctx, 'ssl', 'local_cert', 'CKPdtnTech.pem');
	stream_context_set_option($ctx, 'ssl', 'local_cert', BASE_URI.'ocontrol/includes/ckT.pem');
	stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

	
		//gateway.sandbox.push.apple.com:2195
	/*if($fp = stream_socket_client('ssl://gateway.push.apple.com:2195',
							   $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx)){*/
	if($fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195',
								   $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx)){						   	
		// Create the payload body
		//$push_body['aps'] = array('badge' => +1, 'alert' => $message, 'sound' => 'default');
		//$payload = json_encode($push_body);
		
		$push_body['aps'] = array('badge' => +1, 'alert' => $message, 'sound' => 'default');
		$push_body['open_page'] = "";
		
		$payload = json_encode($push_body);
	
		// Build the binary notification
		$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
		// Send it to the server
		$result = fwrite($fp, $msg, strlen($msg));
		if (!$result) {
	    	//echo 'Message not delivered' . PHP_EOL;
		} else {
	    	//echo 'Message successfully delivered amar'.$message. PHP_EOL;
		}
		// Close the connection to the server
		fclose($fp);
	}	

	
}

function sendGCM($title, $body, $token, $show_in) {

    $url = 'https://fcm.googleapis.com/fcm/send';
	
	$dat = array('show_in' => $show_in);

    $fields = array('registration_ids' => array($token),
					'notification'=>array("body"=>$body, "title"=>$title, "data"=>$dat)
    );
    $fields = json_encode ( $fields );

    $headers = array (
            'Authorization: key=' . FCM_TECH_KEY,
            'Content-Type: application/json'
    );

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

    $result = curl_exec ( $ch );
	
    curl_close ( $ch );
}

$debug = true;

if(isset($_REQUEST['tech_id']) && $_REQUEST['tech_id']!=''){
	$technicianId = trim($_REQUEST['tech_id']);
} else {
	?>
	  <script language="javascript" type="text/javascript">	
	    alert('Something went wrong!');		
		window.location='index.php?page=manage_technician';
	  </script>
	<?php
}

//$latitude = 8.5241391;
//$longitude = 76.9366376;

if(isset($_POST['add'])){
	//print_r($_POST);
	//sunday
	if(isset($_POST['sunday']) && $_POST['sunday']=='on'){
		$sunday = 'on';
		//get slots of the day .delete all entries of day for this user first
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'sunday'");
		//insert new entries
		if(isset($_POST['sunday_time']) && is_array($_POST['sunday_time'])){
			//print_r($_POST['sunday_time']);
			foreach ($_POST['sunday_time'] as $slot) {
				$slotArr = explode('-', $slot);
				$startTime = $slotArr[0];
				$endTime = $slotArr[1];
				mysqli_query($con, "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'sunday', '".$startTime."', '".$endTime."', 'on')");
				//echo "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'sunday', '".$startTime."', '".$endTime."', 'on')";
			}
		} else {
			$error = "Please select atleast one slot for Sunday";
		}
	} else {
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'sunday'");
		//mysqli_query($con, "UPDATE tbl_technician_availability SET status = 'off' WHERE tchnician_id = '".$technicianId."' AND day = 'sunday'");
	}
	//monday
	if(isset($_POST['monday']) && $_POST['monday']=='on'){
		$monday = 'on';
		//get slots of the day .delete all entries of day for this user first
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'monday'");
		//insert new entries
		if(isset($_POST['monday_time']) && is_array($_POST['monday_time'])){
			foreach ($_POST['monday_time'] as $slot) {
				$slotArr = explode('-', $slot);
				$startTime = $slotArr[0];
				$endTime = $slotArr[1];
				mysqli_query($con, "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'monday', '".$startTime."', '".$endTime."', 'on')");
			}
		} else {
			$error = "Please select atleast one slot for Monday";
		}
	} else {
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'monday'");
		//mysqli_query($con, "UPDATE tbl_technician_availability SET status = 'off' WHERE tchnician_id = '".$technicianId."' AND day = 'monday'");
	}
	//tuesday
	if(isset($_POST['tuesday']) && $_POST['tuesday']=='on'){
		$tuesday = 'on';
		//get slots of the day .delete all entries of day for this user first
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'tuesday'");
		//insert new entries
		if(isset($_POST['tuesday_time']) && is_array($_POST['tuesday_time'])){
			foreach ($_POST['tuesday_time'] as $slot) {
				$slotArr = explode('-', $slot);
				$startTime = $slotArr[0];
				$endTime = $slotArr[1];
				mysqli_query($con, "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'tuesday', '".$startTime."', '".$endTime."', 'on')");
			}
		} else {
			$error = "Please select atleast one slot for Tuesday";
		}
	} else {
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'tuesday'");
		//mysqli_query($con, "UPDATE tbl_technician_availability SET status = 'off' WHERE tchnician_id = '".$technicianId."' AND day = 'tuesday'");
	}
	//wednesday
	if(isset($_POST['wednesday']) && $_POST['wednesday']=='on'){
		$wednesday = 'on';
		//get slots of the day .delete all entries of day for this user first
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'wednesday'");
		//insert new entries
		if(isset($_POST['wednesday_time']) && is_array($_POST['wednesday_time'])){
			foreach ($_POST['wednesday_time'] as $slot) {
				$slotArr = explode('-', $slot);
				$startTime = $slotArr[0];
				$endTime = $slotArr[1];
				mysqli_query($con, "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'wednesday', '".$startTime."', '".$endTime."', 'on')");
			}
		} else {
			$error = "Please select atleast one slot for Wednesday";
		}
	} else {
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'wednesday'");
		//mysqli_query($con, "UPDATE tbl_technician_availability SET status = 'off' WHERE tchnician_id = '".$technicianId."' AND day = 'wednesday'");
	}
	//thursday
	if(isset($_POST['thursday']) && $_POST['thursday']=='on'){
		$thursday = 'on';
		//get slots of the day .delete all entries of day for this user first
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'thursday'");
		//insert new entries
		if(isset($_POST['thursday_time']) && is_array($_POST['thursday_time'])){
			foreach ($_POST['thursday_time'] as $slot) {
				$slotArr = explode('-', $slot);
				$startTime = $slotArr[0];
				$endTime = $slotArr[1];
				mysqli_query($con, "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'thursday', '".$startTime."', '".$endTime."', 'on')");
			}
		} else {
			$error = "Please select atleast one slot for Thursday";
		}
	} else {
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'thursday'");
		//mysqli_query($con, "UPDATE tbl_technician_availability SET status = 'off' WHERE tchnician_id = '".$technicianId."' AND day = 'thursday'");
	}
	//friday
	if(isset($_POST['friday']) && $_POST['friday']=='on'){
		$friday = 'on';
		//get slots of the day .delete all entries of day for this user first
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'friday'");
		//insert new entries
		if(isset($_POST['friday_time']) && is_array($_POST['friday_time'])){
			foreach ($_POST['friday_time'] as $slot) {
				$slotArr = explode('-', $slot);
				$startTime = $slotArr[0];
				$endTime = $slotArr[1];
				mysqli_query($con, "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'friday', '".$startTime."', '".$endTime."', 'on')");
			}
		} else {
			$error = "Please select atleast one slot for Friday";
		}
	} else {
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'friday'");
		//mysqli_query($con, "UPDATE tbl_technician_availability SET status = 'off' WHERE tchnician_id = '".$technicianId."' AND day = 'friday'");
	}
	//saturday
	if(isset($_POST['saturday']) && $_POST['saturday']=='on'){
		$saturday = 'on';
		//get slots of the day .delete all entries of day for this user first
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'saturday'");
		//insert new entries
		if(isset($_POST['saturday_time']) && is_array($_POST['saturday_time'])){
			foreach ($_POST['saturday_time'] as $slot) {
				$slotArr = explode('-', $slot);
				$startTime = $slotArr[0];
				$endTime = $slotArr[1];
				mysqli_query($con, "INSERT INTO tbl_technician_availability (technician_id, day, start_time, end_time, status) VALUES ('".$technicianId."', 'saturday', '".$startTime."', '".$endTime."', 'on')");
			}
		} else {
			$error = "Please select atleast one slot for Saturday";
		}
	} else {
		mysqli_query($con, "DELETE FROM tbl_technician_availability WHERE technician_id = '".$technicianId."' AND day = 'saturday'");
		//mysqli_query($con, "UPDATE tbl_technician_availability SET status = 'off' WHERE tchnician_id = '".$technicianId."' AND day = 'saturday'");
	}
	
	
	$exec_token = mysqli_query($con, 'SELECT fcm_token, device FROM tbl_fcm_tokens WHERE tech_id='.$technicianId);
	if(isset($exec_token) && mysqli_num_rows($exec_token)>0) {
		while($res_token = mysqli_fetch_array($exec_token)) {	
			if($res_token['fcm_token']!='') {							
				$title = SITE_NAME;
				$body = 'Hi '.getTechnicianName($technicianId).', your availability details have been updated';
				if($res_token['device']=='android') {								
					sendGCM($title, $body, $res_token['fcm_token'], "tech");
				} else {
					sendIosTechPush($title, $body, $res_token['fcm_token'], "tech");
				}	
				$success = 'Availability details have been updated';			
			}
		}
	}
	
	
	
}


$sundayStat = $mondayStat = $tuesdayStat = $wednesdayStat = $thursdayStat = $fridayStat = $saturdayStat = '';
$start_time_sunday = $start_time_monday = $start_time_tuesday = $start_time_wednesday = $start_time_thursday = $start_time_friday = $start_time_saturday = '';
$end_time_sunday = $end_time_monday = $end_time_tuesday = $end_time_wednesday = $end_time_thursday = $end_time_friday = $end_time_saturday = '';

$availabilityRs = mysqli_query($con, "SELECT * FROM tbl_technician_availability WHERE technician_id = '".$technicianId."'");
if(mysqli_num_rows($availabilityRs)>0){
	$isEdit= true;
	while($availabilityRec = mysqli_fetch_array($availabilityRs)){
		if($availabilityRec['day']=='sunday'){
			$sundayStat = $availabilityRec['status'];
			$start_time_sunday = $availabilityRec['start_time'];
			$end_time_sunday = $availabilityRec['end_time'];
			$editTimeSunday[] = $start_time_sunday.'-'.$end_time_sunday;
		} else if($availabilityRec['day']=='monday'){
			$mondayStat = $availabilityRec['status'];
			$start_time_monday = $availabilityRec['start_time'];
			$end_time_monday = $availabilityRec['end_time'];
			$editTimeMonday[] = $start_time_monday.'-'.$end_time_monday;
		} else if($availabilityRec['day']=='tuesday'){
			$tuesdayStat = $availabilityRec['status'];
			$start_time_tuesday = $availabilityRec['start_time'];
			$end_time_tuesday = $availabilityRec['end_time'];
			$editTimeTuesday[] = $start_time_tuesday.'-'.$end_time_tuesday;
		} else if($availabilityRec['day']=='wednesday'){
			$wednesdayStat = $availabilityRec['status'];
			$start_time_wednesday = $availabilityRec['start_time'];
			$end_time_wednesday = $availabilityRec['end_time'];
			$editTimeWednesday[] = $start_time_wednesday.'-'.$end_time_wednesday;
		} else if($availabilityRec['day']=='thursday'){
			$thursdayStat = $availabilityRec['status'];
			$start_time_thursday = $availabilityRec['start_time'];
			$end_time_thursday = $availabilityRec['end_time'];
			$editTimeThursday[] = $start_time_thursday.'-'.$end_time_thursday;
		} else if($availabilityRec['day']=='friday'){
			$fridayStat = $availabilityRec['status'];
			$start_time_friday = $availabilityRec['start_time'];
			$end_time_friday = $availabilityRec['end_time'];
			$editTimeFriday[] = $start_time_friday.'-'.$end_time_friday;
		} else if($availabilityRec['day']=='saturday'){
			$saturdayStat = $availabilityRec['status'];
			$start_time_saturday = $availabilityRec['start_time'];
			$end_time_saturday = $availabilityRec['end_time'];
			$editTimeSaturday[] = $start_time_saturday.'-'.$end_time_saturday;
		}
	}
}



?>