<?php
include '../db/db.php';
session_start();

require("../../PHPMailer/class.phpmailer.php");

if(isset($_SESSION['userID'])) {
	$log = htmlspecialchars(strip_tags(trim($_SESSION['userID'])), ENT_QUOTES, 'UTF-8');
} else {
	$log = '';
}

if (empty($log)) {
	$redirectUrl = "../";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";

} else {
	$sqlu = "SELECT id FROM user_acc_tbl WHERE userID='$log' and access=1 and val=1";
	$stmtu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($stmtu);
	
	if($countu == 1) {
		$rowu = mysqli_fetch_assoc($stmtu);
		$uid = $rowu['id'];
		
		date_default_timezone_set('Asia/Colombo');
		$date = date('Y-m-d H:i:s');
		
		/************************ Accept Order *************************/
		
	    if (array_key_exists('accept_order', $_POST)) {
			$oid = htmlspecialchars(strip_tags(trim($_POST['oid'])), ENT_QUOTES, 'UTF-8');
			$pay_status = htmlspecialchars(strip_tags(trim($_POST['pay_status'])), ENT_QUOTES, 'UTF-8');
			
			if(empty($oid) || $pay_status != '1') {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
			
			} else {
				$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT *, DATE_FORMAT(order_date, '%Y-%m-%d') AS gdate, DATE_FORMAT(order_date,'%H:%i:%s') AS gtime FROM order_details WHERE id='$oid'"));
				$st = $sql_or['order_status'];
				$inv_no = $sql_or['inv_no'];
				$user_id = $sql_or['user_id'];
				$guest = $sql_or['guest'];
				$gtime = $sql_or['gtime'];
				$gdate = $sql_or['gdate'];
				$sdate = $sql_or['order_date'];
				$cust_emal = $sql_or['email'];
				
				if($st == 0) {
					$sql = "UPDATE order_details SET order_status ='1', date_accept=now(), accept_usr='$uid' WHERE id='$oid'";
					$stmt_log = mysqli_query($conn, $sql);
					if( $stmt_log === false ) {
						echo json_encode(array("msgType" => 2, "msg" => "Error"));
					
					} else {
						/* Stock Update *
						if($guest == 0) {
							$whr = 'User_ID';
							
						} else {
							$whr = 'temp_id';
						}
						
						$sql_inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT stock, purchase FROM invoice_no"));
						$inv = $sql_inv['purchase'];
						$ref = $sql_inv['stock'];
						mysqli_query($conn, "UPDATE invoice_no SET stock=stock+1, purchase=purchase+1");
						
						$sql_ordn = mysqli_query($conn, "SELECT ref FROM stock_orders WHERE ref='$ref'");
						$sql_stkn = mysqli_query($conn, "SELECT ref FROM stock WHERE ref='$ref'");
						
						$stmt5 = mysqli_query($conn, "SELECT invoice FROM stock_orders WHERE invoice='$inv'");
						
						//if(mysqli_num_rows($sql_ordn) == 0 && mysqli_num_rows($sql_stkn) == 0 && mysqli_num_rows($stmt5) == 0) {
							/*$sql_stk = "INSERT INTO stock_orders SET supp_id='', sup_acc='', type='Online Sale', invoice='$inv', ref='$ref', p_order='$inv_no', stock_date='$gdate', stock_time='$gtime', date='$date', time=CURTIME(), userID='$uid'";
							$stmt_log = mysqli_query($conn, $sql_stk);
							
							if($stmt_log === false) {
								//echo json_encode(array("msgType" => 2, "msg" => "error"));
								
							} else {
								$sql_od = mysqli_query($conn, "SELECT id, Item, Qty FROM cart_details WHERE inv_no='$inv_no' AND $whr='$user_id' AND stock_up=0");
								while($row_od = mysqli_fetch_array($sql_od)) {
									$item = $row_od['Item'];
									$Qty = $row_od['Qty'];
									$sid = $row_od['id'];
									
									$sql_ref = "INSERT INTO stock SET stock_card='$item', ref='$ref', cr_qty='$Qty', stock_date='$sdate', date=now()";
									
									if(mysqli_query($conn, $sql_ref)) {
										mysqli_query($conn, "UPDATE cart_details SET stock_up=1 WHERE id='$sid'");
									}

									/*------- Update Item Qty ---------*
									$stk_bal = mysqli_fetch_array(mysqli_query($conn, "SELECT bal_qty FROM `stock_qty` WHERE stock_card='$item'"));

									$itm_qty = $stk_bal['bal_qty'];
									if($itm_qty == null) {$itm_qty=0;}
									
									if($itm_qty <= 0) {
										mysqli_query($conn, "UPDATE bookdetails SET qty='0', stock_out=1 WHERE id='$item'");
									
									} else {
										mysqli_query($conn, "UPDATE bookdetails SET qty='$itm_qty', stock_out=0 WHERE id='$item'");
									}
									/*-------------- // ------------*
								}
							}*/
							
							if(!empty($cust_emal)) {
								$message = '<!DOCTYPE html>
								<html><head><title></title>
								<style>
								body {
								font-family: sans-serif;
								}
								.table .table-bordered {
								border: 1px solid #ccc;
								}
								table {
								border-collapse: collapse;
								}
								.table-bordered th, .table-bordered td {
								border: 1px solid #ccc;
								padding: 6px;
								}
								</style>
								</head><body>
								<p>Dear Mr/Mrs '.$sql_or['f_name'].' '.$sql_or['l_name'].',<br>Your order has been accepted.</p>
								<br>
								<table width="100%" border="1">
								<tr>
								<th scope="col"><p style="margin:10px"><strong>Order Accepted</strong></p></th>
								</tr>
								</table>
								<br>
								<p>You can track your order status below.</p>
								<table style = "width: 100%;margin-top: 10px;" border="0">
								<tr><td style = "width: 15%;"><h3><b>Order ID:</b></h3> </td><td><h3><b>'.$sql_or['inv_no'].'</b></h3></td></tr>
								<tr><td><b>Order Date:</b> </td><td>'.$sql_or['order_date'].'</td></tr>
								<tr><td><b>Total Amount:</b> </td><td>LKR '.$sql_or['grand_total'].'</td></tr>
								<tr><td><b>Order Status:</b> </td><td>Accepted</td></tr>
								<tr><td><b>Date:</b> </td><td>'.date('Y-m-d H:i:s').'</td></tr>
								</table>
								<br><br>
								Thank you for using our online shopping system.<br>
								www.buddhistbooksonline.com<br>
								<p><img src="https://buddhistbooksonline.com/images/logo/logo.png" width="250" style = "margin : 20px 0;"></p>
								Samudra Book Shop<br>
								Contact No: (+94) 37 223 4446<br>
								Website: www.samudrabooks.com<br>
								</body></html>';
								
								//echo $message;
								try {
									$mail = new PHPMailer();
									$mail->IsSMTP(); // set mailer to use SMTP
									$mail->Host = $email_host;  // specify main and backup server
									$mail->SMTPAuth = true;     // turn on SMTP authentication
									$mail->Username = $server_email_add;  // SMTP username
									$mail->Password = $server_email_pw; // SMTP password
									$mail->SMTPSecure = 'ssl';
									$mail->Port = 465;
									$mail->From = $server_email_from;
									$mail->FromName = "buddhistbooksonline.com";
									$mail->AddAddress($cust_emal, $sql_or['f_name'].' '.$sql_or['l_name']);
									$mail->AddReplyTo("info@buddhistbooksonline.com", "buddhistbooksonline.com");
									$mail->IsHTML(true); // set email format to HTML
									$mail->Subject = "Order Accepted - Order ID: ".$sql_or['inv_no'];
									$mail->Body    = $message;

									if(!$mail->Send())
									{
									   //echo "Message could not be sent.";
									   //echo "Mailer Error: " . $mail->ErrorInfo;
									   exit;
									}
								
								} catch(phpmailerException $ex) {
									//$err_msg = $ex->errorMessage();
								}
							}
							
							/*********************** Company EMail ********************/
							
							if($sql_or['delivery_type'] == 1) {
								$del_type = 'Postal';

							} else if($sql_or['delivery_type'] == 2) {
								$del_type = 'Courier Service';

							} else if($sql_or['delivery_type'] == 3) {
								$del_type = 'Expedited Mail Service (EMS)';

							} else if($sql_or['delivery_type'] == 4) {
								$del_type = 'Cash on Delivery';

							} else {
								$del_type = '';
							}
							  
							if($sql_or['pay_method'] == 1) {
								$pay_type = 'Credit/Debit Card';

							} else if($sql_or['pay_method'] == 2) {
								$pay_type = 'Mobile Wallet';
							
							} else if($sql_or['pay_method'] == 3) {
								$pay_type = 'Bank Deposit';
							
							} else if($sql_or['pay_method'] == 4) {
								$pay_type = 'Cash on Delivery';
							
							} else if($sql_or['pay_method'] == 5) {
								$pay_type = 'Internet Banking';
							
							} else {
								$pay_type = '';
							}
							
							$message1 = '<!DOCTYPE html>
							<html>
							<head>
							<title></title>
							<style>
							body {
							font-family: sans-serif;
							}
							.table .table-bordered {
							border: 1px solid #ccc;
							}
							table {
							border-collapse: collapse;
							}
							.table-bordered th, .table-bordered td {
							border: 1px solid #ccc;
							padding: 6px;
							}
							</style>
							</head>
							<body>
							<p align="right"><img src="https://buddhistbooksonline.com/images/logo/logo.png" style = "margin : 20px 0 10px 0;" width="250"></p>
							<table width="100%" border="0" class="table table-bordered">
							<tr>
							<th scope="col"><p style="margin:10px"><strong>Order ID: '.$inv_no.'</strong></p></th>
							</tr>
							</table>
							<br>
							<table style = "width: 100%;" border="0">
							<tr><td style = "width: 15%;"><b>Name:</b> </td><td>'.$sql_or['f_name'].' '.$sql_or['l_name'].'</td></tr>
							<tr><td><b>Delivery Address:</b> </td><td>'.$sql_or['address_1'].' '.$sql_or['address_2'].' '.$sql_or['city'].'</td></tr>
							<tr><td><b>District:</b> </td><td>'.$sql_or['district'].'</td></tr>
							<tr><td><b>Post Code:</b> </td><td>'.$sql_or['postal_code'].'</td></tr>
							<tr><td><b>Country:</b> </td><td>'.$sql_or['country'].'</td></tr>
							<tr><td><b>Contact No:</b> </td><td>'.$sql_or['tel_no'].'</td></tr>
							<tr><td><b>Email:</b> </td><td>'.$sql_or['email'].'</td></tr>
							<tr><td><b>Order Date:</b> </td><td>'.$sql_or['order_date'].'</td></tr>
							<tr><td><b>Delivery Method:</b> </td><td>'.$del_type.'</td></tr>
							<tr><td><b>Payment Method:</b> </td><td>'.$pay_type.'</td></tr>
							</table>
							<br>		  
							<table width="100%" class="table table-bordered">
							<tr>
							<th width="25%" align="left">Product Name</th>
							<th width="20%" align="left">ISBN</th>
							<th width="15%" align="right">Unit Price (Rs)</th>
							<th width="15%" align="right">Discounted Price (Rs)</th>
							<th width="10%" align="right">Qty</th>
							<th width="15%" align="right">Subtotal (Rs)</th>
							</tr>';
							$sql_c = mysqli_query($conn, "SELECT * FROM cart_details WHERE inv_no = '$inv_no'");
							$sub = 0;
							$tot_sub = 0;
							$s_tot = $dis_tot = $w_tot = 0;
							while($row_c = mysqli_fetch_array($sql_c)) {
								$message1 .= '<tr>
								<td align="left">'.$row_c['name'].'</td>
								<td align="left">'.$row_c['isbn'].'</td>
								<td align="right">'.$row_c['item_price'].'</td>
								<td align="right">'.$row_c['price'].'</td>
								<td align="right">'.$row_c['Qty'].'</td>
								<td align="right">'.number_format($row_c['price']*$row_c['Qty'], 2).'</td>
								</tr>';
								$dis_tot += $row_c['price']*$row_c['Qty'];
								$s_tot += $row_c['item_price']*$row_c['Qty'];
							}
							$message1 .= '<tr>
							<td colspan="5" align="right">
							<h4>Subtotal<br>
							Total Discount<br>
							Total Amount<br>
							Delivery Charges</h4>
							<h3>GRAND TOTAL</h3></td>
							<td align="right">
							<h4>'.number_format($s_tot, 2).'<br>
							'.number_format($s_tot - $dis_tot, 2).'<br>
							'.number_format($dis_tot, 2).'<br>
							'.number_format($sql_or['delivery_chg'], 2).'</h4>
							<h3>LKR '.number_format($sql_or['grand_total'], 2).'</h3>
							</td></tr>
							</table>
							</body>
							</html>';
							//echo $message1;
							
							try {
								$mail1 = new PHPMailer();
								$mail1->IsSMTP(); // set mailer to use SMTP
								$mail1->Host = $email_host;  // specify main and backup server
								$mail1->SMTPAuth = true;     // turn on SMTP authentication
								$mail1->Username = $server_email_add;  // SMTP username
								$mail1->Password = $server_email_pw; // SMTP password
								$mail1->SMTPSecure = 'ssl';
								$mail1->Port = 465;
								$mail1->From = $server_email_from;
								$mail1->FromName = "buddhistbooksonline.com";
								$mail1->AddAddress("nirmal@samudrabooks.com", "Nirmal Ranasinghe");
								//$mail1->AddAddress("nuwanthi@cyclomax.net", "nuwa");
								if(!empty($cust_emal)) {
								$mail1->AddReplyTo($cust_emal, $sql_or['f_name'].' '.$sql_or['l_name']);
								}
								$mail1->IsHTML(true); // set email format to HTML
								$mail1->Subject = "New Order Request - Order ID: ".$inv_no;
								$mail1->Body    = $message1;

								if(!$mail1->Send())
								{
								   //echo "Message could not be sent.";
								   //echo "Mailer Error: " . $mail->ErrorInfo;
								   exit;
								}
							
							} catch(phpmailerException $ex) {
								//$err_msg = $ex->errorMessage();
							}
							
							/*********************** // ************************/
							
							echo json_encode(array("msgType" => 1, "msg" => "Success"));
						
						//}
					}
				
				} else {
					echo json_encode(array("msgType" => 4, "msg" => ""));
				}
			}
	    }
		
		/************************ Reject Order *************************/
		
	    if (array_key_exists('reject_order', $_POST)) {
			$oid = htmlspecialchars(strip_tags(trim($_POST['oid'])), ENT_QUOTES, 'UTF-8');
			if(empty($oid)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
			
			} else {
				$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT order_status FROM order_details WHERE id='$oid'"));
				$st = $sql_or['order_status'];
				
				if($st == 0 || $st == 1) {
					$sql = "UPDATE order_details SET order_status ='2', date_accept=now(), accept_usr='$uid' WHERE id='$oid'";
					$stmt_log = mysqli_query($conn, $sql);
					if( $stmt_log === false ) {
						echo json_encode(array("msgType" => 2, "msg" => "Error"));
					
					} else {
						echo json_encode(array("msgType" => 1, "msg" => "Success"));
					}
				
				} else {
					echo json_encode(array("msgType" => 4, "msg" => ""));
				}
			}
	    }
		
		/************************ Deliver Order *************************/
		
	    if (array_key_exists('deliver_order', $_POST)) {
			$oid = htmlspecialchars(strip_tags(trim($_POST['oid'])), ENT_QUOTES, 'UTF-8');
			if(empty($oid)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
			
			} else {
				$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM order_details WHERE id='$oid'"));
				$st = $sql_or['order_status'];
				$cust_emal = $sql_or['email'];
				$inv_id = $sql_or['inv_no'];
				
				if($st == 1) {
					$sql = "UPDATE order_details SET order_status ='3', date_delivery=now() WHERE id='$oid'";
					$stmt_log = mysqli_query($conn, $sql);
					if( $stmt_log === false ) {
						echo json_encode(array("msgType" => 2, "msg" => "Error"));
					
					} else {
						echo json_encode(array("msgType" => 1, "msg" => "Success"));
						
						/***************** Send Emial ****************/
						
						if($sql_or['delivery_type'] == 1) {
							$del_type = 'Postal';

						} else if($sql_or['delivery_type'] == 2) {
							$del_type = 'Courier Service';

						} else if($sql_or['delivery_type'] == 3) {
							$del_type = 'Expedited Mail Service (EMS)';

						} else if($sql_or['delivery_type'] == 4) {
							$del_type = 'Cash on Delivery';

						} else {
							$del_type = '';
						}
						  
						if($sql_or['pay_method'] == 1) {
							$pay_type = 'Credit/Debit Card';

						} else if($sql_or['pay_method'] == 2) {
							$pay_type = 'Mobile Wallet';
						
						} else if($sql_or['pay_method'] == 3) {
							$pay_type = 'Bank Deposit';
						
						} else if($sql_or['pay_method'] == 4) {
							$pay_type = 'Cash on Delivery';
						
						} else if($sql_or['pay_method'] == 5) {
							$pay_type = 'Internet Banking';
						
						} else {
							$pay_type = '';
						}
						
						$message = '<!DOCTYPE html>
						<html><head><title></title>
						<style>
						body {
						font-family: sans-serif;
						}
						.table .table-bordered {
						border: 1px solid #ccc;
						}
						table {
						border-collapse: collapse;
						}
						.table-bordered th, .table-bordered td {
						border: 1px solid #ccc;
						padding: 6px;
						}
						</style>
						</head><body>
						<p>Dear Mr/Mrs '.$sql_or['f_name'].' '.$sql_or['l_name'].',<br>Your order has been handed over to our shipping partner.</p><p>You can track your order status below.</p><br>
						<table width="100%" border="1">
						<tr>
						<th scope="col"><p style="margin:10px"><strong>Order ID: '.$inv_id.'</strong></p></th>
						</tr>
						</table>
						<br>
						<table style = "width: 100%;" border="0">
						<tr><td style = "width: 15%;"><b>Name:</b> </td><td>'.$sql_or['f_name'].' '.$sql_or['l_name'].'</td></tr>
						<tr><td><b>Delivery Address:</b> </td><td>'.$sql_or['address_1'].' '.$sql_or['address_2'].' '.$sql_or['city'].'</td></tr>
						<tr><td><b>District:</b> </td><td>'.$sql_or['district'].'</td></tr>
						<tr><td><b>Post Code:</b> </td><td>'.$sql_or['postal_code'].'</td></tr>
						<tr><td><b>Country:</b> </td><td>'.$sql_or['country'].'</td></tr>
						<tr><td><b>Contact No:</b> </td><td>'.$sql_or['tel_no'].'</td></tr>
						<tr><td><b>Email:</b> </td><td>'.$sql_or['email'].'</td></tr>
						</table>
						<br>
						<table style = "width: 100%;margin-top: 20px;" border="0">
						<tr><td  style = "width: 15%;"><b>Order Date:</b> </td><td>'.$sql_or['order_date'].'</td></tr>
						<tr><td><b>Total Amount:</b> </td><td>LKR '.$sql_or['grand_total'].'</td></tr>
						<tr><td><b>Payment Method:</b> </td><td>'.$pay_type.'</td></tr>
						<tr><td><b>Delivery Method:</b> </td><td>'.$del_type.'</td></tr>
						<tr><td><b>Order Status:</b> </td><td>Delivery Pending</td></tr>
						<tr><td><b>Date:</b> </td><td>'.date('Y-m-d H:i:s').'</td></tr>
						</table>
						<br>		  
						<table width="100%" class="table table-bordered">
						<tr>
						<th width="25%" align="left">Product Name</th>
						<th width="20%" align="left">ISBN</th>
						<th width="15%" align="right">Unit Price (Rs)</th>
						<th width="15%" align="right">Discounted Price (Rs)</th>
						<th width="10%" align="right">Qty</th>
						<th width="15%" align="right">Subtotal (Rs)</th>
						</tr>';
						$sql_c = mysqli_query($conn, "SELECT * FROM cart_details WHERE inv_no = '$inv_id'");
						$sub = 0;
						$tot_sub = 0;
						$s_tot = $dis_tot = $w_tot = 0;
						while($row_c = mysqli_fetch_array($sql_c)) {
							$message .= '<tr>
							<td align="left">'.$row_c['name'].'</td>
							<td align="left">'.$row_c['isbn'].'</td>
							<td align="right">'.$row_c['item_price'].'</td>
							<td align="right">'.$row_c['price'].'</td>
							<td align="right">'.$row_c['Qty'].'</td>
							<td align="right">'.number_format($row_c['price']*$row_c['Qty'], 2).'</td>
							</tr>';
							$dis_tot += $row_c['price']*$row_c['Qty'];
							$s_tot += $row_c['item_price']*$row_c['Qty'];
						}
						$message .= '<tr>
						<td colspan="5" align="right">
						<h4>Subtotal<br>
						Total Discount<br>
						Total Amount<br>
						Delivery Charges</h4>
						<h3>GRAND TOTAL</h3></td>
						<td align="right">
						<h4>'.number_format($s_tot, 2).'<br>
						'.number_format($s_tot - $dis_tot, 2).'<br>
						'.number_format($dis_tot, 2).'<br>
						'.number_format($sql_or['delivery_chg'], 2).'</h4>
						<h3>LKR '.number_format($sql_or['grand_total'], 2).'</h3>
						</td></tr>
						</table>
						<br>
						Thank you for using our online shopping system.<br>
						www.buddhistbooksonline.com<br>
						<p><img src="https://buddhistbooksonline.com/images/logo/logo.png" width="250" style = "margin : 20px 0;"></p>
						Samudra Book Shop<br>
						Contact No: (+94) 37 223 4446<br>
						Website: www.samudrabooks.com<br>
						</body></html>';
						
						//echo $message;
						
						try {
							$mail = new PHPMailer();
							$mail->IsSMTP(); // set mailer to use SMTP
							$mail->Host = $email_host;  // specify main and backup server
							$mail->SMTPAuth = true;     // turn on SMTP authentication
							$mail->Username = $server_email_add;  // SMTP username
							$mail->Password = $server_email_pw; // SMTP password
							$mail->SMTPSecure = 'ssl';
							$mail->Port = 465;
							$mail->From = $server_email_from;
							$mail->FromName = "buddhistbooksonline.com";
							if(!empty($cust_emal)) {
							$mail->AddAddress($cust_emal, $sql_or['f_name'].' '.$sql_or['l_name']);
							}
							$mail->AddBCC("nirmal@samudrabooks.com", "Nirmal Ranasinghe");
							//$mail->AddBCC("nuwanthi@cyclomax.net", "nuwa");
							//$mail->AddBCC("nuwanthir0@gmail.com", "nuwa");
							$mail->AddReplyTo("info@buddhistbooksonline.com", "buddhistbooksonline.com");
							$mail->IsHTML(true); // set email format to HTML
							$mail->Subject = "Product Dispatch Confirmation - Order ID: ".$inv_id;
							$mail->Body    = $message;

							if(!$mail->Send())
							{
							   //echo "Message could not be sent.";
							   //echo "Mailer Error: " . $mail->ErrorInfo;
							   exit;
							}
						
						} catch(phpmailerException $ex) {
							//$err_msg = $ex->errorMessage();
						}

						/********************* // *******************/
					}

				} else {
					echo json_encode(array("msgType" => 4, "msg" => ""));
				}
			}
	    }
		
		/************************ Deliver Order Finish *************************/
		
	    if (array_key_exists('deliver_order_finish', $_POST)) {
			$oid = htmlspecialchars(strip_tags(trim($_POST['oid'])), ENT_QUOTES, 'UTF-8');
			if(empty($oid)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
			
			} else {
				$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM order_details WHERE id='$oid'"));
				$st = $sql_or['order_status'];
				$cust_emal = $sql_or['email'];
				$inv_id = $sql_or['inv_no'];
				
				if($st == 3) {
					$sql = "UPDATE order_details SET order_status ='4', date_del_confirm=now() WHERE id='$oid'";
					$stmt_log = mysqli_query($conn, $sql);
					if( $stmt_log === false ) {
						echo json_encode(array("msgType" => 2, "msg" => "Error"));
					
					} else {
						echo json_encode(array("msgType" => 1, "msg" => "Success"));
						
						/***************** Send Emial ****************/
						
						if($sql_or['delivery_type'] == 1) {
							$del_type = 'Postal';

						} else if($sql_or['delivery_type'] == 2) {
							$del_type = 'Courier Service';

						} else if($sql_or['delivery_type'] == 3) {
							$del_type = 'Expedited Mail Service (EMS)';

						} else if($sql_or['delivery_type'] == 4) {
							$del_type = 'Cash on Delivery';

						} else {
							$del_type = '';
						}
						  
						if($sql_or['pay_method'] == 1) {
							$pay_type = 'Credit/Debit Card';

						} else if($sql_or['pay_method'] == 2) {
							$pay_type = 'Mobile Wallet';
						
						} else if($sql_or['pay_method'] == 3) {
							$pay_type = 'Bank Deposit';
						
						} else if($sql_or['pay_method'] == 4) {
							$pay_type = 'Cash on Delivery';
						
						} else if($sql_or['pay_method'] == 5) {
							$pay_type = 'Internet Banking';
						
						} else {
							$pay_type = '';
						}
						
						$message = '<!DOCTYPE html>
						<html><head><title></title>
						<style>
						body {
						font-family: sans-serif;
						}
						.table .table-bordered {
						border: 1px solid #ccc;
						}
						table {
						border-collapse: collapse;
						}
						.table-bordered th, .table-bordered td {
						border: 1px solid #ccc;
						padding: 6px;
						}
						</style>
						</head><body>
						<p>Dear Mr/Mrs '.$sql_or['f_name'].' '.$sql_or['l_name'].',<br>Your order has been delivered.</p><p>You can track your order status below.</p><br>
						<table width="100%" border="1">
						<tr>
						<th scope="col"><p style="margin:10px"><strong>Order ID: '.$inv_id.'</strong></p></th>
						</tr>
						</table>
						<br>
						<table style = "width: 100%;" border="0">
						<tr><td style = "width: 15%;"><b>Name:</b> </td><td>'.$sql_or['f_name'].' '.$sql_or['l_name'].'</td></tr>
						<tr><td><b>Delivery Address:</b> </td><td>'.$sql_or['address_1'].' '.$sql_or['address_2'].' '.$sql_or['city'].'</td></tr>
						<tr><td><b>District:</b> </td><td>'.$sql_or['district'].'</td></tr>
						<tr><td><b>Post Code:</b> </td><td>'.$sql_or['postal_code'].'</td></tr>
						<tr><td><b>Country:</b> </td><td>'.$sql_or['country'].'</td></tr>
						<tr><td><b>Contact No:</b> </td><td>'.$sql_or['tel_no'].'</td></tr>
						<tr><td><b>Email:</b> </td><td>'.$sql_or['email'].'</td></tr>
						</table>
						<br>
						<table style = "width: 100%;margin-top: 20px;" border="0">
						<tr><td  style = "width: 15%;"><b>Order Date:</b> </td><td>'.$sql_or['order_date'].'</td></tr>
						<tr><td><b>Total Amount:</b> </td><td>LKR '.$sql_or['grand_total'].'</td></tr>
						<tr><td><b>Payment Method:</b> </td><td>'.$pay_type.'</td></tr>
						<tr><td><b>Delivery Method:</b> </td><td>'.$del_type.'</td></tr>
						<tr><td><b>Order Status:</b> </td><td>Delivered</td></tr>
						<tr><td><b>Date:</b> </td><td>'.date('Y-m-d H:i:s').'</td></tr>
						</table>
						<br>		  
						<table width="100%" class="table table-bordered">
						<tr>
						<th width="25%" align="left">Product Name</th>
						<th width="20%" align="left">ISBN</th>
						<th width="15%" align="right">Unit Price (Rs)</th>
						<th width="15%" align="right">Discounted Price (Rs)</th>
						<th width="10%" align="right">Qty</th>
						<th width="15%" align="right">Subtotal (Rs)</th>
						</tr>';
						$sql_c = mysqli_query($conn, "SELECT * FROM cart_details WHERE inv_no = '$inv_id'");
						$sub = 0;
						$tot_sub = 0;
						$s_tot = $dis_tot = $w_tot = 0;
						while($row_c = mysqli_fetch_array($sql_c)) {
							$message .= '<tr>
							<td align="left">'.$row_c['name'].'</td>
							<td align="left">'.$row_c['isbn'].'</td>
							<td align="right">'.$row_c['item_price'].'</td>
							<td align="right">'.$row_c['price'].'</td>
							<td align="right">'.$row_c['Qty'].'</td>
							<td align="right">'.number_format($row_c['price']*$row_c['Qty'], 2).'</td>
							</tr>';
							$dis_tot += $row_c['price']*$row_c['Qty'];
							$s_tot += $row_c['item_price']*$row_c['Qty'];
						}
						$message .= '<tr>
						<td colspan="5" align="right">
						<h4>Subtotal<br>
						Total Discount<br>
						Total Amount<br>
						Delivery Charges</h4>
						<h3>GRAND TOTAL</h3></td>
						<td align="right">
						<h4>'.number_format($s_tot, 2).'<br>
						'.number_format($s_tot - $dis_tot, 2).'<br>
						'.number_format($dis_tot, 2).'<br>
						'.number_format($sql_or['delivery_chg'], 2).'</h4>
						<h3>LKR '.number_format($sql_or['grand_total'], 2).'</h3>
						</td></tr>
						</table>
						<br>
						Thank you for using our online shopping system.<br>
						www.buddhistbooksonline.com<br>
						<p><img src="https://buddhistbooksonline.com/images/logo/logo.png" width="250" style = "margin : 20px 0;"></p>
						Samudra Book Shop<br>
						Contact No: (+94) 37 223 4446<br>
						Website: www.samudrabooks.com<br>
						</body></html>';
						
						//echo $message;
						
						try {
							$mail = new PHPMailer();
							$mail->IsSMTP(); // set mailer to use SMTP
							$mail->Host = $email_host;  // specify main and backup server
							$mail->SMTPAuth = true;     // turn on SMTP authentication
							$mail->Username = $server_email_add;  // SMTP username
							$mail->Password = $server_email_pw; // SMTP password
							$mail->SMTPSecure = 'ssl';
							$mail->Port = 465;
							$mail->From = $server_email_from;
							$mail->FromName = "buddhistbooksonline.com";
							if(!empty($cust_emal)) {
							$mail->AddAddress($cust_emal, $sql_or['f_name'].' '.$sql_or['l_name']);
							}
							$mail->AddBCC("nirmal@samudrabooks.com", "Nirmal Ranasinghe");
							//$mail->AddBCC("nuwanthi@cyclomax.net", "nuwa");
							//$mail->AddBCC("nuwanthir0@gmail.com", "nuwa");
							$mail->AddReplyTo("info@buddhistbooksonline.com", "buddhistbooksonline.com");
							$mail->IsHTML(true); // set email format to HTML
							$mail->Subject = "Order Delivery Confirmation - Order ID: ".$inv_id;
							$mail->Body    = $message;

							if(!$mail->Send())
							{
							   //echo "Message could not be sent.";
							   //echo "Mailer Error: " . $mail->ErrorInfo;
							   exit;
							}
						
						} catch(phpmailerException $ex) {
							//$err_msg = $ex->errorMessage();
						}

						/********************* // *******************/
					}
				
				} else {
					echo json_encode(array("msgType" => 4, "msg" => ""));
				}
			}
	    }
		
		/************************ Deliver Order Finish *************************/
		
	    if (array_key_exists('order_finish', $_POST)) {
			$oid = htmlspecialchars(strip_tags(trim($_POST['oid'])), ENT_QUOTES, 'UTF-8');
			if(empty($oid)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
			
			} else {
				$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT order_status FROM order_details WHERE id='$oid'"));
				$st = $sql_or['order_status'];
				
				if($st == 4) {
					$sql = "UPDATE order_details SET order_status ='5', date_finish=now() WHERE id='$oid'";
					$stmt_log = mysqli_query($conn, $sql);
					if( $stmt_log === false ) {
						echo json_encode(array("msgType" => 2, "msg" => "Error"));
					
					} else {
						echo json_encode(array("msgType" => 1, "msg" => "Success"));
					}
				
				} else {
					echo json_encode(array("msgType" => 4, "msg" => ""));
				}
			}
	    }
		
		/********************* Admin Password Validation *********************/

		if (array_key_exists('validate_admin_pw', $_POST)) {
			$pass = htmlspecialchars(strip_tags(trim($_POST['pwd'])), ENT_QUOTES, 'UTF-8');
			$upass = hash('sha256', $pass);
			
			//'B3212';
			
			if(empty($pass)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
				
			} else {
				if($upass == '0d8d867f633668762f65078680d3d443ec254ad83e975dbb4d996f52c0722c84') {
					echo json_encode(array("msgType" => 1, "msg" => "Success"));
				
				} else {
					echo json_encode(array("msgType" => 2, "msg" => "Error"));
				}
			}
		}
		
		/************************ Get Sale Items ************************/
		
		if (array_key_exists('get_item_list', $_POST)) {
			$ref_id = htmlspecialchars(strip_tags(trim($_POST['ref_id'])), ENT_QUOTES, 'UTF-8');
			
			if(empty($ref_id)) {
			
			} else {
				$sql = "SELECT
	bookdetails.name,
	bookdetails.isbn,
	stock.cr_qty
	FROM
	stock
	Inner Join bookdetails ON stock.stock_card = bookdetails.id
	WHERE
	stock.ref = '$ref_id'";
				$result = mysqli_query($conn, $sql);
				if(mysqli_num_rows($result) > 0) {
					while($row = mysqli_fetch_assoc($result)) {
						$data[] = $row;	
					}
					echo json_encode($data);
				}
			}
		}
		
		/*********************** Update Ref No **********************/

		if (array_key_exists('update_ref_no', $_POST)) {
			$ref_no = htmlspecialchars(trim(strip_tags($_POST['ref_no'])), ENT_QUOTES, 'UTF-8');
			$inv = htmlspecialchars(trim(strip_tags($_POST['inv'])), ENT_QUOTES, 'UTF-8');

			if(empty($ref_no) || empty($inv)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));

			} else {
				$sql = mysqli_query($conn, "SELECT ref_no FROM cashon_del_verify WHERE ref_no='$ref_no'");	
				$sql1 = mysqli_query($conn, "SELECT order_id FROM cashon_del_verify WHERE order_id ='$inv'");	
				
				if(mysqli_num_rows($sql1) == 0) {
					if(mysqli_num_rows($sql) == 0) {
						$sqlu = "INSERT INTO cashon_del_verify SET order_id ='$inv', accept_date=now(), status=1, user='$uid', ref_no='$ref_no'";
						$result = mysqli_query($conn, $sqlu);
						
						if ($result) {
							mysqli_query($conn, "UPDATE order_details SET payment_status=1 WHERE inv_no='$inv'");
							echo json_encode(array("msgType" => 1, "msg" => "Success"));
							
						} else {
							echo json_encode(array("msgType" => 4, "msg" => "Error"));
						}
					
					} else {
						echo json_encode(array("msgType" => 2, "msg" => "Exist"));
					}
				
				} else {
					$sqlinv = mysqli_query($conn, "SELECT ref_no FROM cashon_del_verify WHERE ref_no='$ref_no' AND order_id != '$inv'");	
					
					if(mysqli_num_rows($sqlinv) == 0) {
						$sqlu = "UPDATE cashon_del_verify SET accept_date=now(), status=1, user='$uid', ref_no='$ref_no' WHERE order_id ='$inv'";
						$result = mysqli_query($conn, $sqlu);
						
						if ($result) {
							mysqli_query($conn, "UPDATE order_details SET payment_status=1 WHERE inv_no='$inv'");
							echo json_encode(array("msgType" => 1, "msg" => "Success"));
							
						} else {
							echo json_encode(array("msgType" => 4, "msg" => "Error"));
						}
					
					} else {
						echo json_encode(array("msgType" => 2, "msg" => "Exist"));
					}
				}
			}
		}
		
		/************************** Order Finish Cash ********************************/
		
		if (array_key_exists('order_finish_cash', $_POST)) {	
			$oid = htmlspecialchars(strip_tags(trim($_POST['oid'])), ENT_QUOTES, 'UTF-8');
			if(empty($oid)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
			
			} else {
				$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT order_status, inv_no FROM order_details WHERE id='$oid'"));
				$st = $sql_or['order_status'];
				$inv_id = $sql_or['inv_no'];
				
				if($st == 4) {
					$sql1 = mysqli_query($conn, "SELECT * FROM cashon_del_verify WHERE order_id ='$inv_id' AND status=1");
					if(mysqli_num_rows($sql1) == 0) {
						echo json_encode(array("msgType" => 5, "msg" => "Invalid"));
					
					} else {
						$sql = "UPDATE order_details SET order_status ='5', date_finish=now() WHERE id='$oid'";
						$stmt_log = mysqli_query($conn, $sql);
						if( $stmt_log === false ) {
							echo json_encode(array("msgType" => 2, "msg" => "Error"));
						
						} else {
							echo json_encode(array("msgType" => 1, "msg" => "Success"));
						}
					}
				
				} else {
					echo json_encode(array("msgType" => 4, "msg" => ""));
				}
			}
		}
		
		if (array_key_exists('reject_bank_deposit', $_POST)) {
			$oid = htmlspecialchars(strip_tags(trim($_POST['oid'])), ENT_QUOTES, 'UTF-8');
			if(empty($oid)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));
			
			} else {
				$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT order_status FROM order_details WHERE id='$oid'"));
				$st = $sql_or['order_status'];
				
				if($st == 0) {
					$sql = "UPDATE order_details SET payment_status ='2' WHERE id='$oid'";
					$stmt_log = mysqli_query($conn, $sql);
					if( $stmt_log === false ) {
						echo json_encode(array("msgType" => 2, "msg" => "Error"));
					
					} else {
						echo json_encode(array("msgType" => 1, "msg" => "Success"));
					}
					
				} else {
					echo json_encode(array("msgType" => 4, "msg" => ""));
				}
			}
		}
		
		/*********************** Update Slip No **********************/

		if (array_key_exists('update_slip_no', $_POST)) {
			$slip_no = htmlspecialchars(trim(strip_tags($_POST['slip_no'])), ENT_QUOTES, 'UTF-8');
			$inv = htmlspecialchars(trim(strip_tags($_POST['inv'])), ENT_QUOTES, 'UTF-8');
			$oid = htmlspecialchars(trim(strip_tags($_POST['oid'])), ENT_QUOTES, 'UTF-8');

			if(empty($slip_no) || empty($inv) || empty($oid)) {
				echo json_encode(array("msgType" => 3, "msg" => "Empty"));

			} else {
				$sql = mysqli_query($conn, "SELECT slip_no FROM bank_deposit_verify WHERE slip_no='$slip_no'");	
				$sql1 = mysqli_query($conn, "SELECT order_id FROM bank_deposit_verify WHERE order_id ='$inv'");	
				
				if(mysqli_num_rows($sql1) == 0 && mysqli_num_rows($sql) == 0) {
					$sqlu = "INSERT INTO bank_deposit_verify SET order_id ='$inv', accept_date=now(), status=1, user='$uid', slip_no='$slip_no'";
					$result = mysqli_query($conn, $sqlu);
					
					if ($result) {
						mysqli_query($conn, "UPDATE order_details SET payment_status=1 WHERE inv_no='$inv' AND id='$oid'");
						echo json_encode(array("msgType" => 1, "msg" => "Success"));
						
						$sql_or = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM order_details WHERE inv_no='$inv'"));
						$cust_emal = $sql_or['email'];
							
						if(!empty($cust_emal)) {
							$message = '<!DOCTYPE html>
							<html><head><title></title>
							<style>
							body {
							font-family: sans-serif;
							}
							.table .table-bordered {
							border: 1px solid #ccc;
							}
							table {
							border-collapse: collapse;
							}
							.table-bordered th, .table-bordered td {
							border: 1px solid #ccc;
							padding: 6px;
							}
							</style>
							</head><body>
							<p>Dear Mr/Mrs '.$sql_or['f_name'].' '.$sql_or['l_name'].',<br>Your payment has been verified.</p>
							<br>
							<table width="100%" border="1">
							<tr>
							<th scope="col"><p style="margin:10px"><strong>Payment Verified</strong></p></th>
							</tr>
							</table>
							<br>
							<p>You can track your payment status below.</p>
							<table style = "width: 100%;margin-top: 10px;" border="0">
							<tr><td style = "width: 15%;"><h3><b>Order ID:</b></h3> </td><td><h3><b>'.$sql_or['inv_no'].'</b></h3></td></tr>
							<tr><td><b>Order Date:</b> </td><td>'.$sql_or['order_date'].'</td></tr>
							<tr><td><b>Total Amount:</b> </td><td>LKR '.$sql_or['grand_total'].'</td></tr>
							<tr><td><b>Slip No:</b> </td><td>'.$slip_no.'</td></tr>
							<tr><td><b>Payment Status:</b> </td><td>Accepted</td></tr>
							<tr><td><b>Date:</b> </td><td>'.date('Y-m-d H:i:s').'</td></tr>
							</table>
							<br><br>
							Thank you for using our online shopping system.<br>
							www.buddhistbooksonline.com<br>
							<p><img src="https://buddhistbooksonline.com/images/logo/logo.png" width="250" style = "margin : 20px 0;"></p>
							Samudra Book Shop<br>
							Contact No: (+94) 37 223 4446<br>
							Website: www.samudrabooks.com<br>
							</body></html>';
							
							//echo $message;
							try {
								$mail = new PHPMailer();
								$mail->IsSMTP(); // set mailer to use SMTP
								$mail->Host = $email_host;  // specify main and backup server
								$mail->SMTPAuth = true;     // turn on SMTP authentication
								$mail->Username = $server_email_add;  // SMTP username
								$mail->Password = $server_email_pw; // SMTP password
								$mail->SMTPSecure = 'ssl';
								$mail->Port = 465;
								$mail->From = $server_email_from;
								$mail->FromName = "buddhistbooksonline.com";
								$mail->AddAddress($cust_emal, $sql_or['f_name'].' '.$sql_or['l_name']);
								$mail->AddReplyTo("info@buddhistbooksonline.com", "buddhistbooksonline.com");
								$mail->IsHTML(true); // set email format to HTML
								$mail->Subject = "Payment Verified - Order ID: ".$sql_or['inv_no'];
								$mail->Body    = $message;

								if(!$mail->Send())
								{
								   //echo "Message could not be sent.";
								   //echo "Mailer Error: " . $mail->ErrorInfo;
								   exit;
								}
							
							} catch(phpmailerException $ex) {
								//$err_msg = $ex->errorMessage();
							}
						}
						
					} else {
						echo json_encode(array("msgType" => 4, "msg" => "Error"));
					}
				
				} else {
					echo json_encode(array("msgType" => 2, "msg" => "Exist"));
				}
			}
		}
		
		/**************************************************************/
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>