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

$isEdit = FALSE;
$debug = true;
$curDate = date('Y-m-d H:i:s');

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

if(isset($_REQUEST['user_id']) && $_REQUEST['user_id']!=''){
	$userId = trim($_REQUEST['user_id']);
	$curDate = date('Y-m-d H:i:s');
	


	$categoryRs = mysqli_query($con, "SELECT id, name FROM tbl_service_categories WHERE status = 'Active' AND parent_id = '0' ORDER BY name");

	//get all addresses of the user
	//default address
	$userRec = mysqli_fetch_array(mysqli_query($con, "SELECT house_name, street, place, pin, city, def_address FROM tbl_user WHERE id = '".$userId."'"));
	
	//get other addresses
	$userAddressRs = mysqli_query($con, "SELECT * FROM tbl_user_address WHERE user_id = '".$userId."'");

	if(isset($_REQUEST['id']) && $_REQUEST['id']!=''){
		
		$isEdit = TRUE;
		$editId = mysqli_real_escape_string($con, trim($_REQUEST['id']));	
		$editRs = mysqli_query($con, "SELECT * FROM tbl_project WHERE id = '".$editId."'");
		if(mysqli_num_rows($editRs)>0){
			$resEdit = mysqli_fetch_array($editRs);
		} else {
			$error = 'Project does not exist!';
		}
	
	} 

	if(isset($_POST['add'])) {
				
		if(isset($_POST['date_time']) && strlen($_POST['date_time'])>0) {
			$date_time = trim($_POST['date_time']);
			$dateTimeArr = explode(' ', $date_time);
			$date = $dateTimeArr[0];
			$time = $dateTimeArr[1];
			if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
			   
			} else {
				$dateArr = explode('-', $date);
				$date = $dateArr[2].'-'.$dateArr[1].'-'.$dateArr[0];
			}		
		} else {
			$error = 'Please select date and time';
		}
	
		
		if(strlen(trim($_POST['description'])) > 0) {
			$description = trim($_POST['description']);
		} else {
			$description = '';
		}	
			
		if(isset($_POST['address_id']) && strlen($_POST['address_id'])>0) {
			$address_id = trim($_POST['address_id']);
		} else {
			$error = 'Please select task location';
		}		
		
		if(isset($_POST['category']) && strlen($_POST['category'])>0) {
			$category = trim($_POST['category']);
		} else {
			$error = 'Please select category';
		}	
		
		
		
		if(empty($error)) {
			
			//check if project/task
			$catRec = mysqli_fetch_array(mysqli_query($con, "SELECT cat_type FROM tbl_service_categories WHERE id = '".$category."'"));
			if($catRec['cat_type']=='Project'){
				$isProject = 'yes';
			} else {
				$isProject = 'no';
			}
			
			if($address_id>0){
				$addressRec = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM tbl_user_address WHERE id = '".$address_id."'"));
				$houseName = $addressRec['house_name'];
				$street = $addressRec['street'];
				$place = $addressRec['place'];
				$pin = $addressRec['pin'];
				$city = $addressRec['city'];
				$latitude = $addressRec['latitude'];
				$longitude = $addressRec['longitude'];
			} else {
				$addressRec = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM tbl_user WHERE id = '".$userId."'"));
				$houseName = $addressRec['house_name'];
				$street = $addressRec['street'];
				$place = $addressRec['place'];
				$pin = $addressRec['pin'];
				$city = $addressRec['city'];
				$latitude = $addressRec['latitude'];
				$longitude = $addressRec['longitude'];
			}
			
			//get admin commission percent from settings
			$settingsRec = mysqli_fetch_array(mysqli_query($con, "SELECT admin_commission_direct, admin_commission_admin FROM tbl_settings WHERE id = '1'"));
			$adminCommissionDirect = $settingsRec['admin_commission_direct'];
			$adminCommissionAdmin = $settingsRec['admin_commission_admin'];
			
			if($isProject == 'no'){
			//check if direct assign or admin assign
				$cityRec = mysqli_fetch_array(mysqli_query($con, "SELECT dispatch_type FROM tbl_city WHERE id = '".$city."'"));
				$type = $cityRec['dispatch_type'];
				if($type == 'direct'){
					$adminCommissionPercent = $adminCommissionDirect;
				} else {
					$adminCommissionPercent = $adminCommissionAdmin;
				}					
			} else {
				$adminCommissionPercent = 0;
			}
					
			$insertQry = "INSERT INTO tbl_job(is_project, user_id, category_id, address_id, details, date, task_date, task_time, status, house_name, street, place, pin, city, latitude, longitude, admin_commission_percent, source, viewed) VALUES (
			'".mysqli_real_escape_string($con, $isProject)."',
			 '".mysqli_real_escape_string($con, $userId)."',
			 '".mysqli_real_escape_string($con, $category)."',
			 '".mysqli_real_escape_string($con, $address_id)."',
			 '".mysqli_real_escape_string($con, $description)."',
			 '".mysqli_real_escape_string($con, $curDate)."',
			 '".mysqli_real_escape_string($con, $date)."',
			 '".mysqli_real_escape_string($con, $time)."',	 
			 'New',
			 '".mysqli_real_escape_string($con, $houseName)."',
			 '".mysqli_real_escape_string($con, $street)."',
			 '".mysqli_real_escape_string($con, $place)."',
			 '".mysqli_real_escape_string($con, $pin)."',
			 '".mysqli_real_escape_string($con, $city)."',
			 '".mysqli_real_escape_string($con, $latitude)."',
			 '".mysqli_real_escape_string($con, $longitude)."',
			 '".mysqli_real_escape_string($con, $adminCommissionPercent)."', 'admin', 'yes')";
			
			$execInsert = mysqli_query($con,$insertQry);
			$insert_id = mysqli_insert_id($con);		
			
			if($execInsert) {
				$taskId = $insert_id;
				
				if($isProject=='no'){		
						
					//send mail to user
					//get from email address
					$settingsRec = mysqli_fetch_array(mysqli_query($con, "SELECT from_email FROM tbl_settings WHERE id = '1'"));
					$fromEmail = $settingsRec['from_email'];
					$userRec = mysqli_fetch_array(mysqli_query($con, "SELECT name, email FROM tbl_user WHERE id = '".$userId."'"));
					$userName = $userRec['name'];
					$userEmail = $userRec['email'];
					
					$mailAddressString = '';
					if($houseName!=''){
						$mailAddressString.= $houseName.',';
					}
					if($street!=''){
						$mailAddressString.= $street.',';
					}
					if($place!=''){
						$mailAddressString.= $place.',<br>';
					}
					if($pin!=''){
						$mailAddressString.= 'PIN: '.$pin;
					}
					
					$mail = new PHPMailer();
					$mail->From = $fromEmail;
					$mail->FromName = SITE_NAME;
					$mail->IsHTML(true);	
					$mail->Subject = 'Your task has been booked';	
					$mail->AddAddress($userEmail, $userName);
					
					$email_content_user = '<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;">Task Booked!</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  '. $userName .',</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>Thank you for booking a task with us. We will assign a technician soon.<b></p>
											<p>Task ID: #'.$taskId.'</p>
											<p>Date: '.$date.'</p>
											<p>Time: '.$time.'</p>
											<p>Task Location: '.$mailAddressString.'</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_user;
						$mail->Send(); 						
										
					$success = 'Task Created Successfully';
					header('Location:index.php?page=manage_user_tasks&success='.$success);
				} else {
					$success = 'Project Created Successfully';
					header('Location:index.php?page=manage_projects&success='.$success);
				}				
				exit();			
			}				
		} 
	}

	

} else {
	header('Location:index.php?page=manage_user&p='.$p);
	exit();
}

?>