<?php
/*
* date last modified 28-11-2017
* Edited by PI-Digi Logical Solutions
* HTML Files - add_user.html.php
* Mysql Tables - tbl_designation, tbl_user
*/
include_once('PHPMailer/class.phpmailer.php');
require_once('./classes/class.noseo_pagination.php'); # pagination class
include('includes/functions.php'); # general functions
//require_once('includes/push_functions.php');
//require_once('../webservice/chat_functions.php');

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', BASE_URI.'webservice/ck.pem');
	stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

	
		//gateway.sandbox.push.apple.com:2195
		
	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);
	
		// 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_user1($title, $body, $token, $task_id, $from, $user_id, $user_name, $tech_id, $tech_name) {
		
	$url = 'https://fcm.googleapis.com/fcm/send';
	
	$dat = array('title'=>$title,
				 'body'=>$body,
				 'open_page'=>$from,
				 'task_id'=>$task_id,
				 'user_id'=>$user_id,
				 'user_name'=>$user_name,
				 'tech_id'=>$tech_id,
				 'tech_name'=>$tech_name,
				 'sound'=>'default');	
	
    $fields = array('to' => $token,					
					'data' => $dat);
		

//	$fields = array('registration_ids' => array($token),
//					'data' => $dat);
	
	$fields = json_encode ($fields);	
	
   	$headers = array (
            'Authorization: key=' . FCM_USER_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);
//	echo '<pre>';
//    print_r($result);
//	exit;
    curl_close ($ch);
}


$adminId = $_SESSION['adminId'];
$debug = true;

if(isset($_REQUEST['p']) && $_REQUEST['p']!=''){
	$p = trim($_REQUEST['p']);
} else {
	$p = 1;
}

$pageVars = '';

$categoryRs = mysqli_query($con, "SELECT * FROM tbl_service_categories WHERE parent_id = '0'");


if(isset($_REQUEST['id']) && $_REQUEST['id']!=''){		
	$editId = mysqli_real_escape_string($con, trim($_REQUEST['id']));	
	
	if(isset($_POST['submit'])){
		
		if(isset($_POST['stat_description']) && $_POST['stat_description']!=''){
			$statDescription = trim($_POST['stat_description']);
		} else {
			$statDescription = '';
		}
		
		if(isset($_POST['status']) && $_POST['status']!=''){
			$status = trim($_POST['status']);
			if(strlen($status)>20){
				$error = 'Sorry, status text should not exceed 20 chars';
			}
		} else {
			$error = 'Please enter status';
		}
		
		
		if(empty($error)){
			//insert status
			$curDate = date('Y-m-d H:i:s');
			$insert = mysqli_query($con, "INSERT INTO tbl_task_project_status (task_id, description, status, date, added_by) VALUES ('".$editId."', '".$statDescription."', '".$status."', '".$curDate."', '".$adminId."')");
			if($insert){
				//update project status in task table
				mysqli_query($con, "UPDATE tbl_job SET status = '".$status."' WHERE id = '".$editId."'");
				
				//get user
				$projRec = mysqli_fetch_array(mysqli_query($con, "SELECT user_id FROM tbl_job WHERE id = '".$editId."'"));
				$userId = $projRec['user_id'];
				$userName = getUserName($userId);
				
				//send push	to user			
				$exec_token = mysqli_query($con, 'SELECT fcm_token, device FROM tbl_fcm_tokens WHERE user_id='.$userId);
				if(isset($exec_token) && mysqli_num_rows($exec_token)>0) {
					while($res_token = mysqli_fetch_array($exec_token)) {
						if($res_token['fcm_token']!='') {
							$title = 'Updated status of project #'.$editId;
							$body = 'Status: '.$status;
							if($res_token['device']=='android') {		
//								sendGCM($title, $body, $res_token['fcm_token'], "user", $editId, $userId, $userName, "task");
								sendGCM_user1($title, $body, $res_token['fcm_token'], $editId, "task", $userId, $userName, "", "");
								
								
							} elseif($res_token['device']=='ios') {
								sendIosTechPush($title, $body, $res_token['fcm_token'], "user");
							}
						}
					}
				}
				
				
				$success = 'The project status has been updated';				
				header('Location:index.php?page=view_task_project&id='.$editId.'&p='.$p.'&success='.$success);
				exit();				
			} else {
				$error = 'Something went wrong!';
			}			
		}		
	}	
	
	$editRs = mysqli_query($con, "SELECT * FROM tbl_job WHERE id = '".$editId."'");
	if(mysqli_num_rows($editRs)>0){
		$resEdit = mysqli_fetch_array($editRs);		
		
		//get all statuses if any
		$statRs = mysqli_query($con, "SELECT * FROM tbl_task_project_status WHERE task_id = '".$editId."'");
		
								
	} else {
		header('Location:index.php?page=manage_user_tasks');
		exit();		
	}

}   

?>