<?php
session_start();
include "connect.php";
include "removespecial.php";

$brmid=$_SESSION['linkarisebranchid'];
			$salesmid = $_SESSION['linkariseumid'];

		$cmpmid=$_SESSION['linkarisecmpmid'];

		$cmid=$_POST['cmid'];
		$invoicemid=$_POST['invoicemid'];
		$ordermid=$_POST['ordermid'];
		$invoicerefno=$_POST['invoicerefno'];
		$invoicedate=implode('-', array_reverse(explode('-', $_POST['invoicedate'])));
		$fdate=implode('-', array_reverse(explode('-', $_POST['fdate'])));
		$invoiceterms=$_POST['invoiceterms'];
		$copyinvoice=$_POST['copyinvoice'];
		
		$invoicereceivedamount=0;
		$tmode="";
		$tmbankname="";
		$tmchkno="";
		$tmchkdate="";
		$tremarks="";
		$invdeliverylotno=$_POST['invdeliverylotno'];
		$invdispatchthrough=$_POST['invdispatchthrough'];
		$invorderno=$_POST['invorderno'];
		$invdestination=$_POST['invdestination'];
		$invremarks=$_POST['invremarks'];
		$invshipto=$_POST['invshipto'];
		$invoicemno=$_POST['invoicemno'];
		$invewaybillno=$_POST['invewaybillno'];
		$agentmid=0;
		$agentcommision=0;
		$agentcommisionamt=0;
		$tptalpaidamt=0;
		$copyqt=0;
		
		$createdby="";
		$kindatten="";
		if($copyinvoice==1)
		{
			$invoicemid=0;
			$copyqt= $copyinvoice;
		}
		date_default_timezone_set("Asia/Kolkata");
		$mdate= date('Y-m-d');
		$mdatetime= date('Y-m-d H:i:s');
		$invoiceyear='23-24';
		$invoiceprefix='R_Inv-';
		$evelastyear = "select * from res_company_master where cmpmid=$cmpmid";
	$relastyear = mysqli_query($conn, $evelastyear);
	while($rtlastyear = mysqli_fetch_assoc($relastyear))
	{
		$invoiceyear=$rtlastyear['cmpyear'];
		$invoiceprefix=$rtlastyear['retailinvoiceprefix'];
	}
		
		if($invoicemid==0)
		{
			$maxinvicemno=0;
			
			 $evemaxq = "SELECT max( invoicemno ) AS maxinvoicemno FROM res_invoice_master where invoiceyear='$invoiceyear' and invtype='r' and cmpmid='$cmpmid'";
			$remaxq = mysqli_query($conn, $evemaxq);
			while($rtmaxq = mysqli_fetch_assoc($remaxq))
			{
				$maxinvoicemno=$rtmaxq['maxinvoicemno'];
			} 
			$maxinvoicemno1=$maxinvoicemno+1;
			$maxinvoicemno2=$invoiceprefix.$maxinvoicemno1;
			$invoicepdf=$maxinvoicemno2.'_'.date('YmdHis').rand(1000,9999).'.pdf';
			$eve77 = "select invoicemid from res_invoice_master where invoicemno=$invoicemno and invtype='r' and invoiceyear='$invoiceyear' and cmpmid='$cmpmid'";
			$re77 = mysqli_query($conn, $eve77);
			if(mysqli_num_rows($re77) > 0)
			{
				$_SESSION['msg1'] = "Invoice No. Already exists.";
				header('Location: retailinvoicegenerate.php');
				return;
			}
			
				$eve1 = "INSERT INTO res_invoice_master (cmpmid,invoicestatus,invoiceprefix,invoicemno,invoicefordisplay,invoiceyear,addedby,addedon,invtype,invshipto,brmid,invoicepdf) 
				VALUES($cmpmid,'In Review','$invoiceprefix','$maxinvoicemno1','$maxinvoicemno2','$invoiceyear','$salesmid','$mdatetime','r','$invshipto','$brmid','$invoicepdf')";
				if ($conn->query($eve1) === TRUE)
				{
					$invoicemid = $conn->insert_id;
					
					/*  $evefup = "INSERT INTO res_followup_detail (fdate,frefid,followuptype,fremarks,fiscompleted) 
					VALUES('$fdate',$invoicemid,'Invoice','Ask for Payment','0')";
					if ($conn->query($evefup) === TRUE)
					{
					} */
			}
		}
		date_default_timezone_set("Asia/Kolkata");
		$mdate= date('Y-m-d');
		$eve1 = "update res_invoice_master set customermid='$cmid',invoiceterms='$invoiceterms',invoicerefno='$invoicerefno',invoicedate='$invoicedate',invdeliverylotno='$invdeliverylotno',invdispatchthrough='$invdispatchthrough',invorderno='$invorderno',invdestination='$invdestination',invremarks='$invremarks',invewaybillno='$invewaybillno',agentmid='$agentmid',agentcommision='$agentcommision',agentcommisionamt='$agentcommisionamt',invshipto='$invshipto' where invoicemid=$invoicemid";
		if ($conn->query($eve1) === TRUE)
		{
			$n=0;
			$n2=0;
			$subtotal=0;
			$grosstotal=0;
			$amount=0;
			$gtamount=0;
			$totaltaxcalc1=0;
			$totaltaxcalc2=0;
			$tcper1 = 0;
			$tcper2 = 0;
			$delete_checkbox_array = $_POST['itemid'];
			foreach ($delete_checkbox_array as $one_by_one_sid)
			{
				$itemid=$one_by_one_sid;
				$invoicedid=$_POST['qdid'][$n];
				$srate=$_POST['pprice'][$n];
				$sqty=$_POST['pqty'][$n];
				$iunit=$_POST['iunit'][$n];
				$sdesc=removespecialchar($_POST['pdesc'][$n]);
				$pdiscper=$_POST['pdiscper'][$n];
				$ptax = 0;
				$tcper1 = $ptax/2;
				$tcper2 = $ptax/2;
				$eve_id_2 = "select * from res_item_master WHERE itemid='$itemid'";
				$re_id_2 = mysqli_query($conn, $eve_id_2);
				$pid=0;
				
				$iunitmasterstock = 0;
				$hsncode = "";
				if(mysqli_num_rows($re_id_2) > 0)
				{
					while($rt_id_2 = mysqli_fetch_assoc($re_id_2))
					{
						$itemname = $rt_id_2['itemname'];
						$hsncode = $rt_id_2['itemhsncode'];
						/* $ptax = $rt_id_2['itemtaxper']; */
						$iunitmasterstock = $rt_id_2['iunitmasterstock'];
						$iunitmaster=$rt_id_2['iunitmaster'];
						/* $tcper1 = $ptax/2;
						$tcper2 = $ptax/2; */	
						break;
					}
				}				
				$amount=floatval($srate)*floatval($sqty);
				$pdiscamt=($amount*$pdiscper)/100;
				$samount=$amount-$pdiscamt;
				$subtotal=$subtotal+$samount;
				$taxcalc=($samount * $tcper1)/100;
				$taxcalc2=($samount * $tcper2)/100;
				$taxcalctotal=($samount * $ptax)/100;
				$totaltaxcalc1=$totaltaxcalc1+$taxcalc;;
				$totaltaxcalc2=$totaltaxcalc2+$taxcalc2;
				$tamount=$samount+$taxcalc+$taxcalc2;
				$tamount=$samount+$taxcalctotal;
				$gtamount=$gtamount+$tamount;
				$grosstotal=$grosstotal+$tamount;
				$n = $n + 1;
				$n2++;
				if($copyqt==1)
				{
					if($itemid==0 || $sqty==0)
					{
						$_SESSION['msg1'] = "Pls select product or add some quantity";
						header('Location: retailinvoicegenerate.php');
					}
					else
					{ 
				       
						$query = "INSERT INTO res_invoice_detail (invoicemid,itemid,itemname,itemunit,itemqty,itemiprice,itemamount,itemgstper,itemcgstamount,itemsgstamount,itemgstamount,itemtotalamount,itemhsncode,itemdesc,itemdiscper,itemdiscamt)
						VALUES('$invoicemid','$itemid','$itemname','$iunit','$sqty','$srate','$samount','$ptax','$taxcalc','$taxcalc2','$taxcalctotal','$tamount','$hsncode','$sdesc','$pdiscper','$pdiscamt')";
						if ($conn->query($query) === TRUE)
						{
							$invoicedid = $conn->insert_id;
						}
						$_SESSION['msg'] = "Invoice Added";
		
					}
				}
				else
				{
					if($invoicedid==0)
					{
						if($itemid==0 || $sqty==0)
						{
							$_SESSION['msg1'] = "Pls select product ";
						header('Location: retailinvoicegenerate.php');
						}
						else
						{ 
					       
							$query = "INSERT INTO res_invoice_detail (invoicemid,itemid,itemname,itemunit,itemqty,itemiprice,itemamount,itemgstper,itemcgstamount,itemsgstamount,itemgstamount,itemtotalamount,itemhsncode,itemdesc,itemdiscper,itemdiscamt) 
							VALUES('$invoicemid','$itemid','$itemname','$iunit','$sqty','$srate','$samount','$ptax','$taxcalc','$taxcalc2','$taxcalctotal','$tamount','$hsncode','$sdesc','$pdiscper','$pdiscamt')";
							if ($conn->query($query) === TRUE)
							{
								$invoicedid = $conn->insert_id;
							}
							
						}						
					}
					else
					{
						if($itemid==0 || $sqty==0)
						{
							$query_del = "delete from res_invoice_detail where invoicedid=$invoicedid";
							$result_del= mysqli_query($conn, $query_del) or die("Error");
						}
						else
						{
							
						 $query = "update res_invoice_detail set itemname='$itemname',itemunit='$iunit',itemqty='$sqty',itemiprice='$srate',itemamount='$samount',itemdiscper='$pdiscper',itemdiscamt='$pdiscamt',itemgstper='$ptax',itemcgstamount='$taxcalc',itemsgstamount='$taxcalc2',itemgstamount='$taxcalctotal',itemtotalamount='$tamount',itemdesc='$sdesc' where invoicedid=$invoicedid";
						$result= mysqli_query($conn, $query) or die("Error");
						
						}
					}
				}
				
				$iunitmasterstock2=$iunitmasterstock-$sqty;
				$eve21 = "INSERT INTO res_item_detail (itemtranmid,itemtrandid,itemid,itransactiontype,iinouttype,itemtrandate,ioutqty,ioutqtyactual,ioutunit,ioutunitactual,itransremarks,itfinancialyear,ilateststockback) 
				VALUES('$invoicemid','$invoicedid','$itemid','Invoice Out','Out','$mdate','$sqty','$sqty','$iunit','$iunitmaster','Invoice Generated','$invoiceyear','$iunitmasterstock2')";	
				if ($conn->query($eve21) === TRUE)
				{
					$eve22 = "update res_item_master set iunitmasterstock=$iunitmasterstock2  where itemid=$itemid";	
					if ($conn->query($eve22) === TRUE)
					{
					}
					
				}  
			}
			
			$customermid=$cmid;
		
				/* $eve ="insert into res_customerpayment_master (customermid,cpdate,receivedamount,tremarks,tmode,tmbankname,tmchkno,tmchkdate) 
				values('$customermid','$mdate','$invoicereceivedamount','$tremarks','$tmode','$tmbankname','$tmchkno','$tmchkdate')";
				if ($conn->query($eve) === TRUE)	
				{	
					$last_id = $conn->insert_id;
				}  */
			
			
			$eve55 = "select sum(itemgstamount) as tax1,sum(itemqty) as tqty from res_invoice_detail WHERE invoicemid='$invoicemid'";
			$re55 = mysqli_query($conn, $eve55);
			$totaltaxamt=0;
			$totalqty=0;
			while($rt55 = mysqli_fetch_assoc($re55))
			{
				$totaltaxamt=$rt55['tax1'];
				$totalqty=$rt55['tqty'];
			}
			
			
			/* $netamount1=round($gtamount); */
			$netamount1=$gtamount;
			$invoiceroundoffamount=$netamount1-$gtamount;
			/*  $eve3 = "update res_invoice_master set invoiceroundoffamount='$invoiceroundoffamount',invoicetotalitem='$sqty',invoicetotaltaxamount='$totaltaxcalc1+$totaltaxcalc2',invoicetotalamount='$subtotal',invoicegrossamount='$grosstotal',invoicenetamount='$netamount1' ,addedby='$salesmid',addedon='$mdatetime',invoicereceivedamount=invoicereceivedamount+$invoicereceivedamount where invoicemid='$invoicemid'";  */
			
			$eve3 = "update res_invoice_master set invoiceroundoffamount='$invoiceroundoffamount',invoicetotalitem='$totalqty',invoicetotalamount='$subtotal',invoicegrossamount='$grosstotal',invoicenetamount='$netamount1' ,addedby='$salesmid',addedon='$mdatetime',invoicereceivedamount=invoicereceivedamount+$invoicereceivedamount where invoicemid='$invoicemid'";
			$re3 = mysqli_query($conn, $eve3);
			//$_SESSION['msg'] = "Invoice Added";
		//header("Location: generatepdf/invoicepdf.php?invoicemid=$invoicemid");
		 $eve4 ="insert into res_paymenttransaction_detail (partymid,cmpmid,paymenttype,Paymentrefid,paymentrefno,paymentdate,paymentoutamount,paymentmode,paymentdetail)
				values('$cmid','$cmpmid','Retail Invoice','$invoicemid','$maxinvoicemno2','$mdate','$netamount1','','')";
				$re4 = mysqli_query($conn, $eve4); 
		
			if($invoicereceivedamount!=0)
			{
				
				
				$cmpcurrentyear='20-21';
		$prefix='PayIn-';
		$evelastyear = "select * from res_company_master where cmpmid=$cmpmid";
		$relastyear = mysqli_query($conn, $evelastyear);
		while($rtlastyear = mysqli_fetch_assoc($relastyear))
		{
			$cmpcurrentyear=$rtlastyear['cmpyear'];
			$prefix=$rtlastyear['payinprefix'];
		}
		
		
		$payinno=0;
		$evemaxq = "SELECT max( payinno ) AS maxpayinno FROM res_paymentin_master where payinyear='$cmpcurrentyear' and cmpmid=$cmpmid";
		$remaxq = mysqli_query($conn, $evemaxq);
		while($rtmaxq = mysqli_fetch_assoc($remaxq))
		{
			$maxpayinno=$rtmaxq['maxpayinno'];
		}
		$maxpayinno1=$maxpayinno+1;
		$maxpayinno2=$prefix.$maxpayinno1;
				
				$query = "INSERT INTO res_paymentin_master (partymid, receiptrefrenceid, receiptdate, receiptamont, cmpmid, receiptmode, receiptdetail,payinno,payinyear,payinprefix,payinnofordisplay,addedby,addedon,updatedby,updatedon) VALUES ('$cmid', '$invoicemid', '$mdate', '$invoicereceivedamount', '$cmpmid', '$tmode', '$tremarks','$maxpayinno1','$cmpcurrentyear','$prefix','$maxpayinno2','$salesmid','$mdatetime','$salesmid','$mdatetime')";
				
				if ($conn->query($query) === TRUE)
				{
					$paymentinmid = $conn->insert_id;
				 $eve41 ="insert into res_paymenttransaction_detail (partymid,cmpmid,paymenttype,Paymentrefid,paymentrefno,paymentdate,paymentinamount,paymentmode,paymentdetail)
				values('$cmid','$cmpmid','Payment In','$paymentinmid','$maxpayinno2','$mdate','$invoicereceivedamount','$tmode','$tremarks')";
							$re41 = mysqli_query($conn, $eve41); 
							}
							
			}
			
			$tptalpaidamt=$tptalpaidamt+$invoicereceivedamount;
			
			/* $eve5 ="update res_customerpayment_master set receivedamount='$tptalpaidamt' where cpmid=$last_id";
			$re5 = mysqli_query($conn, $eve5);  */
		}
		$_SESSION['msg'] = "Invoice Added";
		                header("Location: retailinvoicepdf.php?invoicemid=$invoicemid");
?>
