<?php
include '../db/db.php';
session_start();
$log= htmlspecialchars(trim($_SESSION['user']), ENT_QUOTES, 'UTF-8');
if (empty($log)) {

  $redirectUrl = "../index.php";
  echo "<script type=\"text/javascript\">";
  echo "window.location.href = '$redirectUrl'";
  echo "</script>";

}else{

  $sqlu="SELECT * FROM details_of_users WHERE user='$log' and val='1'";
  $resultu=mysqli_query($conn, $sqlu);
  $countu=mysqli_num_rows($resultu);

	if($countu==1){

		if (array_key_exists('code_validation', $_POST)) {//data table

			$response = [];
			$code = htmlspecialchars(trim($_POST['val']), ENT_QUOTES, 'UTF-8');

			//echo $qty . " " . $ref;

			$sql = "SELECT * FROM `discount_table` WHERE `key` = '$code'";
			$result = mysqli_query($conn, $sql);
			$rowcount=mysqli_num_rows($result);

			if ($rowcount == 0) {
				$response = 1;
			}else{
				$response = 0;
			}

			echo json_encode($response);

		}

		if (array_key_exists('cart_code_validation', $_POST)) {//data table

			$response = [];
			$code = htmlspecialchars(trim($_POST['val']), ENT_QUOTES, 'UTF-8');

			//echo $qty . " " . $ref;

			$sql = "SELECT * FROM `discount_table` WHERE `key` = '$code'";
			$result = mysqli_query($conn, $sql);
			$rowcount=mysqli_num_rows($result);

			if ($rowcount == 0) {
				$response['status'] = 1;
			}else{
				$response['status'] = 0;
				$response['discount'] = 10;
			}

			echo json_encode($response);

		}



		if (isset($_POST['dis_val'])) {

			$dis_val = '0';
			$amount = '0';

			$txt_random = htmlspecialchars(trim($_POST['txt_random']), ENT_QUOTES, 'UTF-8');
			$date = htmlspecialchars(trim($_POST['date']), ENT_QUOTES, 'UTF-8');

			if (!empty($_POST['dis_val'])) {
				$dis_val = htmlspecialchars(trim($_POST['dis_val']), ENT_QUOTES, 'UTF-8');
			}

			if (!empty($_POST['dis_amo'])) {
				$amount = htmlspecialchars(trim($_POST['dis_amo']), ENT_QUOTES, 'UTF-8');
			}

			$type = htmlspecialchars(trim($_POST['type']), ENT_QUOTES, 'UTF-8');


			echo $sql = "INSERT INTO discount_table SET `key` = '$txt_random' , date = '$date', type = '$type', amount = '$amount', percentage = '$dis_val', flag = '0'";
			$result = mysqli_query($conn, $sql);

			if ($result) {
				echo "Data inserted";
			}

		}

		if (array_key_exists('delete_item', $_POST)) {
    //echo "in";
		    $id = htmlspecialchars(trim($_POST['id']), ENT_QUOTES, 'UTF-8');
		    //echo $id;
		    $sql = mysqli_query($conn, "DELETE FROM discount_table WHERE id=$id");
		    if ($sql) {
		      $response = 'ok';
		    }else{
		      $response = 'error';
		    }

		    echo json_encode($response);
		    //echo "In";
		  }

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

	}
}

?>