<?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

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

$pageVars = '';

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


if(isset($_POST['add'])) {
		
	if(isset($_POST['quantity']) && strlen($_POST['quantity'])>0) {
		$quantity = trim($_POST['quantity']);
		if(is_numeric($quantity) && $quantity>0){
			//ok
		} else {
			$error = 'Invalid value for quantity';
		}
	} else {
		$error = 'Enter quantity';
	}
	
	if(isset($_POST['product']) && strlen($_POST['product'])>0) {
		$product = trim($_POST['product']);
	} else {
		$error = 'Please select product';
	}	
	
	if(isset($_POST['category']) && strlen($_POST['category'])>0) {
		$category = trim($_POST['category']);
	} else {
		$error = 'Please select category';
	}
	
	if(isset($_REQUEST['id']) && $_REQUEST['id']!=''){		
		$orderId = mysqli_real_escape_string($con, trim($_REQUEST['id']));
	} else {
		$error = 'Something went wrong!';
	}	
	
	if(empty($error)) {			
		
		$insertQry = "INSERT INTO tbl_purchase_order_products(order_id, product_id, cat_id, quantity) VALUES (
		'".mysqli_real_escape_string($con, $orderId)."',
		 '".mysqli_real_escape_string($con, $product)."',
		 '".mysqli_real_escape_string($con, $category)."',
		 '".mysqli_real_escape_string($con, $quantity)."')";
		
		$execInsert = mysqli_query($con,$insertQry);
		$insert_id = mysqli_insert_id($con);				
		if($execInsert) {						
			$success = 'Product Added Successfully';
			header('Location:index.php?page=view_purchase_order&id='.$orderId.'&p='.$p.'&success='.$success);
			exit();			
		}				
	} 
}



if(isset($_REQUEST['id']) && $_REQUEST['id']!=''){		
	$editId = mysqli_real_escape_string($con, trim($_REQUEST['id']));	
	//if assign action
	if(isset($_REQUEST['partner_id']) && $_REQUEST['partner_id']!=''){
		$partnerId = mysqli_real_escape_string($con, trim($_REQUEST['partner_id']));
		if(isset($_REQUEST['action']) && $_REQUEST['action']=='assign'){
			//assign the shop to this order
			$update = mysqli_query($con, "UPDATE tbl_purchase_order SET partner_id = '".$partnerId."', status = 'assigned' WHERE id = '".$editId."'");
			if($update){
				
				//get partner details
				$partnerRec = mysqli_fetch_array(mysqli_query($con, "SELECT name, email, mobile FROM tbl_purchase_partner WHERE id = '".$partnerId."'"));
				$partnerName = $partnerRec['name'];
				$partnerEmail = $partnerRec['email'];
				$partnerMobile = $partnerRec['mobile'];
				
				if($partnerEmail!=''){
					//get order details
					$orderRec = mysqli_fetch_array(mysqli_query($con, "SELECT technician_id, user_id, job_id FROM tbl_purchase_order WHERE id = '".$editId."'"));
					$technicianName = getTechnicianName($orderRec['technician_id']);
					$userName = getUserName($orderRec['user_id']);
					$taskId = $orderRec['job_id'];
									
					//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 Order';	
			
					
					$mail->AddAddress($partnerEmail, $partnerName);					
					//$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 order from '.SITE_NAME.'</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  '. $partnerName .',</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>New order received from '.SITE_NAME.'<b></p>
										<p>Task ID: #'.$taskId.'</p>
										<p>Technician: '.$technicianName.'</p>
										<p>User: '.$userName.'</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();
				}

				//send sms to pp				   
				$smsMessage = urlencode('Task #'.$taskId.', New purchase request received. Kindly reply the total amount by app/web.');						
				$smsRes = file_get_contents('http://roundsms.com/api/sendhttp.php?authkey=Nzk3YWJkY2VmMWU&mobiles='.$partnerMobile.'&message='.$smsMessage.'&sender=odpP&type=1&route=3'); 
				$smsRes = json_decode($smsRes);
				if($smsRes->error!= 'null' && $smsRes->error!=''){
					$error = $smsRes->error;
					if($error!=''){
						mail($contact_email, 'SMS API Error','SMS API failed to send in view_purchase_order(admin), pp phone:'.$partnerMobile.', Error-'.$error);
					}
				}			
				
				$success = 'Successfully assigned to the order';
			} else {
				$error = 'Something went wrong';
			}
		}					
	}		


	//cancel shop from order
	if(isset($_REQUEST['action']) && $_REQUEST['action']=='cancel_shop'){
			//get order details
			$orderRec = mysqli_fetch_array(mysqli_query($con, "SELECT technician_id, user_id, job_id, partner_id FROM tbl_purchase_order WHERE id = '".$editId."'"));
			$technicianName = getTechnicianName($orderRec['technician_id']);
			$userName = getUserName($orderRec['user_id']);
			$taskId = $orderRec['job_id'];
			$partnerId = $orderRec['partner_id'];
			
			$update = mysqli_query($con, "UPDATE tbl_purchase_order SET partner_id = '0', status = 'new' WHERE id = '".$editId."'");
			if($update){				
				//get partner details
				$partnerRec = mysqli_fetch_array(mysqli_query($con, "SELECT name, email, mobile FROM tbl_purchase_partner WHERE id = '".$partnerId."'"));
				$partnerName = $partnerRec['name'];
				$partnerEmail = $partnerRec['email'];
				$partnerMobile = $partnerRec['mobile'];				
				if($partnerEmail!=''){									
					//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.' Order Cancelled';	
					
					$mail->AddAddress($partnerEmail, $partnerName);					
					//$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;">Order cancelled from '.SITE_NAME.'</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  '. $partnerName .',</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>An order has been cancelled from '.SITE_NAME.'<b></p>
										<p>Task ID: #'.$taskId.'</p>
										<p>Technician: '.$technicianName.'</p>
										<p>User: '.$userName.'</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();
				}

				//send sms to pp				   
				$smsMessage = urlencode('Task #'.$taskId.', The order has been cancelled.');						
				$smsRes = file_get_contents('http://roundsms.com/api/sendhttp.php?authkey=Nzk3YWJkY2VmMWU&mobiles='.$partnerMobile.'&message='.$smsMessage.'&sender=odpP&type=1&route=3'); 
				$smsRes = json_decode($smsRes);
				if($smsRes->error!= 'null' && $smsRes->error!=''){
					$error = $smsRes->error;
					if($error!=''){
						mail($contact_email, 'SMS API Error','SMS API failed to send in view_purchase_order(admin), pp phone:'.$partnerMobile.', Error-'.$error);
					}
				}			
				
				$success = 'The shop has been unassigned from the order';
			} else {
				$error = 'Something went wrong';
			}
		}					
	}





	$editRs = mysqli_query($con, "SELECT * FROM tbl_purchase_order WHERE id = '".$editId."'");
	if(mysqli_num_rows($editRs)>0){
		$resEdit = mysqli_fetch_array($editRs);		
		//get order products		
		$select = "SELECT * FROM tbl_purchase_order_products WHERE order_id = '".$editId."'";
		// Using pagination class
		$pagination = new pagination_noseo($select);
		$execDetails = $pagination->createPages(20);		
		$pageLnk = 'index.php?page='.$page.'&'.$pageVars;
		$pageNums = $pagination->pageNumber(5, $pageLnk);	
		
		
		
		
		
	} else {
		$error = 'Order does not exist!';
	}

 


?>