<?php
include '../backend/db/db.php';
session_start();
	
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;
	$st = 1;

} else if (isset($_SESSION['temp_user_bb']) && isset($_SESSION['guest_user_bb'])) {
	$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
	$whr = 'temp_id';
	$guest = 1;
	$st = 1;

} else {
	$response['status'] = '3';
	echo json_encode($response);
	$st = 0;
}

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

if($st == 1) {
	$sql = mysqli_query($conn, "SELECT order_id, inv_no, SUM(price*Qty) AS sub_tot, SUM(item_price*Qty) AS item_tot, SUM(weight*Qty) 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'];
		$item_tot = $row['item_tot'];
		$sub_tot = $row['sub_tot'];
		$tot_discount = $item_tot-$sub_tot;
		$tot_weight = $row['tot_weight'];
		$order_id = $row['order_id'];
		
		if(empty($inv_id)) {
			$response['status'] = '3';
			echo json_encode($response);
			
		} else {
			if (isset($_SESSION['normal_user_bb']) || isset($_SESSION['guest_user_bb'])) {
			
				/*********************** Get Checkout Details **********************/
				
				if (array_key_exists('get_chkout_details', $_POST)) {
					$sql_tmp = "SELECT f_name, l_name, tel_no, email, address_1, address_2, city, district, country, postal_code, delivery_type, special_msg FROM order_details_temp WHERE inv_no='$inv_id'";
					$result_tmp = mysqli_query($conn, $sql_tmp);
				
					if(mysqli_num_rows($result_tmp) == 0) {
						if (isset($_SESSION['normal_user_bb'])) {
							$sql = mysqli_query($conn, "SELECT f_name, l_name, email, tel_no, address_1, address_2, city FROM customer_reg WHERE cusID=$user_id AND val=1");
							$row = mysqli_fetch_assoc($sql);
							echo json_encode($row);
						
						} else {
							//echo json_encode('');
						}
			
					} else {
						$sqltmp = mysqli_fetch_assoc($result_tmp);
						echo json_encode($sqltmp);
					}
				}

				/****************************** Checkout **********************************/
				if (isset($_POST['btn_checkout'])) {
					$fname = htmlspecialchars(strip_tags(trim($_POST['fname'])), ENT_QUOTES, 'UTF-8');
					$lname = htmlspecialchars(strip_tags(trim($_POST['lname'])), ENT_QUOTES, 'UTF-8');
					$tel_no = htmlspecialchars(strip_tags(trim($_POST['tel_no'])), ENT_QUOTES, 'UTF-8');
					$address_1 = htmlspecialchars(strip_tags(trim($_POST['address_1'])), ENT_QUOTES, 'UTF-8');
					$address_2 = htmlspecialchars(strip_tags(trim($_POST['address_2'])), ENT_QUOTES, 'UTF-8');
					$city = htmlspecialchars(strip_tags(trim($_POST['city'])), ENT_QUOTES, 'UTF-8');
					$email = htmlspecialchars(strip_tags(trim($_POST['email'])), ENT_QUOTES, 'UTF-8');
					$del_method = htmlspecialchars(strip_tags(trim($_POST['del_method'])), ENT_QUOTES, 'UTF-8');
					$postal_code = htmlspecialchars(strip_tags(trim($_POST['postal_code'])), ENT_QUOTES, 'UTF-8');
					$s_msg = htmlspecialchars(strip_tags(trim($_POST['s_msg'])), ENT_QUOTES, 'UTF-8');
					$country = htmlspecialchars(strip_tags(trim($_POST['country'])), ENT_QUOTES, 'UTF-8');

					// Delivery Fee Calculation
					$del_fee = $flag = 0;
					$sql_cou = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM courier_charges"));
					
					if($tot_weight > 0) {
						if($del_method == 1 && $country == 'Sri Lanka') { // Postal
							$sql_del_chg = mysqli_query($conn, "SELECT fee FROM postal_charges WHERE low_w < '$tot_weight' AND high_w >='$tot_weight'");	
							
							if($tot_weight > 20000) { // Max Out 2kg
								$flag = 1;
								
							} else {
								if(mysqli_num_rows($sql_del_chg) == 0) {
									$flag = 1;
									
								} else {
									$row_del_chg = mysqli_fetch_assoc($sql_del_chg);
									$del_fee = $row_del_chg['fee'];
								}
							}
						
						} else if($del_method == 2 && $country == 'Sri Lanka') { // Courier
							$a = floor($tot_weight/1000);
							
							if($tot_weight > 0 && $tot_weight <= 1000) {
								$del_fee = $sql_cou['courier_fee'];
							
							} else {
								$del_fee = $sql_cou['courier_fee'] + ($a * $sql_cou['courier_1kg']);
							}
							
						} else if($del_method == 4 && $country == 'Sri Lanka') { // Cash on Delivery
							$a = floor($tot_weight/1000);

							if($tot_weight >= 0 && $tot_weight <= 1000) {
								$del_fee = $sql_cou['cash_on_del'];

							} else {
								$del_fee = $sql_cou['cash_on_del'] + ($a * $sql_cou['cash_on_1kg']);
							}
						
						} else if($del_method == 3 && $country != 'Sri Lanka') { // International Shipping
							$sql_wgt = mysqli_query($conn, "SELECT * FROM ems_charges WHERE country='$country'");
							if(mysqli_num_rows($sql_wgt) == 0) {
								$flag = 1;
									
							} else {
								$row_wgt = mysqli_fetch_assoc($sql_wgt);
								$max_w = $row_wgt['max_kg']*1000; // Max Weight (g)
								
								if($row_wgt['max_kg'] == 20) {
									if($tot_weight > $max_w) {
										$flag = 1;
									
									} else {
										if($tot_weight > 10000) { // 10001-20000 Grams
											$f = $row_wgt['kg_20'];
											
											$r = $tot_weight - 1000;
											$w = ceil($r/500);
											$del_fee = $row_wgt['kg_1'] + ($w * $f);
										
										} else if($tot_weight > 1000) { // 1001-10000 Grams
											$f = $row_wgt['kg_10'];
											
											$r = $tot_weight - 1000;
											$w = ceil($r/500);
											$del_fee = $row_wgt['kg_1'] + ($w * $f);
										
										} else if($tot_weight > 500) { // 501-1000 Grams
											$del_fee = $row_wgt['kg_1'];
										
										} else if($tot_weight > 250) { // 251-500 Grams
											$del_fee = $row_wgt['g_500'];
										
										} else { // 0-250 Grams
											$del_fee = $row_wgt['g_250'];
										}
										
										$del_fee += 250; // Packing Charges
									}
								
								} else if($row_wgt['max_kg'] == 30) {
									if($tot_weight > $max_w) {
										$flag = 1;

									} else {
										if($tot_weight > 20000) { // 20001-30000 Grams
											$f = $row_wgt['kg_30'];
											
											$r = $tot_weight - 1000;
											$w = ceil($r/500);
											$del_fee = $row_wgt['kg_1'] + ($w * $f);
										
										} else if($tot_weight > 10000) { // 10001-20000 Grams
											$f = $row_wgt['kg_20'];
											
											$r = $tot_weight - 1000;
											$w = ceil($r/500);
											$del_fee = $row_wgt['kg_1'] + ($w * $f);
										
										} else if($tot_weight > 1000) { // 1001-10000 Grams
											$f = $row_wgt['kg_10'];
											
											$r = $tot_weight - 1000;
											$w = ceil($r/500);
											$del_fee = $row_wgt['kg_1'] + ($w * $f);
										
										} else if($tot_weight > 500) { // 501-1000 Grams
											$del_fee = $row_wgt['kg_1'];
										
										} else if($tot_weight > 250) { // 251-500 Grams
											$del_fee = $row_wgt['g_500'];
										
										} else { // 0-250 Grams
											$del_fee = $row_wgt['g_250'];
										}
										
										$del_fee += 250; // Packing Charges
									}
									
								} else {
									$flag = 1;
								}
							}
						
						} else {
							$flag = 1;
						}
					
					} else {
						$flag = 1;
					}
					
					if($flag == 1) {
						$response['status'] = '4';
						$response['message'] = 'Total Weight is Exceeded or Invalid Delivery Method. Please Try Again.';
						
					} else if($del_fee == 0) {
						$response['status'] = '4';
						$response['message'] = 'Invalid Delivery Fee.';
						
					} else {
						$total_val = $sub_tot + $del_fee;
						$sqlu = "SELECT * FROM order_details_temp WHERE user_id = $user_id AND guest=$guest";
						$resultu = mysqli_query($conn, $sqlu);
						$countu = mysqli_num_rows($resultu);

						if($countu == 0) {
							$sql_add_order = "INSERT INTO order_details_temp SET order_id='$order_id', inv_no='$inv_id', user_id=$user_id, guest=$guest, f_name='$fname', l_name='$lname', tel_no='$tel_no', email='$email', address_1='$address_1', address_2='$address_2', city='$city', country='$country', district='', postal_code='$postal_code', special_msg='$s_msg', delivery_type=$del_method, pay_method=0, payment_status=0, order_status=0, price_total='$item_tot', tot_discount='$tot_discount', sub_total='$sub_tot', delivery_chg='$del_fee', grand_total='$total_val', date=now()";
							$result_add_order = mysqli_query($conn,$sql_add_order);

							if ($result_add_order) {
								$response['status'] = '1';
							
							} else {
								$response['status'] = '2';
								$response['message'] = 'MySQL Error! Please Try Again';
							}
						
						} else {
							$sql_add_order = "UPDATE order_details_temp SET order_id='$order_id', inv_no='$inv_id', f_name='$fname', l_name='$lname', tel_no='$tel_no', email='$email', address_1='$address_1', address_2='$address_2', city='$city', district='', country='$country', postal_code='$postal_code', special_msg='$s_msg', delivery_type=$del_method, pay_method=0, payment_status=0, order_status=0, price_total='$item_tot', tot_discount='$tot_discount', sub_total='$sub_tot', delivery_chg='$del_fee', grand_total='$total_val', date=now() WHERE user_id = $user_id AND guest=$guest";
							$result_add_order = mysqli_query($conn,$sql_add_order);

							if ($result_add_order) {
								$response['status'] = '1';
							
							} else {
								$response['status'] = '2';
								$response['message'] = 'MySQL Error! Please Try Again';
							}
						}
					}
					
					echo json_encode($response);
				}	
				
				/****************************** // **********************************/
			
			} else {
				$response['status'] = '3'; // Session Expired
				echo json_encode($response);
			}
		}
		
	} else {
		$response['status'] = '3';
		echo json_encode($response);
	}
}
?>