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

if(isset($_POST['clear'])) { ?>
<script language="javascript" type="text/javascript">			
	window.location='index.php?page=<?php echo $page;?>';
</script>
<?php }

$departmentRs = mysqli_query($con, "SELECT DISTINCT department FROM tbl_ivrs WHERE department!= '' ORDER BY department");

//run the API
$curDate = date('Y-m-d H:i:s');
$currentDate = strtotime($curDate);
$pastTime = $currentDate-(60*10); //seconds
//echo $pastTime;

	$data = array("token" => "6206af1eb1d0b1edde4c28d74774f7b2","from" => $pastTime);      
	//$data = array("token" => "6206af1eb1d0b1edde4c28d74774f7b2");                                                               
	$data_string = json_encode($data); 
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,            "https://developers.myoperator.co/search" );
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt($ch, CURLOPT_POST,           1 );
	curl_setopt($ch, CURLOPT_POSTFIELDS,     $data_string ); 
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
	    'Content-Type: application/json',                                                                                
	    'Content-Length: ' . strlen($data_string))                                                                       
	);	
	$result=curl_exec ($ch);
	$result = json_decode($result);
	if($_SERVER['REMOTE_ADDR']=='202.88.237.77'){
	//print_r($result);
	//echo $result->status;
	//$result->data->hits;
	}
	foreach ($result->data->hits as $hits) {
		$callerId = $hits->user_id;		
		$mobileNumber = $hits->_source->caller_number_raw;
		if(isset($hits->_source->department_name)){
			$department = $hits->_source->department_name;
		} else { $department  = ''; }		
		$callEndTime = $hits->_source->start_time;
		//if(strlen($department)>0){
			//check for duplicate
			$chkRs = mysqli_query($con, "SELECT id FROM tbl_ivrs WHERE caller_id = '".$callerId."'");
			if(mysqli_num_rows($chkRs)>0){
				//already exists
			} else {
				$userType = '';
				$userId = 0;
				//check if a registered user
				$chkUserRs = mysqli_query($con, "SELECT id FROM tbl_user WHERE phone = '".$mobileNumber."'");
				if(mysqli_num_rows($chkUserRs)>0){
					$chkUserRec = mysqli_fetch_array($chkUserRs);
					$userType = 'U';
					$userId = $chkUserRec['id'];
				} else {
					//check if a partner
					$chkUserRs = mysqli_query($con, "SELECT id FROM tbl_purchase_partner WHERE (phone = '".$mobileNumber."' OR mobile = '".$mobileNumber."')");
					if(mysqli_num_rows($chkUserRs)>0){
						$chkUserRec = mysqli_fetch_array($chkUserRs);
						$userType = 'P';
						$userId = $chkUserRec['id'];
					} else {
						//check if a technician
						$chkUserRs = mysqli_query($con, "SELECT id FROM tbl_technician WHERE (phone = '".$mobileNumber."' OR mobile2 = '".$mobileNumber."')");
						if(mysqli_num_rows($chkUserRs)>0){
							$chkUserRec = mysqli_fetch_array($chkUserRs);
							$userType = 'T';
							$userId = $chkUserRec['id'];
						}
					}
				}
				
				mysqli_query($con, "INSERT INTO tbl_ivrs (caller_id, mobile, user_type, user_id, department, time) VALUES ('".$callerId."', '".$mobileNumber."', '".$userType."', '".$userId."', '".$department."', '".$callEndTime."')");
			}			
		//}
	}


//--------------------

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

if(isset($_GET['action']) && $_GET['action'] == 'processed') {
	/* Delete User */
	if(isset($_GET['id']) && $_GET['id']!=''){
		$update = mysqli_query($con,"UPDATE tbl_ivrs SET `status` = 'Processed' WHERE id='".$_GET['id']."'");
		if($update) {
			$success = 'Processed the call';
			?>
	        <script language="javascript" type="text/javascript">			
				window.location='index.php?page=<?php echo $page;?>&success=<?php echo $success; ?>';
			</script>
	        <?php
		}
	}
}

if(isset($_GET['action']) && $_GET['action'] == 'delete') {
	/* Delete User */
	if(isset($_GET['del_id']) && $_GET['del_id']!=''){
		$delete = mysqli_query($con,'DELETE FROM tbl_ivrs WHERE id='.$_GET['del_id']);
		if($delete) {
			$success = 'Deleted the call';
			?>
	        <script language="javascript" type="text/javascript">			
				window.location='index.php?page=<?php echo $page;?>&success=<?php echo $success; ?>';
			</script>
	        <?php
		}
	}
}

$pageVars = '';

// Get All User details to list 
$where = ' id>0 ';

if(isset($_REQUEST['department']) && strlen($_REQUEST['department'])>0) {
	$department = trim($_REQUEST['department']);
	$where.= " AND department = '".$department."' ";
	$pageVars.= "&department=".$department.'&';
}	


$select = "SELECT * FROM tbl_ivrs WHERE ".$where." ORDER BY id DESC";
//echo $select;
// Using pagination class
$pagination = new pagination_noseo($select);
$execDetails = $pagination->createPages(30);

$pageLnk = 'index.php?page='.$page.'&'.$pageVars;
$pageNums = $pagination->pageNumber(5, $pageLnk);
?>