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

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

date_default_timezone_set('Asia/Colombo');
$date = date('Y-m-d');

if (isset($_SESSION['normal_user_bb']) || (isset($_SESSION['guest_user_bb']) && isset($_SESSION['temp_user_bb']))) {
	if (isset($_SESSION['normal_user_bb'])) {
		$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_bb'])), ENT_QUOTES, 'UTF-8');
		$whr = 'User_ID';
		$guest = 0;
	
	} else if (isset($_SESSION['temp_user_bb'])) {
		$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
		$whr = 'temp_id';
		$guest = 1;
	
	} else {
		$user_id = '';
	}
	
	if(empty($user_id)) {
		$response = '3'; // Invalid Login
		
	} else {
		$sql = mysqli_query($conn, "SELECT order_id, inv_no, SUM(price*Qty) AS sub_tot, SUM(item_price*Qty) AS item_tot, SUM(weight) AS tot_weight FROM live_cart WHERE $whr=$user_id");
		
		if(mysqli_num_rows($sql) == 1) {
			$row = mysqli_fetch_assoc($sql);
			$inv_id = $row['inv_no'];
			$order_id = $row['order_id'];
			
			if(empty($inv_id)) {
				$response['status'] = '3';
				
			} else {
				
				/*************************** Payment Verify Bank ***********************/
				
				$sqlu = "SELECT * FROM order_details_temp WHERE user_id='$user_id' AND inv_no='$inv_id' AND guest=$guest";
				$resultu = mysqli_query($conn, $sqlu);
				$countu = mysqli_num_rows($resultu);
				
				if($countu == 0) {
					$response['status'] = 'error';
				
				} else {
					if (array_key_exists('payment_confirm_bank', $_POST)) {
						$pay_type_val = htmlspecialchars(strip_tags(trim($_POST['pay_type'])), ENT_QUOTES, 'UTF-8');
						
						if(empty($pay_type_val)) {
							$response['status'] = 'empty';
							
						} else {
							$sql_t = "INSERT INTO order_details (order_id, inv_no, user_id, guest, f_name, l_name, tel_no, email, address_1, address_2, city, district, country, postal_code, special_msg, delivery_type, pay_method, payment_status, order_status, price_total, tot_discount, sub_total, delivery_chg, grand_total, date, order_date) SELECT order_id, inv_no, user_id, guest, f_name, l_name, tel_no, email, address_1, address_2, city, district, country, postal_code, special_msg, delivery_type, '$pay_type_val', payment_status, order_status, price_total, tot_discount, sub_total, delivery_chg, grand_total, date, now() FROM order_details_temp WHERE user_id='$user_id' AND inv_no='$inv_id' AND guest=$guest LIMIT 1";
									
							if(mysqli_query($conn, $sql_t)) {
								$sql_od = mysqli_query($conn, "SELECT id FROM order_details WHERE user_id='$user_id' AND inv_no='$inv_id' AND guest=$guest");
								if(mysqli_num_rows($sql_od) == 0) {
									$response['status'] = 'mysql error';
								
								} else {
									$sqlc = mysqli_query($conn, "SELECT * FROM live_cart WHERE $whr = '$user_id' AND inv_no='$inv_id'");
									while($rowc = mysqli_fetch_array($sqlc)) {
										$item = $rowc['Item'];
										$id = $rowc['id'];
										
										$sqlc1 = "INSERT INTO cart_details (User_ID, temp_id, inv_no, Item, name, img, Qty, weight, isbn, item_price, price, order_id, order_date, date) SELECT User_ID, temp_id, inv_no, Item, name, img, Qty, weight, isbn, item_price, price, order_id, date, now() FROM live_cart WHERE id='$id' AND $whr = '$user_id' AND inv_no='$inv_id'";
										
										if(mysqli_query($conn, $sqlc1)) {
											$sql_ct = mysqli_query($conn, "SELECT id FROM cart_details WHERE Item='$item' AND $whr = '$user_id' AND inv_no='$inv_id'");
											if(mysqli_num_rows($sql_ct) == 0) {
											
											} else {
												mysqli_query($conn, "DELETE FROM live_cart WHERE Item='$item' AND $whr = '$user_id' AND inv_no='$inv_id'");
											}
										}
									}
									
									mysqli_query($conn, "DELETE FROM order_details_temp WHERE user_id='$user_id' AND inv_no='$inv_id' AND guest=$guest");
									
									if (isset($_SESSION['normal_user_bb'])) {
										$new_oid = $order_id + 1;
										mysqli_query($conn, "UPDATE customer_reg SET order_id=$new_oid WHERE cusID=$user_id");
									
									} else if (isset($_SESSION['temp_user_bb'])) {
										unset($_SESSION['temp_user_bb']);
										unset($_SESSION['guest_user_bb']);
									}
									
									$response['status'] = 'success';
									$response['inv_id'] = $inv_id;
								}
								
							} else {
								 //echo("Error description: " . mysqli_error($conn));
								 $response['status'] = 'mysql error';
							}
						}
							
						/******************* Customer Email ********************/
			
						$sql_ord = mysqli_query($conn, "SELECT * FROM order_details WHERE inv_no='$inv_id'");
						if(mysqli_num_rows($sql_ord) == 1) {
							$sql_ordr = mysqli_fetch_assoc($sql_ord);
							$cust_emal = $sql_ordr['email'];
							
							if($sql_ordr['delivery_type'] == 1) {
								$del_type = 'Postal';

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

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

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

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

							} else if($sql_ordr['pay_method'] == 2) {
								$pay_type = 'Mobile Wallet';
							
							} else if($sql_ordr['pay_method'] == 3) {
								$pay_type = 'Bank Deposit';
							
							} else if($sql_ordr['pay_method'] == 4) {
								$pay_type = 'Cash on Delivery';
							
							} else if($sql_ordr['pay_method'] == 5) {
								$pay_type = 'Internet Banking';
							
							} else {
								$pay_type = '';
							}
								
							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_ordr['f_name'].' '.$sql_ordr['l_name'].',<br>Thank you for your order. Your order has been received and will be processed once payment has been confirmed.</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 Confirmation</strong></p></th>
								</tr>
								</table>
								<br>
								<table style = "width: 100%;" border="0">
								<tr><td style = "width: 15%;"><b>Name:</b> </td><td>'.$sql_ordr['f_name'].' '.$sql_ordr['l_name'].'</td></tr>
								<tr><td><b>Delivery Address:</b> </td><td>'.$sql_ordr['address_1'].' '.$sql_ordr['address_2'].' '.$sql_ordr['city'].'</td></tr>
								<tr><td><b>District:</b> </td><td>'.$sql_ordr['district'].'</td></tr>
								<tr><td><b>Post Code:</b> </td><td>'.$sql_ordr['postal_code'].'</td></tr>
								<tr><td><b>Country:</b> </td><td>'.$sql_ordr['country'].'</td></tr>
								<tr><td><b>Contact No:</b> </td><td>'.$sql_ordr['tel_no'].'</td></tr>
								<tr><td><b>Email:</b> </td><td>'.$sql_ordr['email'].'</td></tr>
								</table>
								<br>
								<table style = "width: 100%;margin-top: 20px;" border="0">
								<tr><td style = "width: 15%;"><h3><b>Order ID:</b></h3> </td><td><h3><b>'.$inv_id.'</b></h3></td></tr>
								<tr><td><b>Order Date:</b> </td><td>'.$sql_ordr['order_date'].'</td></tr>
								<tr><td><b>Total Amount:</b> </td><td>LKR '.$sql_ordr['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>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_ordr['delivery_chg'], 2).'</h4>
								<h3>LKR '.number_format($sql_ordr['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 = "sudila.esrilanka.org";
									$mail->AddAddress($cust_emal, $sql_ordr['f_name'].' '.$sql_ordr['l_name']);
									$mail->AddReplyTo("info@sudila.com", "sudila.esrilanka.org");
									$mail->IsHTML(true); // set email format to HTML
									$mail->Subject = "Order 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();
								}
							}
			  
							/********************* Company Email **********************/
								  
							$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_id.'</strong></p></th>
							</tr>
							</table>
							<br>
							<table style = "width: 100%;" border="0">
							<tr><td style = "width: 15%;"><b>Name:</b> </td><td>'.$sql_ordr['f_name'].' '.$sql_ordr['l_name'].'</td></tr>
							<tr><td><b>Delivery Address:</b> </td><td>'.$sql_ordr['address_1'].' '.$sql_ordr['address_2'].' '.$sql_ordr['city'].'</td></tr>
							<tr><td><b>District:</b> </td><td>'.$sql_ordr['district'].'</td></tr>
							<tr><td><b>Post Code:</b> </td><td>'.$sql_ordr['postal_code'].'</td></tr>
							<tr><td><b>Country:</b> </td><td>'.$sql_ordr['country'].'</td></tr>
							<tr><td><b>Contact No:</b> </td><td>'.$sql_ordr['tel_no'].'</td></tr>
							<tr><td><b>Email:</b> </td><td>'.$sql_ordr['email'].'</td></tr>
							<tr><td><b>Order Date:</b> </td><td>'.$sql_ordr['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>
							<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)) {
								$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_ordr['delivery_chg'], 2).'</h4>
							<h3>LKR '.number_format($sql_ordr['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 = "sudila.esrilanka.org";
								// $mail1->AddAddress("nirmal@samudrabooks.com", "Nirmal Ranasinghe");
								//$mail1->AddAddress("nuwanthi@cyclomax.net", "nuwa");
								$mail1->AddAddress("keshnijay@gmail", "test");

								if(!empty($cust_emal)) {
								$mail1->AddReplyTo($cust_emal, $sql_ordr['f_name'].' '.$sql_ordr['l_name']);
								}
								$mail1->IsHTML(true); // set email format to HTML
								$mail1->Subject = "New Order Request - Order ID: ".$inv_id;
								$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();
							}
							
							/********************* // **********************/
						}
					}
					
					/************************** // *****************************/
					
					if (array_key_exists('edit_payment_method', $_POST)) {
						$order_id = htmlspecialchars(strip_tags(trim($_POST['inv'])), ENT_QUOTES, 'UTF-8');
						$pay_type = htmlspecialchars(strip_tags(trim($_POST['pay_type'])), ENT_QUOTES, 'UTF-8');
								
						$sql = "UPDATE order_details_temp SET pay_method=$pay_type WHERE inv_no='$order_id'";
						if(!empty($order_id) && !empty($pay_type)) {
							if(mysqli_query($conn, $sql)) {
								$response['status'] = 'success';
							
							} else {
								$response['status'] = 'error';
							}
						
						} else {
							$response['status'] = 'error';
						}
					}
					
					/************************** // **************************/
				}
			}
			
		} else {
			$response = '3'; // Invalid Login
		}
	}

} else {
	$response = '3'; // Invalid Login
}

echo json_encode($response);
?>