<?php
require_once('../../config/config.inc.php');
require(DB);
include_once('../PHPMailer/class.phpmailer.php');
include('../includes/functions.php');
require_once('../includes/push_functions.php');
session_start();

//assign admin to leads
if(isset($_REQUEST['action']) && $_REQUEST['action']=='set_assignee') {
	$adminId = $_REQUEST['admin_id'];
	$leadsId = $_REQUEST['leads_id'];	
	$assignedBy = $_SESSION['adminId'];
	if($adminId!='' && $leadsId!=''){
		$update = mysqli_query($con, "UPDATE tbl_new_leads SET assignee = '".$adminId."', assigned_by = '".$assignedBy."' WHERE id = '".$leadsId."'");
		if($update){
			$assignorAdminName = getAdminUserName($assignedBy);
			$assignedAdminName = getAdminUserName($adminId);
			$curDate = date('Y-m-d');
			$currentDateTime = date('Y-m-d H:i:s');
			$curTime = date('h:i A', strtotime($currentDateTime));			
			$note = $assignorAdminName.' assigned '.$assignedAdminName.' on '.getFormattedDateRet($curDate).' at '.$curTime;
			mysqli_query($con, "INSERT INTO tbl_leads_notes (leads_id, note, date, added_by) VALUES ('".$leadsId."', '".$note."', '".$curDate."', '".$assignedBy."')");
			echo 'success';
		} else {
			echo 'Something went wrong!';
		}
	} else {
		echo 'Something went wrong!';
	}			
}

//technician mark paid
if(isset($_REQUEST['action']) && $_REQUEST['action']=='tech_mark_paid') {
	$techId = $_REQUEST['tech_id'];
	$amount = $_REQUEST['amount'];	
	if($techId!='' && $amount!='' && is_numeric($amount)){
		$curDate = date('Y-m-d H:i:s');
		$incDate = date('Y-m-d');
		$adminId = $_SESSION['adminId'];
		//insert the amount
		$insert = mysqli_query($con, "INSERT INTO tbl_technician_paid (technician_id, amount, date, added_by) VALUES ('".$techId."', '".$amount."', '".$curDate."', '".$adminId."')");		
		if($insert){
			//make the tech as paid
			mysqli_query($con, "UPDATE tbl_technician SET is_paid = 'yes' WHERE id = '".$techId."'");
			
			//insert in to income table
			mysqli_query($con, "INSERT INTO tbl_incomes (cat_id, amount, inc_date, date, added_by) VALUES ('2', '".$amount."', '".$incDate."', '".$curDate."', '".$adminId."')");		
			
			//send sms to tech
			$techRec = mysqli_fetch_array(mysqli_query($con, "SELECT name, phone FROM tbl_technician WHERE id = '".$techId."'"));
			$techName = $techRec['name'];
			$techPhone = $techRec['phone'];
			$smsMessage = urlencode('Hi '.$techName.', we received a payment of Rs.'.$amount.' from you. Thank you.');	
			if(sendSMSP($techPhone, $smsMessage)){							
				//ok
			} else {
				mail($contact_email, 'SMS API Error','SMS API failed to send in lcontrol/ajax/tech_mark_paid, tech phone:'.$techPhone.', Error-'.$error);			
			}						
			echo 'success';
		} else {
			echo 'Unable to submit the payment!';
		}
	} else {
		echo 'Something went wrong!';
	}			
}

//shop mark paid
if(isset($_REQUEST['action']) && $_REQUEST['action']=='shop_mark_paid') {
	$shopId = $_REQUEST['shop_id'];
	$amount = $_REQUEST['amount'];	
	if($shopId!='' && $amount!='' && is_numeric($amount)){
		$curDate = date('Y-m-d H:i:s');
		$incDate = date('Y-m-d');
		$adminId = $_SESSION['adminId'];
		//insert the amount
		$insert = mysqli_query($con, "INSERT INTO tbl_shop_paid (shop_id, amount, date, added_by) VALUES ('".$shopId."', '".$amount."', '".$curDate."', '".$adminId."')");		
		if($insert){
			//make the shop as paid
			mysqli_query($con, "UPDATE tbl_purchase_partner SET is_paid = 'yes' WHERE id = '".$shopId."'");
			
			//insert in to income table
			mysqli_query($con, "INSERT INTO tbl_incomes (cat_id, amount, inc_date, date, added_by) VALUES ('3', '".$amount."', '".$incDate."', '".$curDate."', '".$adminId."')");		
			
			//send sms to purchase partner
			$ppRec = mysqli_fetch_array(mysqli_query($con, "SELECT name, mobile FROM tbl_purchase_partner WHERE id = '".$shopId."'"));
			$ppName = $ppRec['name'];
			$ppPhone = $ppRec['mobile'];
			if($ppPhone!=''){
				$smsMessage = urlencode('Hi '.$ppName.', we received a payment of Rs.'.$amount.' from you. Thank you.');
				if(sendSMSP($ppPhone, $smsMessage)){							
					//ok
				} else {
					mail($contact_email, 'SMS API Error','SMS API failed to send in lcontrol/ajax/tech_mark_paid, tech phone:'.$ppPhone);			
				}				
			}	
			
			echo 'success';
		} else {
			echo 'Unable to submit the payment!';
		}
	} else {
		echo 'Something went wrong!';
	}			
}

//assign task slot to tech
if(isset($_REQUEST['action']) && $_REQUEST['action']=='assign_task_slot') {
	$taskId = $_REQUEST['task_id'];
	$slot_tech = $_REQUEST['slot_tech'];
	if(strlen($slot_tech)>0){
		$slotVal = explode('-',$slot_tech);
		$slotHr = $slotVal[0];	
		$techId = $slotVal[1];
		$amPm = 'AM';
		$hrAmPm = $hrAmPm2 = 0;
		$slotString = '';
		if($taskId!='' && $slotHr!='' && $techId!=''){
			//check if any slot already assigned to the technician
			$chkRec = mysqli_fetch_array(mysqli_query($con, "SELECT admin_slot, place FROM tbl_job WHERE id = '".$taskId."'"));
			if($chkRec['admin_slot']!='00:00:00'){
				echo '<span style="color:red;">Sorry, already assigned a slot!</span>';
			} else {
				//assign tech in job and send a mail regarding the time slot alloted to him
				//find operator in the location
				$operatorId = '';
				if($chkRec['place']!=''){
					$taskPlace = $chkRec['place'];
					$operatorRs = mysqli_query($con, "SELECT operator_id FROM tbl_operator_locations WHERE place = '".$taskPlace."' ORDER BY id DESC LIMIT 1");
					if(mysqli_num_rows($operatorRs)>0){
						$operatorRec = mysqli_fetch_array($operatorRs);
						$operatorId = $operatorRec['operator_id'];
					}
				}
				$slotDb = $slotHr.':00:00';
				$timestamp = strtotime($slotDb);
				$slotDb = date('H:i:s', $timestamp);
				//$slotDbTo = ($slotHr+2).'00:00';
				$timestamp = strtotime($slotDb)+(60*120); //add two hours
				$slotDbTo = date('H:i:s', $timestamp);
				$update = mysqli_query($con, "UPDATE tbl_job SET technician_id = '".$techId."', operator_id = '".$operatorId."', status = 'assigned', admin_slot = '".$slotDb."', admin_slot_to = '".$slotDbTo."' WHERE id = '".$taskId."'");
				if($update){
				//get user and tech details
					$taskRec = mysqli_fetch_array(mysqli_query($con, "SELECT user_id, task_date FROM tbl_job WHERE id = '".$taskId."'"));
					$userName = getUserName($taskRec['user_id']);
					$taskDate = getFormattedDateRet($taskRec['task_date']);
					
					if($slotHr>12){
						$hrAmPm = $slotHr-12;
						$hrAmPm .= ' PM';
						$hrAmPm2 = ($hrAmPm+2).' PM';					
					} else if($slotHr==12){					
						$hrAmPm = '12 PM';
						$hrAmPm2 = '2 PM';
					} else if($slotHr==0){					
						$hrAmPm = '12 AM';
						$hrAmPm2 = '2 AM';
					} else {
						$hrAmPm = $slotHr;
						$hrAmPm .= ' AM';
						if($slotHr==11){
							$hrAmPm2 = ($hrAmPm+2).' PM';	
						} else {
							$hrAmPm2 = ($hrAmPm+2).' AM';
						}						
					}
					
					$techRec = mysqli_fetch_array(mysqli_query($con, "SELECT name, email, phone FROM tbl_technician WHERE id = '".$techId."'"));
					$techName = $techRec['name'];
					$techEmail = $techRec['email'];
					$techPhone = $techRec['phone'];
					
					//send mail to technician
					//get from email address
					$settingsRec = mysqli_fetch_array(mysqli_query($con, "SELECT from_email FROM tbl_settings WHERE id = '1'"));
					$fromEmail = $settingsRec['from_email'];
					$mail = new PHPMailer();
					$mail->From = $fromEmail;
					$mail->FromName = SITE_NAME;
					$mail->IsHTML(true);	
					$mail->Subject = SITE_NAME.' New task';	
			
					
					$mail->AddAddress($techEmail, $techName);		
					//$mail->AddAddress('renjith@pi-digi.com', $techName);			
					//$to_name = $name;			
			
							$email_content = '<table width="600" border="0" align="center" cellpadding="0" cellspacing="0">
						  <tr>
							<td height="68" align="left" valign="top"><a href="'.BASE_URL.'" target="_blank"><img src="'.BASE_URL.'images/logo.png" /></a></td>
							<td align="right" valign="bottom" style="color:#ff8d07;">&nbsp;</td>
						  </tr>
						   <tr>
							<td height="5" colspan="2" align="left" valign="top"></td>
						  </tr>
						  <tr>
							<td height="49" colspan="2" align="left" valign="top" bgcolor="#970198" style="padding:10px 0px 0px 20px; color:#FFFFFF; font-size:24px; font-family:Times New Roman, Times,   serif;">New task from user</td>
						  </tr>
						  <tr>
							<td colspan="2" align="left" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0" style="border:#970198 solid 1px;">
							  <tr>
								<td height="4" colspan="4" align="left" valign="top" bgcolor="#970198"></td>
							  </tr>
							  <tr>
								<td height="8" colspan="4" align="left" valign="top"></td>
							  </tr>
								<tr>
								<td width="258" align="left" valign="top" style="color:#4e4e4e; font-size:13px; line-height:16px; padding:0px 0px 0px 9px;">Hello  '. $techName .',</td>
							  </tr>
								  <tr>
									<td height="8" align="left" valign="top" style="color:#4e4e4e; font-size:11px;  padding:0px 0px 0px 9px;"></td>
								</tr>
							  <tr>
								<td height="10" colspan="4" align="left" valign="top"></td>
							  </tr>
							  <tr>
								<td colspan="4" align="left" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
								  <tr>
									<td width="8" align="left" valign="top">&nbsp;</td>
									<td width="581" height="140" align="left" valign="top" bgcolor="#f0f0f0" style="border:#c9ccc5 solid 1px; line-height:18px; padding:10px 0px 0px 8px; font-size:11px; font-weight:normal; line-height:27px;">
										<p></p>
										<p><b>'.SITE_NAME.' assigned you in a task from the user '.$userName.'<b></p>
										<p>Task ID: #'.$taskId.'</p>
										<p>Task Date: '.$taskDate.'</p>
										<p>Task Slot: '.$hrAmPm.' to '.$hrAmPm2.'</p>
										<p></p>
										<p></p>
										<p></p>
									  </td>
									<td width="7" align="left" valign="top">&nbsp;</td>
								  </tr>
								</table></td>
							  </tr><tr>
								<td colspan="4" align="left" valign="top">&nbsp;</td>
							  </tr>
							</table></td>
						  </tr>
						</table>';
					$mail->Body = $email_content;
					$mail->Send();	
					
					//echo '<span style="color:green;">Assigned the technician in to the task</span>';
					echo 'success';
					
					//send push to tech			
					$exec_token = mysqli_query($con, 'SELECT fcm_token, device FROM tbl_fcm_tokens WHERE tech_id='.$techId);
					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.' assigned you in a task from the user '.$userName;
								$body = 'Task ID: #'.$taskId.', Task Date: '.$taskDate.', Task Slot: '.$hrAmPm.' to '.$hrAmPm2;
								if($res_token['device']=='android') {																
									sendGCM($title, $body, $res_token['fcm_token'], "tech", $taskId, $taskRec['user_id'], $userName, "task");
								} elseif($res_token['device']=='ios') {
									//sendIosTechPush($title, $body, $res_token['fcm_token'], "tech");
									sendIosTechAssignPush($title, $body, $res_token['fcm_token'], "tech", $taskId, "task", $taskRec['user_id'], $userName, $techId, $techName);
								}
							}
						}
					}	

					$userPhoneRec = mysqli_fetch_array(mysqli_query($con, "SELECT phone FROM tbl_user WHERE id = '".$taskRec['user_id']."'"));
					$userPhone = $userPhoneRec['phone'];
	
					//send sms to tech			
					//get task location
					$taskAddressRec = mysqli_fetch_array(mysqli_query($con, "SELECT house_name, street, place, pin, city FROM tbl_job WHERE id = '".$taskId."'"));
					$taskLocation = '';	 
					if($taskAddressRec['house_name']!=''){
						$taskLocation .= $taskAddressRec['house_name'].',';	
					}
					if($taskAddressRec['street']!=''){
						$taskLocation .= $taskAddressRec['street'].',';	
					}	
					if($taskAddressRec['place']!=''){
						$taskLocation .= $taskAddressRec['place'].',';	
					}
					if($taskAddressRec['pin']!=''){
						$taskLocation .= $taskAddressRec['pin'].',';	
					}
					if($taskAddressRec['city']!=''){
						$taskLocation .= $taskAddressRec['city'];	
					}
					
					$smsMessage = urlencode('New task assigned for you successfully. ID#'.$taskId.', Date: '.$taskDate.', Time:'.$hrAmPm.', User Name:'.$userName.', Mobile:'.$userPhone.', Location:'.$taskLocation);
					sendSMSP($techPhone, $smsMessage);						
									
					//send push to user
					$exec_token = mysqli_query($con, 'SELECT fcm_token, device FROM tbl_fcm_tokens WHERE user_id='.$taskRec['user_id']);
					if(isset($exec_token) && mysqli_num_rows($exec_token)>0) {
						while($res_token = mysqli_fetch_array($exec_token)) {
							if($res_token['fcm_token']!='') {
								$userId = $taskRec['user_id'];
								$userName = getUserName($userId);
								$title = 'Your task has been assigned to '.$techName;
								$body = 'Task ID: #'.$taskId.', Task Date: '.$taskDate.', Task Slot: '.$hrAmPm.' to '.$hrAmPm2;
								if($res_token['device']=='android') {
									sendGCM_user($title, $body, $res_token['fcm_token'], $taskId, "task", $userId, $userName, $techId, $techName);																
									//sendGCMUserTaskAssign($title, $body, $res_token['fcm_token'], "user", $taskId, $techId, $techName, "task");
								} elseif($res_token['device']=='ios') {
									sendIosTechPush($title, $body, $res_token['fcm_token'], "tech");
								}
							}
						}
					}
					
					//send sms to user
					$smsMessage = urlencode('Your request has been assigned successfully. ID#'.$taskId.', Date: '.$taskDate.', Time:'.$hrAmPm.', Technician Name:'.$techName.', Mobile:'.$techPhone);
					sendSMSP($userPhone, $smsMessage);						
									
				}
		}		
		
		} else {
			echo '<span style="color:red;">Something went wrong!</span>';
		}
	} else {
		echo '<span style="color:red;">Please select a time slot</span>';
	}			
}

//validate commission when trying to add extra tech percent for fixed rate tasks
if(isset($_REQUEST['action']) && $_REQUEST['action']=='assign_validate_commission') {
	$taskId = $_REQUEST['task_id'];
	$techId = $_REQUEST['tech_id'];
	$newVal = $_REQUEST['new_val'];
	if($taskId!='' && $techId!='' && $newVal!=''){
		//find total commission for all extra techs including the submited percent
		$techCommissionRec = mysqli_fetch_array(mysqli_query($con, "SELECT commission_percent FROM tbl_job_extra_tech WHERE job_id = '".$taskId."' AND technician_id = '".$techId."'"));
		$currentCommission = $techCommissionRec['commission_percent'];
		if($newVal>$currentCommission){
			$changeInCommission = $newVal-$currentCommission;
		} else {
			$changeInCommission = $currentCommission-$newVal;
		}
		//get total commission of all extra tech
		$totComRec = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(commission_percent) AS tot_commission FROM tbl_job_extra_tech WHERE job_id = '".$taskId."'"));
		$totCommission = $totComRec['tot_commission'];
		$commissionForMain = 100-($totCommission+$changeInCommission);	
		if($commissionForMain>0){
			echo '<span style="color:green;">The commission for Main tech will be '.$commissionForMain.'%</span>-|-'.$commissionForMain;
		} else {
			echo '<span style="color:red;">The commission for Main tech will be '.$commissionForMain.'%</span>-|-'.$commissionForMain;
		}
	} else {
		echo '<span style="color:red;">Something went wrong!</span>-|-error';
	}			
}

//add extra technician in task
if(isset($_REQUEST['action']) && $_REQUEST['action']=='add_extra_tech') {
	$debug = true;
	$taskId = $_REQUEST['task_id'];
	$techId = $_REQUEST['tech_id'];
	$commission = $_REQUEST['commission'];
	$values = $_REQUEST['values'];
	//print_r($_REQUEST['values']);
	$totalCommission = 0;
	//exit;
	//get all extra techs
	$extraTechRs = mysqli_query($con, "SELECT technician_id FROM tbl_job_extra_tech WHERE job_id = '".$taskId."'");
	if(mysqli_num_rows($extraTechRs)>0){
		while($extraTechRec = mysqli_fetch_array($extraTechRs)){
			$extraId = $extraTechRec['technician_id'];
			if(isset($_REQUEST['extra_per-'.$extraId])){
				//echo 'extra_per-'.$extraId.',';
				$totalCommission+= $_REQUEST['extra_per-'.$extraId];
			}
		}
	}

	/*Request format
	 * [action] => add_extra_tech
    [tech_id] => 68
    [task_id] => 891
    [commission] => 10
    [values] => extra_per-1=20.00
    [extra_per-49] => 10.00
    [extra_per-14] => 20.00
    [main_per] => 50
    [commission_percent] => 10*/
	//extra_per-1=20.00&extra_per-49=10.00&main_per=70&commission_percent=10
	if($taskId!='' && $techId!='' && $commission!=''){
		if(isset($_REQUEST['values']) && $_REQUEST['values']!=''){
			$values = $_REQUEST['values'];
			$arr1 = explode('=', $values);
			if($arr1[0]=='main_per'){
				$mainCommission = trim($arr1[1]);
				$totalCommission+=$mainCommission;
			} else {
				$arr2 = explode('-', $arr1[0]);
				if($arr2[1]!=''){
					$extraTechComm = $arr1[1]*1;
					$totalCommission+=$extraTechComm;				
				}
			}			
		} 
		if(isset($_REQUEST['main_per']) && $_REQUEST['main_per']!=''){
			$mainCommission = trim($_REQUEST['main_per']);
			$totalCommission+=$mainCommission;
		}		
		if(isset($_REQUEST['commission_percent']) && $_REQUEST['commission_percent']!=''){
			$commissionPercent = trim($_REQUEST['commission_percent']);
			$totalCommission+=$commissionPercent;
		}
		//echo 'tot-'.$totalCommission; exit;
		
		if(($totalCommission==100) && ($mainCommission>=0)){
			//values have a an extra tech 
			if(isset($_REQUEST['values']) && $_REQUEST['values']!=''){
				$values = $_REQUEST['values'];
				$arr1 = explode('=', $values);
				if($arr1[0]=='main_per'){
					$mainCommission = trim($arr1[1]);
					//no need to update . its for main tech
				} else {
					$arr2 = explode('-', $arr1[0]);
					if($arr2[1]!=''){
						$extraTechComm = $arr1[1]*1;
						$extraTechId = $arr2[1];
						mysqli_query($con, "UPDATE tbl_job_extra_tech SET commission_percent = '".$extraTechComm."' WHERE job_id = '".$taskId."' AND technician_id = '".$extraTechId."'");			
					}
				}				
			}
			//get all other extra techs
			$extraTechRs = mysqli_query($con, "SELECT technician_id FROM tbl_job_extra_tech WHERE job_id = '".$taskId."'");
			if(mysqli_num_rows($extraTechRs)>0){
				while($extraTechRec = mysqli_fetch_array($extraTechRs)){
					$extraId = $extraTechRec['technician_id'];
					if(isset($_REQUEST['extra_per-'.$extraId])){						
						$extraTechComm = $_REQUEST['extra_per-'.$extraId];
						mysqli_query($con, "UPDATE tbl_job_extra_tech SET commission_percent = '".$extraTechComm."' WHERE job_id = '".$taskId."' AND technician_id = '".$extraId."'");
					}
				}
			}
			//update main tech commission
			$taskRec = mysqli_fetch_array(mysqli_query($con, "SELECT technician_id FROM tbl_job WHERE id = '".$taskId."'"));
			$mainTechId = $taskRec['technician_id'];
			
			$curDate = date('Y-m-d H:i:s');
			//assign tech with commission per
			//echo "UPDATE tbl_job_extra_tech SET technician_id = '".$techId."' commission_percent = '".$commissionPercent."' WHERE job_id = '".$taskId."' AND technician_id = '0' ORDER BY id DESC LIMIT 1";
			$insert = mysqli_query($con, "UPDATE tbl_job_extra_tech SET technician_id = '".$techId."', commission_percent = '".$commissionPercent."', status = 'assigned' WHERE job_id = '".$taskId."' AND technician_id = '0' ORDER BY id DESC LIMIT 1");
			//$insert = mysqli_query($con, "INSERT INTO tbl_job_extra_tech (job_id, tech_main_id, technician_id, commission_percent, date) VALUES ('".$taskId."', '".$mainTechId."', '".$techId."', '".$commissionPercent."', '".$curDate."')");
			if($insert){
				mysqli_query($con, "UPDATE tbl_job SET tech_request = '' WHERE id = '".$taskId."'");
				echo 'success';
			}			
		} else {
			echo 'Enter a valid commission percent';
		}
				
	} else {
		echo 'Something went wrong!';
	}			
}

//set dispatch type
if(isset($_REQUEST['action']) && $_REQUEST['action']=='set_dispatch_type') {
	$locId = $_REQUEST['city_id'];
	$type = $_REQUEST['type'];
	if($locId!='' && $type!=''){
		$update = mysqli_query($con, "UPDATE tbl_city SET dispatch_type = '".$type."' WHERE id = '".$locId."'");
		if($update){
			echo '<span style="color:green;">Updated</span>';
		} else {
			echo '<span style="color:red;">Something went wrong!</span>';
		}
	} else {
		echo '<span style="color:red;">Something went wrong!</span>';
	}			
}

//get products under a category as select box
if(isset($_REQUEST['action']) && $_REQUEST['action']=='get_cat_products') {
	$catId = $_REQUEST['cat_id'];
	$res = '';
	if(($catId!='' && $catId!='undefined')){
		$prodRs = mysqli_query($con, "SELECT id, name FROM tbl_products WHERE cat_id = '".$catId."'");
		if(mysqli_num_rows($prodRs)>0){
			$res.= '<select name="product" id="product">';
			$res = '<option value="">--Select Product--</option>';
			while($prodRec = mysqli_fetch_array($prodRs)){
				$res .= '<option value="'.$prodRec['id'].'">'.$prodRec['name'].'</option>';
			}
			$res.= '</select>';
		} else {
			$res.= '<select name="product" id="product">';
			$res = '<option value="">No Products Found</option>';
			$res.= '</select>';
		}
	}
	echo $res;		
}

//get staff date - add salary page
if(isset($_REQUEST['action']) && $_REQUEST['action']=='save_menu_toggle') {
	setcookie("menu_close",'yes',time()+31556926 ,'/');
	echo $_COOKIE['menu_close'];
}

//get staff date - add salary page
if(isset($_REQUEST['action']) && $_REQUEST['action']=='get_staff_data') {
	$error = $res = $msg = '';	
	$advanceAmount = $netAmount = $leaveCasual = $leaveSick = $totLeaves = $advanceReturnAmount = 0;
	$staffId = $_REQUEST['staff_id'];	
	$year = $_REQUEST['year'];	
	$month = $_REQUEST['month'];		
	if(($staffId!='' && $staffId!='undefined')){
		$staffRs = mysqli_query($con, "SELECT name, salary FROM tbl_staff WHERE id = '".$staffId."'");
		if(mysqli_num_rows($staffRs)>0){
			$resStaff = mysqli_fetch_array($staffRs);
			$basicSalary = $resStaff['salary']; 
			$netAmount = $basicSalary;			
		} else {
			$error = 'Staff does not exist!';
		}
		
		//get advance amount given to staff if any
		$advanceRs = mysqli_query($con, "SELECT amount, advance_return FROM tbl_staff_advance WHERE staff_id = '".$staffId."'");
		if(mysqli_num_rows($advanceRs)>0){
			while($advanceRec = mysqli_fetch_array($advanceRs)){
				$advanceAmount += $advanceRec['amount'];
				$advanceReturnAmount += $advanceRec['advance_return'];
			}
			$advanceAmount = $advanceAmount - $advanceReturnAmount;
			$netAmount = $basicSalary-$advanceAmount;
		}
		//get total leaves
		if(($year!='' && $year!='undefined') && ($month!='' && $month!='undefined')){			
			$leaveRs = mysqli_query($con, "SELECT * FROM tbl_staff_leaves WHERE staff_id = '".$staffId."' AND YEAR(date) = '".$year."' AND MONTH(date) = '".$month."'");
			if(mysqli_num_rows($leaveRs)>0){
				while($leaveRec = mysqli_fetch_array($leaveRs)){
					if($leaveRec['leave_type'] == 'casual'){
						if($leaveRec['status'] == 'full_day'){
							$leaveCasual++;
						} else if($leaveRec['status'] == 'half_day'){
							$leaveCasual = $leaveCasual+0.5;
						}						
					} else if($leaveRec['leave_type'] == 'sick'){
						if($leaveRec['status'] == 'full_day'){
							$leaveSick++;
						} else if($leaveRec['status'] == 'half_day'){
							$leaveSick = $leaveSick+0.5;
						}
					}					
				}
			} 
		}
		$totLeaves = $leaveCasual+$leaveSick;
		
		/*not completed*/
		//get settings for leaves and calculate deduction
		$settingsRes = mysqli_fetch_array(mysqli_query($con, "SELECT casual_leave_count, allow_advance_leave, sick_leave_count, allow_advance_sick_leave, working_days FROM tbl_settings WHERE id = '1'"));
		$casualLeaveCount = $settingsRes['casual_leave_count'];
		$allowAdvanceLeave = $settingsRes['allow_advance_leave'];
		$sickLeaveCount = $settingsRes['sick_leave_count'];
		$allowAdvanceSickLeave = $settingsRes['allow_advance_sick_leave'];
		$workingDays = $settingsRes['working_days'];
		$casualLeavePerMonth = $casualLeaveCount/12;
		$sickLeavePerMonth = $sickLeaveCount/12;
		//the total leave count in a year will vary if the staff joined on the year after some months or like that
		//so we have to calculate the total leaves from the joining month
		//get joining year,month
		$staffRec = mysqli_fetch_array(mysqli_query($con, "SELECT YEAR(date) AS year, MONTH(date) AS month FROM tbl_staff WHERE id = '".$staffId."'"));
		$joinYear = $staffRec['year'];
		$joinMonth = $staffRec['month'];
		if($joinYear==$year){
			$monthBalance = (12-$joinMonth)+1;
			$casualLeaveCount = $casualLeaveCount/$monthBalance;
			$sickLeaveCount = $sickLeaveCount/$monthBalance;
		}
		//find total casual leaves taken by the staff in current year, month
		$leaveCasualYear = $leaveSickYear = 0;
		$leaveCasualMonth = $leaveSickMonth = 0;
		$leaveRs = mysqli_query($con, "SELECT * FROM tbl_staff_leaves WHERE staff_id = '".$staffId."' AND YEAR(date) = '".$year."'");
		if(mysqli_num_rows($leaveRs)>0){
				while($leaveRec = mysqli_fetch_array($leaveRs)){
					if($leaveRec['leave_type'] == 'casual'){
						if($leaveRec['status'] == 'full_day'){
							$leaveCasualYear++;
						} else if($leaveRec['status'] == 'half_day'){
							$leaveCasualYear = $leaveCasualYear+0.5;
						}						
					} else if($leaveRec['leave_type'] == 'sick'){
						if($leaveRec['status'] == 'full_day'){
							$leaveSickYear++;
						} else if($leaveRec['status'] == 'half_day'){
							$leaveSickYear = $leaveSickYear+0.5;
						}
					}					
				}
		}
		//calculate total casual leaves taken for the month
		if($allowAdvanceLeave == 'Yes'){
			$extraCausalLeaves = $leaveCasualYear - $casualLeaveCount;
		} else {
			//total casual leaves taken on this month
			$leaveCasualMonth = 0;
			$leaveRs = mysqli_query($con, "SELECT * FROM tbl_staff_leaves WHERE staff_id = '".$staffId."' AND YEAR(date) = '".$year."' AND MONTH(date) = '".$month."'");
			if(mysqli_num_rows($leaveRs)>0){
					while($leaveRec = mysqli_fetch_array($leaveRs)){
						if($leaveRec['leave_type'] == 'casual'){
							if($leaveRec['status'] == 'full_day'){
								$leaveCasualMonth++;
							} else if($leaveRec['status'] == 'half_day'){
								$leaveCasualMonth = $leaveCasualMonth+0.5;
							}						
						} 					
					}
			}		
			if($leaveCasualMonth>0){
				$extraCausalLeaves = $leaveCasualMonth - $casualLeavePerMonth;
			} else {
				$extraCausalLeaves = 0;
			}
			
			//$extraCausalLeaves = 2-1;
		}
		//calculate total sick leaves taken for the month
		if($allowAdvanceSickLeave == 'Yes'){
			$extraSickLeaves = $leaveSickYear - $sickLeaveCount;			
		} else {
			//total casual leaves taken on this month
			$leaveSickMonth = 0;
			$leaveRs = mysqli_query($con, "SELECT * FROM tbl_staff_leaves WHERE staff_id = '".$staffId."' AND YEAR(date) = '".$year."' AND MONTH(date) = '".$month."'");
			if(mysqli_num_rows($leaveRs)>0){
					while($leaveRec = mysqli_fetch_array($leaveRs)){
						if($leaveRec['leave_type'] == 'sick'){
							if($leaveRec['status'] == 'full_day'){
								$leaveSickMonth++;
							} else if($leaveRec['status'] == 'half_day'){
								$leaveSickMonth = $leaveSickMonth+0.5;
							}						
						} 					
					}
			}	
			if($leaveSickMonth>0){
				$extraSickLeaves = $leaveSickMonth - $sickLeavePerMonth;
			} else {
				$extraSickLeaves = 0;
			}
			
		}
		$salToCutForCasual = $salToCutForSick = 0;
		$msg2 = '';
		if($extraCausalLeaves>0){
			$salToCutForCasual = ($basicSalary/$workingDays)*$extraCausalLeaves;
			$msg2 = '<b>'.$salToCutForCasual.'</b> (Casual) + ';
		} else {
			$msg2 = '<b>0</b> (Casual) + ';
		}
		if($extraSickLeaves>0){
			$salToCutForSick = ($basicSalary/$workingDays)*$extraSickLeaves;
			$msg2 .= '<b>'.$salToCutForSick.'</b> (Sick)';
		} else {
			$msg2 .= '<b>0</b> (Sick)';
		}
		/*not completed*/	
		
		if($totLeaves>0){
			$msg = '<b>'.$leaveCasual.'</b> casual + <b>'.$leaveSick.'</b> sick.';
		} 
		
		
		$res = $basicSalary.'-|-'.$advanceAmount.'-|-'.$netAmount.'-|-'.$totLeaves.'-|-'.$salToCutForCasual.'-|-'.$salToCutForSick.'-|-'.$msg.'-|-'.$msg2;
	} else {
		$error = 'Something went wrong!';			
	}	
	if(!empty($error)){
		echo '<span style="color:red;">'.$error.'</span>';
	} else {
		echo $res;
	}
}

if(isset($_REQUEST['action']) && $_REQUEST['action']=='change_cat_type') {
	$cat_id = $_REQUEST['cat_id'];
	$cat_type = $_REQUEST['cat_type'];
	$update_cat_type = mysqli_query($con, 'UPDATE tbl_service_categories SET cat_type="'.mysqli_real_escape_string($con, $cat_type).'" WHERE id='.$cat_id);
}

if(isset($_REQUEST['action']) && $_REQUEST['action']=='tech_push') {
	
	$title = $_REQUEST['title'];
	$body = $_REQUEST['body'];
	$token = $_REQUEST['token'];
	sendIosTechPush($title, $body, $token, "tech");
	
	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', 'ckT.pem');
	stream_context_set_option($ctx, 'ssl', 'local_cert', BASE_URI.'lcontrol/includes/CKPdtnTech.pem');	
	stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

	$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);
}
}

// set app cat
if(isset($_REQUEST['action']) && $_REQUEST['action']=='set_app_cat') {
	$id = $_REQUEST['id'];
	
	$update = mysqli_query($con, 'UPDATE tbl_settings SET app_cat='.$id.' WHERE id=1');
	if($update) {
		$response = array("status" => "success");
	} else {
		$response = array("status" => "failed");
	}

	print json_encode($response);
}
?> 