<?php

require_once("config/configDB.php"); 
require 'financial_year_calculation.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
     $accountyear    = $financialYearStart."-".$financialYearEnd;
    

    
    
$sqlInvoiceCount = mysqli_query($conn,"SELECT count(*) as invoice FROM saleheader where flag=1 and accountyear='$accountyear' and status=''");
//echo "SELECT count(*) as invoice FROM saleheader where flag=1 and accountyear='$accountyear' and status=''";
 
$rowInvoiceCount=mysqli_fetch_array($sqlInvoiceCount,MYSQLI_ASSOC);

$invoice1   = sprintf('%03d',$rowInvoiceCount['invoice']+3);

$acyear="INV/".$syr."-".$eyr."/";

$saleinvoice= $acyear.$invoice1;
    

//$saleinvoice    = stripslashes($_POST['saleinvoice']);
$saledate       = new DateTime(stripslashes($_POST['saledate']));
$saledate 		= $saledate->format('Y-m-d');
$customer_id   = stripslashes($_POST['customerName']);
$customerid=$customer_id;

$area      = stripslashes($_POST['area']);
$area_tamil         = stripslashes($_POST['area_tamil']);
$employeeid         = stripslashes($_POST['employeeid']);
$vehicleno=$_POST['vehicleno'];
$billing_address=$_POST['billing_address'];
$del_address=$_POST['del_address'];
$notes=$_POST['notes'];


$user=$_SESSION['username'];

$tray_product=$_POST['tray_product'];
$pending_tray    = $_POST['pending_tray'];
$tray_eqty   = $_POST['tray_eqty'];
$tray_out_qty=$_POST['tray_out'];



$sql_check = mysqli_query($conn,"SELECT a.id,a.ccode,a.cname,a.mobile,sum(a.samount) as samount,sum(payamount) as payamount,sum(discount) as discount 
FROM (
  SELECT cm.id,cm.ccode,cm.cname,cm.mobile,SUM(sd.tamount) as samount,0 as payamount,0 as discount from customer_master as cm LEFT JOIN saleheader sd ON cm.id=sd.customer_id WHERE cm.isdelete=1 and sd.status='' and cm.id='$customerid' GROUP BY cm.id
  
  UNION ALL
  
  SELECT cm.id,cm.ccode,cm.cname,cm.mobile,0 as samount,sum(sc.received_amount) as payamount,sum(discount) as discount from customer_master as cm LEFT JOIN customer_payment_header as sc ON cm.id=sc.customerID WHERE cm.isdelete=1 and sc.status='' and cm.id='$customerid' GROUP by cm.id
 
) a GROUP BY a.id  ");



$row_check=mysqli_fetch_array($sql_check,MYSQLI_ASSOC);

$sql_return=mysqli_query($conn,"select Sum(tamount) as return_amount from sale_return_header where status='' and customer_id='$customerid' ");
$row_return=mysqli_fetch_array($sql_return,MYSQLI_ASSOC);

$return_amount=$row_return['return_amount'];

$sql_opening=mysqli_query($conn,"select opening_balance from customer_master where id='$customerid' ");
$row_opening=mysqli_fetch_array($sql_opening,MYSQLI_ASSOC);

$opening_balance=$row_opening['opening_balance'];




$pamount1        = ($row_check['samount']+$opening_balance)-($row_check['payamount']+$row_check['discount']+$return_amount);

$pamount=number_format($pamount1,2,'.','');


//$pending_tamount=$_POST['pending_tamount'];
$pending_tamount=$pamount;

$payamount    = $_POST['payamount'];
$discount   = $_POST['discount'];

$cash_amount   = $_POST['cash_amount'];
$bank_amount   = $_POST['bank_amount'];

$payment_type=$_POST['paymenttype'];


$productID    = $_POST['productID'];
$eqtyinput    = $_POST['eqtyinput'];
$prateinput   = $_POST['prateinput'];
$salenetamt=$_POST['salenetamt'];
$lot_number=0;

$totalNetamt    =round(stripslashes($_POST['totalNetamt']));

//$accountyear    = $financialYearStart."-".$financialYearEnd;

$create_date  	= date("Y-m-d H:i:s"); 
$itemcount      = count($productID);

 $msql2=mysqli_query($conn,"select * from customer_master where id='".$customer_id."'");
        
		while($rw2=mysqli_fetch_array($msql2))
		{
			
		$cname=$rw2['cname'];
			
		}
		
		$msql3=mysqli_query($conn,"select * from employee_master where id='".$employeeid."'");
        
		while($rwemp=mysqli_fetch_array($msql3))
		{
			
		$ename=$rwemp['ename'];
			
		}
		
		$ename=$rw2['cname'];
			
		}
		
		$msql_trayname=mysqli_query($conn,"select * from product_master where id='".$tray_product."'");
        
		while($rw_tray=mysqli_fetch_array($msql_trayname))
		{
			
		$tray_name=$rw_tray['productname'];
			
		}
		
		$autoinc_tray=mysqli_query($conn,"ALTER TABLE tray_details CHANGE id id INT(11) NOT NULL AUTO_INCREMENT ");


$autoinc=mysqli_query($conn,"ALTER TABLE saleheader CHANGE id id INT(11) NOT NULL AUTO_INCREMENT ");
$autoinc1=mysqli_query($conn,"ALTER TABLE saledetails CHANGE id id INT(11) NOT NULL AUTO_INCREMENT ");

$autoinc_collection=mysqli_query($conn,"ALTER TABLE customer_payment_header CHANGE id id INT(11) NOT NULL AUTO_INCREMENT ");







		
				
		
		$count=0;
$check_query	= mysqli_query($conn,"SELECT count(invoice_no) as counts FROM saleheader WHERE invoice_no = '$saleinvoice' and accountyear='$accountyear' and status=''"); // Check the database


while($row = mysqli_fetch_array($check_query)){
$count=$row['counts'];
}
if($count!=0){
// Already Exsist


		echo "<script> alert ('Data Inserted Success.');</script>";
		?>
<script language="javascript">window.location.href = "saleDashboard.php";</script>
<?php
		

}		
else
{


if($payamount>0 || $discount>0)
{
	
	
	$sql_InvoiceQuery_collection   = mysqli_query($conn,"SELECT count(*) as invoice FROM customer_payment_header WHERE accountyear='$accountyear' and status='' ");
$rowInvoiceCount_coll    = mysqli_fetch_array($sql_InvoiceQuery_collection,MYSQLI_ASSOC);

$invoice_count      = $rowInvoiceCount_coll['invoice']+1;

$acyear="SCL/".$syr."-".$eyr."/";

$invoice_collection= $acyear.$invoice_count;


$check_query_collection	= mysqli_query($conn,"SELECT count(cashno) as counts_collection FROM customer_payment_header WHERE cashno = '$invoice_collection' and accountyear='$accountyear' and status=''"); // Check the database
		
		$row_collection=mysqli_fetch_array($check_query_collection,MYSQLI_ASSOC);
		
		$collectioncount=$row_tray['counts_collection'];
		
		if($collectioncount==0)
		{
			
			
			
			 $sql_collection = "INSERT INTO customer_payment_header    (cashno,sales_inv,collectiondate,customerID,pending, paymenttype,paymentreference ,bank_name,handover,transactionno,remark,paidby,received_amount,cash_amount,bank_amount,discount,tray_amount,saleid,payment_through,status,flag,accountyear) VALUES ('$invoice_collection','$saleinvoice','$saledate','$customer_id','$pending_tamount','$paymenttype','$paymenttype','','','','$notes','$createdby','$payamount','$cash_amount','$bank_amount','$discount','0','0','Accounts','','1','$accountyear')";

//echo $sql;
mysqli_query($conn,$sql_collection);
			
		}
	
	
	
}


		
		
$sql_saleheader  = "INSERT INTO saleheader (invoice_no, sale_date, customer_id,cname, area, area_tamil,employeeid,ename,vehicleno,billing_address,del_address,notes, itemcount, tamount,pending_amount,collection_amount,discount,cash_amount,bank_amount,payment_type,pending_tray,in_tray,out_tray,status,user, create_date, flag, accountyear) VALUES ('$saleinvoice','$saledate','$customer_id','$cname','$area','$area_tamil','$employeeid','$ename','$vehicleno','$billing_address','$del_address','$notes','$itemcount','$totalNetamt','$pending_tamount','$payamount','$discount','$cash_amount','$bank_amount','$payment_type','$pending_tray','$tray_eqty ','$tray_out_qty','','$user','$create_date', '1','$accountyear')";

mysqli_query( $conn, $sql_saleheader ); 			

$last_id = mysqli_insert_id($conn);
//INSERT INTO saledetails( saleheader_id, productID, sale_eqty, sale_prate, sale_gst, sale_cgst, sale_sgst, salenetamt,create_date, flag) VALUES ( )

foreach ($productID as $key => $value) {
    $ntamt=$eqtyinput[$key]*$prateinput[$key];
	$ntamt1=number_format($ntamt,2,'.','');

    $sql_saledetails  = "INSERT INTO saledetails( saleheader_id, productID,lot_number, sale_eqty, sale_prate,    salenetamt,status,create_date, flag,accountyear) VALUES ('$last_id','$productID[$key]','$lot_number[$key]','$eqtyinput[$key]','$prateinput[$key]','$ntamt1','','$create_date','1','$accountyear')";

    mysqli_query( $conn, $sql_saledetails );

}

header("Location:saleDashboard.php");


}

?>