<?php 

include '../backend/db/db.php';

session_start();

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




if (isset($_SESSION['normal_user_bb']) || isset($_SESSION['guest_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';
	} else if (isset($_SESSION['temp_user_bb'])) {
		$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
		$whr = 'temp_id';
	}

	$sql = mysqli_query($conn, "SELECT inv_no, order_id FROM live_cart WHERE $whr='$user_id' GROUP BY $whr");
	if(mysqli_num_rows($sql) == 1) {
		$row = mysqli_fetch_assoc($sql);
		$inv_id = $row['inv_no'];
		$order_id = $row['order_id'];

		date_default_timezone_set('Asia/Colombo');
		$date = date('Y-m-d');
		$datetime = date('Y-m-d H:i:s');


	/****************************** Payment Verify **********************************/
		$sqlu = "SELECT * FROM order_details_temp WHERE user_id='$user_id' AND inv_no='$inv_id'";
		$resultu = mysqli_query($conn, $sqlu);
		$countu = mysqli_num_rows($resultu);

		if($countu > 0) {
			if (array_key_exists('payment_confirm', $_POST)) {
				$pay_type_val = htmlspecialchars(strip_tags(trim($_POST['pay_type'])), ENT_QUOTES, 'UTF-8');
				$tel_no = htmlspecialchars(strip_tags(trim($_POST['phone'])), ENT_QUOTES, 'UTF-8');
				if(empty($pay_type_val)) {
					$response['status'] = 'empty';
				} else {
					$sql_t = "INSERT INTO order_details (inv_no, user_id, f_name, l_name, name, phone, email, address, city, district, country, postal_code, delivery_type, s_instructions, order_status, payment_status, date, g_total, guest, order_date, payment_type) SELECT inv_no, user_id, f_name, l_name, name, phone, email, address, city, district, country, postal_code, delivery_type, s_instructions, order_status, payment_status, date, g_total, guest, '$datetime', '$pay_type_val' FROM order_details_temp WHERE user_id='$user_id' AND inv_no='$inv_id' LIMIT 1";

/*********************************** reduce stock ****************************************/
					$sql5 = "SELECT * FROM live_cart where $whr = '$user_id' AND  inv_no='$inv_id' ";
					$result5 = mysqli_query($conn, $sql5);
					mysqli_query($conn, "UPDATE invoice_no SET stock=stock+1");
					$sql_inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT stock FROM invoice_no"));
					$ref = $sql_inv['stock'];

					$sql_stk = "INSERT INTO stock_orders SET supp_id='', sup_acc='', type='SALE', invoice='$inv_id', ref='$ref', p_order='', stock_date='', stock_time='', date=now(), time=CURTIME(), userID=''";
					$stmt_log = mysqli_query($conn, $sql_stk);

					while ($row5 = mysqli_fetch_array($result5)) {
						$item = $row5['Item_Code'];
						$qty = $row5['Qty'];

						$sql4 = "INSERT INTO stock SET stock_card='$item', ref='$ref', discount='0',  unit_cost='0', dr_qty='0', cr_qty='$qty', stock_date=now(), date=now(), supp_id='0',r_price='0'";
						$result2 = mysqli_query($conn, $sql4);

						$stmt_log2 = mysqli_query($conn,"SELECT SUM(cr_qty) AS cr, SUM(dr_qty) AS dr FROM stock where stock_card='$item'");

						$result3 = mysqli_fetch_assoc($stmt_log2);
						$bal = $result3['dr']-$result3['cr'];
						$stmt_log3 = mysqli_query($conn,"UPDATE items SET qty = '$bal' where id='$item' ");

					}
/********************************************************************************************/
					if(mysqli_query($conn, $sql_t)) {
						mysqli_query($conn, "DELETE FROM order_details_temp WHERE user_id='$user_id' AND inv_no='$inv_id'");

						$sqlc = "INSERT INTO cart_details (user_id, Item_Code, Item, Qty, price, order_id, inv_no, order_date, item_price) SELECT User_ID, Item_Code, name, Qty, price, order_id, inv_no, order_date, item_price FROM live_cart WHERE $whr = '$user_id' AND inv_no='$inv_id'";

						if(mysqli_query($conn, $sqlc)) {
							mysqli_query($conn, "DELETE FROM live_cart WHERE $whr = '$user_id' AND inv_no='$inv_id'");

							if (isset($_SESSION['normal_user_bb'])) {
								$new_oid = $order_id + 1;
								mysqli_query($conn, "UPDATE user SET order_id=$new_oid WHERE id=$user_id");

							} else if (isset($_SESSION['temp_user_bb'])) {
								unset($_SESSION['temp_user_bb']);
								unset($_SESSION['guest_user_bb']);
							}
						}

						
						/******************* 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>
								Sudila Printers<br>
								Contact No: (+94) 37 223 4446<br>
								Website: sudila.esrilanka.org<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("nirmal11@samudrabooks.com", "Nirmal Ranasinghe");
								$mail1->AddAddress("keshnijay@gmail.com", "nuwa");
								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();
							}
							
							/********************* // **********************/
						}
					}
					



		

echo json_encode($response);

function send_sms_fun($inv_id,$contact,$g_total) {

	$SMS_tp = $contact;              
	$cus_msg = "Your order has been successfully placed. Order ID : ".$inv_id.". Order Amount : ".$g_total.". Thank you!";

	$url= 'https://smsserver.textorigins.com/Send_sms?';

	$data_sms = array(
              'src' => 'Sampathbay', //Mask
              'email' => 'kurunegala20021@gmail.com', //User Email
              'pwd' => 'Kur66556', //User Password
              'msg' => $cus_msg, //Message
              'dst' => $SMS_tp,); //Phone Number

	$msg = http_build_query($data_sms);

	$url .= $msg;
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_exec($ch);

	$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);

}

function send_sms_fun2($inv_id,$g_total) {

	$owner_msg = "Order has been placed. Order ID : ".$inv_id.". Order Amount : ".$g_total.".";

	$url= 'https://smsserver.textorigins.com/Send_sms?';
	// $resultData = ['0769447707','0779509500'];
	// $pnumbers=implode(",", $resultData);

	$data_sms = array(
              'src' => 'Sampathbay', //Mask
              'email' => 'kurunegala20021@gmail.com', //User Email
              'pwd' => 'Kur66556', //User Password
              'msg' => $owner_msg, //Message
              'dst' => '0777440440',); //Phone Number
              // 'dst' => $pnumbers); //Phone Number

	$msg = http_build_query($data_sms);

	$url .= $msg;
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_exec($ch);

	$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);

}

function send_sms_fun3($inv_id,$g_total) {

	$owner_msg = "Order has been placed. Order ID : ".$inv_id.". Order Amount : ".$g_total.".";

	$url= 'https://smsserver.textorigins.com/Send_sms?';
	// $resultData = ['0769447707','0779509500'];
	// $pnumbers=implode(",", $resultData);

	$data_sms = array(
              'src' => 'Sampathbay', //Mask
              'email' => 'kurunegala20021@gmail.com', //User Email
              'pwd' => 'Kur66556', //User Password
              'msg' => $owner_msg, //Message
              'dst' => '0779509500',); //Phone Number
              // 'dst' => $pnumbers); //Phone Number

	$msg = http_build_query($data_sms);

	$url .= $msg;
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_exec($ch);

	$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);

}
if (array_key_exists('up_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 payment_type=$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['status'] = 'error';
	}

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

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

?>