<?php
session_start();
require("php_con.php");
require("function.php");

if(isset($_COOKIE['user_id'])){
	$current_user_qury=mysqli_query($connation,"SELECT * FROM user_details WHERE user_id='$_COOKIE[user_id]'");
	$current_user_resalt=mysqli_fetch_array($current_user_qury);
}
else{
	echo "<script>window.location='logout';</script>";
}

$bill_id=mysqli_real_escape_string($connation,$_GET['bill_id']);

$check_bil_id=mysqli_query($connation,"SELECT * FROM sale_details WHERE sale_details_billid='$bill_id'");
if(mysqli_num_rows($check_bil_id)>0){
echo "<script>window.location='bill-payment-update?bill_id=$bill_id';</script>";
}

$qury=mysqli_query($connation,"SELECT COUNT(*) AS total_count,SUM(sl.sale_qty*sl.sale_saleprice) AS amount
FROM sale_list sl WHERE sl.sale_billid='$bill_id'");
$resalt=mysqli_fetch_array($qury);

if(isset($_POST['payment_btn'])){
	$sale_details_billid=mysqli_real_escape_string($connation,$_GET['bill_id']);
	$sale_details_cash_payment=mysqli_real_escape_string($connation,$_POST['sale_details_cash_payment']);
	$sale_details_card_payment=mysqli_real_escape_string($connation,$_POST['sale_details_card_payment']);
	$sale_details_discount=mysqli_real_escape_string($connation,$_POST['sale_details_discount']);
	$sale_details_customer=(int)mysqli_real_escape_string($connation,$_POST['sale_details_customer']);
	
	$sale_details_cus_payment=(float)$sale_details_cash_payment+(float)$sale_details_card_payment;
	
	if(bill_amount($sale_details_billid)>$sale_details_cus_payment){
		
	$new_sale_details_cash_payment=(float)$sale_details_cash_payment;
		
	}
	else{
		
	if(bill_amount($sale_details_billid)==0){
	$new_sale_details_cash_payment=(float)$sale_details_cash_payment;
	}
	else{
	$bill_amount=bill_amount($sale_details_billid);
	$new_sale_details_cash_payment=(float)$bill_amount-(float)$sale_details_card_payment;
	}
		
	}
	
	$sale_details_billid_update=bill_id();
	
	if(mysqli_query($connation,"INSERT INTO
	sale_details (sale_details_id, sale_details_billid, sale_details_cash_payment, sale_details_card_payment, sale_details_cus_payment, sale_details_discount, sale_details_user, sale_details_customer, sale_details_date, sale_details_time)
	VALUES (NULL, '$sale_details_billid_update', '$new_sale_details_cash_payment', '$sale_details_card_payment', '$sale_details_cus_payment', '$sale_details_discount', '$_COOKIE[user_id]', '$sale_details_customer', '$current_date', '$current_time')")){
		
	$update_qury=mysqli_query($connation,"SELECT *
	FROM sale_list sl INNER JOIN product_details pd ON sl.sale_barcode=pd.product_barcode
	WHERE sl.sale_billid='$sale_details_billid'");
	while($update_resalt=mysqli_fetch_assoc($update_qury)){
		if($update_resalt['product_stock_maintain']==1){
			
		if($update_resalt['sale_qty']<0){
			$stock_type=1;
		}
		else{
			$stock_type=0;
		}
			
		
			
		if($update_resalt['product_affect_stock']==1){
			
		$stock_qury=mysqli_query($connation,"SELECT * FROM product_affect_details pad INNER JOIN product_details pd ON pad.pad_product_id=pd.product_id
		WHERE pad.pad_main_product='$update_resalt[product_id]'");
		while($stock_resalt=mysqli_fetch_assoc($stock_qury)){
			
		$sale_qty=abs($update_resalt['sale_qty']*$stock_resalt['pad_qty']);
			
		mysqli_query($connation,"INSERT INTO
		stock_details (stock_id, stock_systemid, stock_bill_id, stock_qty, stock_type, stock_info, stock_addtime)
		VALUES (NULL, '$stock_resalt[product_systemid]', '$sale_details_billid_update', '$sale_qty', '$stock_type', 'Create bill and update stock. Bill: $sale_details_billid_update<br>(Instead of $update_resalt[product_name])', '$current_date $current_time')");
		}
			
		}
		else{
			
		$sale_qty=abs($update_resalt['sale_qty']);
			
		mysqli_query($connation,"INSERT INTO
		stock_details (stock_id, stock_systemid, stock_bill_id, stock_qty, stock_type, stock_info, stock_addtime)
		VALUES (NULL, '$update_resalt[product_systemid]', '$sale_details_billid_update', '$sale_qty', '$stock_type', 'Create bill and update stock. Bill: $sale_details_billid_update', '$current_date $current_time')");
		}
		}
	}		
		mysqli_query($connation,"UPDATE sale_list SET sale_billid='$sale_details_billid_update' WHERE sale_billid='$sale_details_billid'");
		mysqli_query($connation,"UPDATE return_details SET rd_system_id='$sale_details_billid_update' WHERE rd_system_id='$sale_details_billid'");
		
		if(empty($_POST['bill_print'])){
		$_SESSION['bill_print']=0;
		}
		else{
		$_SESSION['bill_print']=1;
		}
		
		echo "<script>window.location='poin-of-sale?print=$sale_details_billid_update';</script>";
	}
	else{
	echo "Error Number: ".mysqli_errno($connation);
	exit();
	}

}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title><?php echo $system_name; ?></title>
<link rel="stylesheet" href="cus_css.css">
	
<script src="data_table/js/jquery-3.5.1.js"></script>
<script src="data_table/js/jquery.dataTables.min.js"></script>
<script src="data_table/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="data_table/css/bootstrap.css">
<link rel="stylesheet" href="data_table/css/dataTables.bootstrap4.min.css">
	
<link rel="stylesheet" href="alert/sweetalert2.min.css">
<script src="alert/sweetalert2.min.js"></script>
	
<link rel="stylesheet" href="icon/css/font-awesome.css">
<link rel="stylesheet" href="icon/css/font-awesome.min.css">
</head>

<body class="bg-light">
<script>
window.addEventListener("load",function(){
	var load_screen=document.getElementById('load_screen');
	document.body.removeChild(load_screen);
});
</script>

<div id="load_screen"><div id="loading"><img src="image/loading.gif" width="80px;"></div></div>
	
	
<div class="container">
  <div class="row mt-4">
		<div class="col-lg-4 col-sm-12 m-auto card p-2">					
			<form method="post" autocomplete="off">
			<table class="table table-sm table-borderless">
				<tbody>
					<tr>
					  <td colspan="2" align="center" valign="middle" style="background-color: black;" class="pb-0"><h1 class="font-weight-bold text-warning" id="amount_display_h1"><?php echo number_format((float)$resalt['amount'],2); ?></h1></td>
				  </tr>
					<tr style="display: none;">
					  <td align="right" valign="middle">Amount </td>
					  <td valign="middle"><input name="amount" type="text" class="form-control form-control-sm" id="amount" value="<?php echo number_format((float)$resalt['amount'],2,".",""); ?>" readonly="readonly"></td>
				  </tr>
					
				  <tr>
					  <td align="center"></td>
					  <td>
						  Bill Discount Issue: 
						  <?php if(setting_view("bill_discount_issue")==0){ ?>
						  <span class="badge badge-danger">OFF</span><br> 
						  <span class="btn btn-sm btn-light border-dark" onClick="password_accept();" id="accept_btn">Accept</span>
						  <?php } ?>
						  
						  <?php if(setting_view("bill_discount_issue")==1){ ?><span class="badge badge-success">ON</span><?php } ?>
					  </td>
				  </tr>
					
					<tr>
					  <td align="right" valign="middle" style="white-space: nowrap;">Customer Card</td>
					  <td valign="middle"><input name="cs_pin" type="number" class="form-control form-control-sm" id="cs_pin" autocomplete="off" onKeyUp="member_card(this.value);"></td>
				  </tr>
					<tr>
					  <td align="right" valign="middle" style="white-space: nowrap;">Customer Mobile <i class="btn btn-sm btn-light fa fa-plus" onClick="add_cus();"></i></td>
					  <td valign="middle"><input name="sale_details_customer" type="tel" class="form-control form-control-sm" id="sale_details_customer" list="cus_list" autocomplete="off" onKeyUp="check_cus(this.value); document.getElementById('cs_pin').value=''; document.getElementById('cs_pin').style.backgroundColor='white';"></td>
				  </tr>
					
					<tr valign="middle">
						<td align="right" valign="middle">Discount (%)</td>
					  <td style="padding: 0px;">
						  
<table style="width: 100%; margin: 0px;">
  <tbody>
    <tr>
      <th scope="col"><input name="discount_prasantage" type="number" class="form-control form-control-sm" id="discount_prasantage" placeholder="%" step="0.01" onKeyUp="rate_cal();" <?php if(setting_view("bill_discount_issue")==0){echo "readonly";} ?>></th>
      <th scope="col"><input name="sale_details_discount" type="number" class="form-control form-control-sm" id="sale_details_discount" placeholder="Amount" step="0.01" onKeyUp="prasantage_cal();" <?php if(setting_view("bill_discount_issue")==0){echo "readonly";} ?>></th>
    </tr>
  </tbody>
</table>

						  
						  </td>
					</tr>
					<tr>
					  <td align="right" valign="middle" style="white-space: nowrap;">Cash Payment <img src="image/cash_payment.jpg" style="height: 40px;"></td>
					  <td valign="middle"><input name="sale_details_cash_payment" type="number" autofocus="autofocus" required="required" class="form-control form-control-sm" id="sale_details_cash_payment" step="0.01" onKeyUp="balance_cal();"></td>
				  </tr>
					<tr>
						<td align="right" valign="middle" style="white-space: nowrap;">Card Payment <img src="image/cd_payment.jpg" style="height: 40px;"></td>
					  <td valign="middle"><input name="sale_details_card_payment" type="number" class="form-control form-control-sm" id="sale_details_card_payment" step="0.01" onKeyUp="balance_cal();"></td>
					</tr>
					<tr>
					  <td align="right" valign="middle">Payment Type</td>
					  <td valign="middle"><input name="pay_type" type="text" class="form-control form-control-sm" id="pay_type" readonly="readonly"></td>
				  </tr>
					<tr>
					  <td align="right" valign="middle">Net Amount </td>
					  <td valign="middle"><input name="net_amount" type="text" class="form-control form-control-sm font-weight-bold" id="net_amount" style="background-color: rgba(0,128,0,0.2);" value="0.00" readonly="readonly"></td>
				  </tr>
					<tr>
						<td align="right" valign="middle">Balance </td>
					  <td valign="middle"><input name="balance" type="text" class="form-control form-control-sm font-weight-bold" id="balance" style="background-color: rgba(255,255,0,0.5);" value="0.00" readonly="readonly"></td>
					</tr>
					<tr>
						<td>&nbsp;</td>
					  <td>
						<label class="btn btn-sm btn-light w-100 border-secondary"><input name="bill_print" type="checkbox" id="bill_print" <?php if(setting_view("bill_pint")==1){echo "checked";} ?>> Bill Print (On/Off)</label>
					  </td>
				  </tr>
					<tr>
						<td colspan="2" align="right">
							<button type="submit" name="payment_btn" class="btn btn-sm btn-success" id="payment_btn">Payment</button>
							<button type="button" class="btn btn-sm btn-dark" onClick="window.location='poin-of-sale?bill_id=<?php echo $bill_id; ?>';">Back to edit</button>
							<button type="button" class="btn btn-sm btn-danger" onClick="if(confirm('Are your sure close bill?')){window.location='poin-of-sale';}">Close Bill</button>
						</td>
					</tr>
				</tbody>
			</table>
</form>
	  </div>
  </div>
</div>
	
<div class="model model-hide" id="cus_model">
	<div class="model-contain">
		<div class="model-header">Add New Customer <span onClick="model_close();">&times;</span></div>
		<div class="model-body">

<table style="width: 100%;">
	<tbody>

		<tr>
			<td colspan="2">
				Customer Name *<br>
				<input name="cs_name" type="text" required class="form-control form-control-sm" id="cs_name" autocomplete="off">
			</td>
		</tr>

		<tr>
			<td> Mobile *
				<br>
				<input name="cs_mobile" type="text" required class="form-control form-control-sm" id="cs_mobile" pattern="\d*" autocomplete="off">
			</td>
			<td> NIC Number
				<br>
				<input name="cs_nic" type="text" class="form-control form-control-sm" id="cs_nic" autocomplete="off">
			</td>
		</tr>
		
<tr valign="top">
  <td>Customer PIN *
    <input name="cs_pin_insert" type="text" required class="form-control form-control-sm" id="cs_pin_insert" value="<?php echo customer_pin(); ?>">
	</td>
  <td> Discount Rate (%)
    <input name="cs_bill_discount" type="number" class="form-control form-control-sm" id="cs_bill_discount"></td>
  </tr>

		<tr>
			<td> Address
				<br>
				<textarea name="cs_address" rows="4" class="form-control form-control-sm" id="cs_address"></textarea>
			</td>
			<td>&nbsp;</td>
		</tr>

		<tr>
			<td colspan="2" align="right">
				<button type="submit" class="btn btn-success btn-sm mt-2" onClick="save_customer();">Add Customer</button>
			</td>
		</tr>

	</tbody>
</table>

</div>
</div>
</div>
	
<datalist id="cus_list">
<?php 
$c_qury=mysqli_query($connation,"SELECT *
FROM customer_details
ORDER BY cs_name");
while($c_resalt=mysqli_fetch_assoc($c_qury)){
?>
<option value="<?php echo "0".(int)$c_resalt['cs_mobile']; ?>"><?php echo $c_resalt['cs_name']; ?> <?php echo $c_resalt['cs_nic']; ?></option>
<?php } ?>
</datalist>
	
<div class="model model-hide" id="accept_popup">
	<div class="model-contain" style="width: 30%;">
		<div class="model-header">Enter Admin Password <span onClick="password_accept_close();">&times;</span>
		</div>
		<div class="model-body" id="model_body">
			
<div id="error_msg1" class="text-danger text-center"></div>
			
<table class="table table-sm table-borderless mb-0">
	<tbody>
		<tr>
			<td>User Name</td>
			<td><input name="user_username" type="text" class="form-control form-control-sm" id="user_username"></td>
		</tr>
		
		<tr>
			<td>Password</td>
			<td><input name="user_password" type="password" class="form-control form-control-sm" id="user_password"></td>
		</tr>
		
		<tr>
			<td colspan="2" align="right"><button type="button" class="btn btn-sm btn-success" onClick="cheack_password();">Accept</button></td>
		</tr>
	</tbody>
</table>

		</div>
	</div>
</div>

<script>
window.addEventListener("keyup", function(event){
	if(event.keyCode==27){
		window.location="poin-of-sale?bill_id=<?php echo $bill_id; ?>";
	}
});
	
	function rate_cal(){
		let discount_prasantage=document.getElementById('discount_prasantage').value;
		let amount=document.getElementById('amount').value;
		
		let b=amount/100*discount_prasantage;
		
		document.getElementById('sale_details_discount').value=b.toFixed(2);
		balance_cal();
	}
	function prasantage_cal(){
		let sale_details_discount=document.getElementById('sale_details_discount').value;
		let amount=document.getElementById('amount').value;
		
		let a=sale_details_discount/amount*100;
		
		document.getElementById('discount_prasantage').value=a.toFixed(2);
		balance_cal();
	}
	
	function balance_cal(){
		let sale_details_cash_payment=document.getElementById('sale_details_cash_payment').value;
		let sale_details_card_payment=document.getElementById('sale_details_card_payment').value;
		let sale_details_discount=document.getElementById('sale_details_discount').value;
		let amount=document.getElementById('amount').value;
		
		let a=+sale_details_cash_payment + +sale_details_card_payment;
		let b=amount-sale_details_discount;
		
		let c=a-b;
		
		document.getElementById('net_amount').value=b.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
		document.getElementById('amount_display_h1').innerHTML=b.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');	
		document.getElementById('balance').value=c.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
		
		if(sale_details_cash_payment==""&&sale_details_card_payment==""&&sale_details_discount==""){
			document.getElementById('pay_type').value="";
			document.getElementById('pay_type').classList.remove("text-danger");
			document.getElementById('pay_type').classList.remove("text-success");
		}
		else{
		
		if(b>a){
			document.getElementById('pay_type').value="Credit Payment";
			document.getElementById('pay_type').classList.add("text-danger");
			document.getElementById('pay_type').classList.remove("text-success");
			document.getElementById('sale_details_customer').required=true;
		}
		else{
			document.getElementById('pay_type').value="Cash Payment";
			document.getElementById('pay_type').classList.remove("text-danger");
			document.getElementById('pay_type').classList.add("text-success");
			document.getElementById('sale_details_customer').required=false;
		}
			
		}
		
	}
	function add_cus(){
		document.getElementById('cus_model').classList.remove("model-hide");
	}
	function model_close(){
		document.getElementById('cus_model').classList.add("model-hide");
	}
	
	function save_customer(){
		let cs_name=document.getElementById('cs_name').value;
		let cs_mobile=document.getElementById('cs_mobile').value;
		let cs_nic=document.getElementById('cs_nic').value;
		let cs_address=document.getElementById('cs_address').value;
		let cs_pin_insert=document.getElementById('cs_pin_insert').value;
		let cs_bill_discount=document.getElementById('cs_bill_discount').value;
		
		if(cs_name==""||cs_mobile==""||cs_pin_insert==""){
			alert("Please Enter Request Value.");
		}
		else{
		
		const xhttp = new XMLHttpRequest();
		xhttp.onload = function() {
		//document.getElementById("demo").innerHTML = this.responseText;
		document.getElementById('sale_details_customer').value=cs_mobile;
			
		check_cus(cs_mobile);
		
		model_close();
		}
		xhttp.open("GET", "ajax_customer_save.php?cs_name="+cs_name+"&cs_mobile="+cs_mobile+"&cs_nic="+cs_nic+"&cs_address="+cs_address+"&cs_pin_insert="+cs_pin_insert+"&cs_bill_discount="+cs_bill_discount, true);
		xhttp.send();
		
		document.getElementById('cs_name').value="";
		document.getElementById('cs_mobile').value="";
		document.getElementById('cs_nic').value="";
		document.getElementById('cs_address').value="";
		document.getElementById('cs_pin_insert').value="";
		document.getElementById('cs_bill_discount').value="";
			
		}
		
	}
	
function member_card(pin){		
		const xhttp = new XMLHttpRequest();
		xhttp.onload = function() {
		let sale_details_customer=this.responseText;		
		document.getElementById("sale_details_customer").value = sale_details_customer;
			
		if(pin==""){
		document.getElementById('cs_pin').style.backgroundColor="white";
		}
		else{
			
		if(sale_details_customer==""){
		document.getElementById('cs_pin').style.backgroundColor="rgba(255,0,0,0.2)";
		}
		else{
		document.getElementById('cs_pin').style.backgroundColor="rgba(0,128,0,0.2)";
		}
			
		}
			
		let cs_mobile=document.getElementById('sale_details_customer').value;
		check_cus(cs_mobile);
		}
		xhttp.open("GET", "ajax_cus_pin.php?pin="+pin, true);
		xhttp.send();
}
	
	function check_cus(cs_mobile){
		const xhttp = new XMLHttpRequest();
		xhttp.onload = function() {
		
		let btn_status=this.responseText;
			
		if(cs_mobile==""){
		document.getElementById('payment_btn').disabled=false;
		}
		else{
			
		if(btn_status==1){
		document.getElementById('payment_btn').disabled=false;
		}
		else{
		document.getElementById('payment_btn').disabled=true;
		}
			
		}
			
		}
		xhttp.open("GET", "ajax_check_customer.php?cs_mobile="+cs_mobile, true);
		xhttp.send();
		
		const xhttp1 = new XMLHttpRequest();
		xhttp1.onload = function() {
		document.getElementById("discount_prasantage").value = this.responseText;
		rate_cal();
		balance_cal();
		}
		xhttp1.open("GET", "ajax_cus_discount.php?cs_mobile="+cs_mobile, true);
		xhttp1.send();
		
		document.getElementById("sale_details_cash_payment").value="";
	}
	
function password_accept(){
document.getElementById('accept_popup').classList.remove("model-hide");
document.getElementById('user_username').select();
}
function password_accept_close(){
document.getElementById('accept_popup').classList.add("model-hide");
document.getElementById('user_username').value="";
document.getElementById('user_password').value="";
document.getElementById('error_msg1').innerHTML="";
}
	
function cheack_password(){
	let user_username=document.getElementById('user_username').value;
	let user_password=document.getElementById('user_password').value;
	
	const xhttp = new XMLHttpRequest();
	xhttp.onload = function() {
	let action=this.responseText;
		
	if(action==3){
		document.getElementById('error_msg1').innerHTML="User not found, Please try again.";
	}
	if(action==2){
		document.getElementById('error_msg1').innerHTML="Password not match, Please try again.";
	}
		
	if(action==1){
	password_accept_close();
	document.getElementById('discount_prasantage').readOnly=false;
	document.getElementById('sale_details_discount').readOnly=false;
	document.getElementById('discount_prasantage').select();
	document.getElementById('accept_btn').style.display="none";
	}
		
	}
	xhttp.open("GET", "ajax_check_password.php?user_username="+user_username+"&user_password="+user_password, true);
	xhttp.send();
}
</script>
</body>
</html>
<?php @mysqli_close($connation); ?>