<?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){
	
	  $sqlc="SELECT * FROM details_of_users where user='$log'";
	  $resultc=mysqli_query($conn, $sqlc);
	  while ($rowc = mysqli_fetch_array($resultc)){
	  $name=$rowc['id'];
	  }
		
		$s_name= htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8');
		$address= htmlspecialchars(trim($_POST['address']), ENT_QUOTES, 'UTF-8');
		$nic= htmlspecialchars(trim($_POST['nic']), ENT_QUOTES, 'UTF-8');
		$mobile= htmlspecialchars(trim($_POST['mobile']), ENT_QUOTES, 'UTF-8');
		$tp= htmlspecialchars(trim($_POST['tp']), ENT_QUOTES, 'UTF-8');
		$note= htmlspecialchars(trim($_POST['note']), ENT_QUOTES, 'UTF-8');
		$v_code = htmlspecialchars(trim($_POST['v_code']), ENT_QUOTES, 'UTF-8');
		
		$B_Code = 6;
		$T_Code = 8;
		$H_Code = 11;
		
		$query = mysqli_query($conn, "SELECT PName FROM account_posting WHERE PName='$s_name'");
		
		if (mysqli_num_rows($query)!= 0){
			echo "<script>alert('Supplier Name Already Exist!')</script>";
			$redirectUrl = "../add_supplier.php";
			echo "<script type=\"text/javascript\">";
			echo "window.location.href = '$redirectUrl'";
			echo "</script>";  	 

		} else {


			$sql6 = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM account_numbers"));
			$PR_Code2 = $sql6['PR_Code'];
			$PR_Code = $PR_Code2+1;
			
			$B_Code= htmlspecialchars(trim($B_Code), ENT_QUOTES, 'UTF-8');
			$T_Code= htmlspecialchars(trim($T_Code), ENT_QUOTES, 'UTF-8');
			$H_Code= htmlspecialchars(trim($H_Code), ENT_QUOTES, 'UTF-8');
			$PR_Code= htmlspecialchars(trim($PR_Code), ENT_QUOTES, 'UTF-8');

			$L_Code = $B_Code."-".$T_Code."-".$H_Code."-".$PR_Code;
			$L_Code= htmlspecialchars(trim($L_Code), ENT_QUOTES, 'UTF-8');

			mysqli_query($conn, "UPDATE account_numbers SET PR_Code='$PR_Code'");
			
			mysqli_query($conn, "INSERT INTO account_posting SET P_Code='$PR_Code', PName='$s_name', B_Code='$B_Code', T_Code='$T_Code', H_Code='$H_Code', L_Code='$L_Code'");
			
			mysqli_query($conn, "INSERT INTO supplier SET name='$s_name', address='$address', nic='$nic', mobile='$mobile', tp='$tp', note='$note', acc_no='$L_Code', vender_code='$v_code'");

			echo "<script>alert('Insert Successfully!')</script>";
			$redirectUrl = "../add_supplier.php";
			echo "<script type=\"text/javascript\">";
			echo "window.location.href = '$redirectUrl'";
			echo "</script>"; 
		}

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

?>