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

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');
		$time = date('H:i:s');
		
		/*************************** Add Supplier GRN ***************************/
		
		if(isset($_POST['country'])) {
			$country = htmlspecialchars(strip_tags(trim($_POST['country'])), ENT_QUOTES, 'UTF-8');


			$stmt1 = mysqli_query($conn, "SELECT country FROM ems_charges WHERE country='$country'");
			$row_count1 = mysqli_num_rows($stmt1);
			


			if($row_count1 == 0 ) {


				$sql = "INSERT INTO ems_charges SET country='$country', g_250='0.00', g_500='0.00', kg_1='0.00',kg_10='0.00',kg_20='0.00',kg_30='0.00',max_kg='0'";
				$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" => 3, "msg" => "data exist")); // order no exist
			}
		}

		/************************ Remove *************************/
		
		if (array_key_exists('remove_data', $_POST)) {
			$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
			
			// $stmt = mysqli_query( $conn, "SELECT sup_id FROM grn_tkn_order WHERE sup_id=$id");
			// $row_count = mysqli_num_rows( $stmt );
			
			// $stmt1 = mysqli_query( $conn, "SELECT country FROM ems_charges WHERE supp_id=$id");
			// $row_count1 = mysqli_num_rows( $stmt1 );

			// if($row_count == 0 ) {
				$sql = "DELETE FROM ems_charges WHERE id=$id";
				$stmt_log = mysqli_query($conn, $sql);
				
				if( $stmt_log === false ) {
					echo json_encode(array("msgType" => 2, "msg" => "Sorry ! not deleted"));

				} else {
					echo json_encode(array("msgType" => 1, "msg" => "Successfully Removed"));
				}

			// } else {
			// 	echo json_encode(array("msgType" => 3, "msg" => "data exist"));
			// }
		}
		
		

		


		

		
		/************************************************************/
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>