<?php include("sass/icon_for_datepicker_and_datatable.php");?>

        <?php
$errMsg=""; 
if(isset($_POST['submit'])) // To check 'submmited or not' by if(isset($_POST['submit'])) 
{
	$name = $_POST['name'];
	$cash = $_POST['cash'];
	$bank = $_POST['bank'];
	$bank_id = $_POST['bank_id'];
	$cheque_no = $_POST['cheque_no'];
	$cheque_date = $_POST['cheque_date'];
	$sector = $_POST['sector'];
	$description = $_POST['description'];
	$date = $_POST['date'];
	
	if(!empty($cheque_date)) {
$cheque_date = date("Y-m-d", strtotime($cheque_date));
}
else {
$cheque_date = "";
}
	$date = $_POST['date'];
	if(!empty($date)) {
$date = date("Y-m-d", strtotime($date));
}
else {
$date = "";
}
	
	
	if(empty($date)) $errMsg="Please Enter Date";
	if(empty($errMsg))
	{
	
	$sql="select MAX(RIGHT(id,10)) as id from accounts_expense where id like '$branch_id_for_header_user-EX%'";
	$result=mysqli_query($connection,$sql);

	if($row=mysqli_fetch_array($result))
	{
	$invoice_no=$row['id'];
	}
	else
	{
	$invoice_no=0;
	}
	$invoice_no++;
	$invoice_no="$branch_id_for_header_user-EX".str_pad($invoice_no,10,0,STR_PAD_LEFT);
		
		mysqli_query($connection,"INSERT INTO accounts_expense (id, name, cash, bank, bank_id, cheque_no, cheque_date, sector, description, date, branch_id) VALUES ('$invoice_no','$name','$cash','0','$bank_id','$cheque_no','$cheque_date','$sector','$description','$date','$branch_id_for_header_user')")
		or die(mysqli_error()); 
		
		
		if(!empty($bank_id)) {
		//mysqli_query($connection,"UPDATE bank_name SET balance = balance - $bank WHERE bank_id = $bank_id")
				//or die(mysqli_error());
		
		mysqli_query($connection,"INSERT INTO bank_statement (amount, ref, payment_type, reason, bank_id, cheque_no, cheque_date, date, branch_id) VALUES ('$bank','$invoice_no','credit','10','$bank_id','$cheque_no','$cheque_date','$cheque_date','$branch_id_for_header_user')")
		or die(mysqli_error()); 
		
		
		mysqli_query($connection,"INSERT INTO transaction (ref_id, branch_id) VALUES ('$invoice_no','$branch_id_for_header_user')")
		or die(mysqli_error());
		
		}
		else {}
		
		if(!empty($cash)) { 
		
			mysqli_query($connection,"INSERT INTO transaction (date, ref_id, ledger, credit, hint, details, payment_type, branch_id) VALUES ('$date','$invoice_no','10','$cash','Expense','$description','cash','$branch_id_for_header_user')")
		or die(mysqli_error());	
		
		mysqli_query($connection,"UPDATE cash SET cash = cash - $cash WHERE id = 1")
				or die(mysqli_error());
		
		 }
		
		
		
	
print "<script>";
	print "self.location='expense_invoice.php?inv=$invoice_no';";
	print "</script>";	
		
	
}
}
?>