<?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");
		// include("resize_class.php");
		
		$dis_val = htmlspecialchars(trim($_POST['dis_val']), ENT_QUOTES, 'UTF-8');
		$select_cat = htmlspecialchars(trim($_POST['select_cat']), ENT_QUOTES, 'UTF-8');
		$date=date('Y-m-d H:i:s');
		
		if(!empty($dis_val)) {
		if(!empty($select_cat)) {
			$select_cat = htmlspecialchars(trim($_POST['select_cat']), ENT_QUOTES, 'UTF-8');
			
			
				mysqli_query($conn,"UPDATE bookdetails SET discount='$dis_val' WHERE id IN (SELECT Book_ID FROM category_map where Cat_ID='$select_cat')");
				mysqli_query($conn,"INSERT INTO discount_b SET user='$log',discount='$dis_val',cat='$select_cat',date='$date'");

				echo "<script>alert('Successfully Updated!')</script>";
				$redirectUr = "../add-new-book.php";
				echo "<script type=\"text/javascript\">";
				echo "window.location.href = '$redirectUr'";
				echo "</script>";
			
		
		} else{

		  if(isset($_POST['sam_all'])) {
			mysqli_query($conn,"UPDATE bookdetails SET discount='$dis_val'");
			mysqli_query($conn,"INSERT INTO discount_b SET user='$log',discount='$dis_val',cat='',date='$date'");

			echo "<script>alert('Successfully !')</script>";
			$redirectUr = "../add-new-book.php";
			echo "<script type=\"text/javascript\">"; 
			echo "window.location.href = '$redirectUr'";
			echo "</script>";
			// echo "<script>alert('Successfully !')</script>";
		}else{
			echo "<script>alert('Something Went Wrong!')</script>";
			$redirectUr = "../add-new-book.php";
			echo "<script type=\"text/javascript\">"; 
			echo "window.location.href = '$redirectUr'";
			echo "</script>";
		}
		}
		

		
	
	}	else {
		echo "<script>alert('Invalid Discount Value!')</script>";
		$redirectUr = "../add-new-book.php";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUr'";
		echo "</script>";		
	}
		
		
	
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>