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

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

		$cmpmid=$_SESSION['linkarisecmpmid'];

		$cmid=$_POST['cmid'];
		$qmid=$_POST['qmid'];
		$ordermid=$_POST['ordermid'];
		$orderrefno=$_POST['orderrefno'];
		$orderdate=implode('-', array_reverse(explode('-', $_POST['orderdate'])));
		$fdate=implode('-', array_reverse(explode('-', $_POST['fdate'])));
		$orderterms=$_POST['orderterms'];
		$copyorder=$_POST['copyorder'];
		
		
		/* $tmode=$_POST['tmode'];
		$tmbankname=$_POST['tmbankname'];
		$tmchkno=$_POST['tmchkno'];
		$tmchkdate=date("Y-m-d", strtotime($_POST['tmchkdate']));
		$tremarks=$_POST['tremarks']; */
		$orderdeliverylotno=$_POST['orderdeliverylotno'];
		$orderdispatchthrough=$_POST['orderdispatchthrough'];
	
		$orderdestination=$_POST['orderdestination'];
		$orderremarks=$_POST['orderremarks'];
		$ordershipto=$_POST['ordershipto'];
		$ordermno=$_POST['ordermno'];
		$orderewaybillno=$_POST['orderewaybillno'];
		$agentmid=0;
		$agentcommision=0;
		$agentcommisionamt=0;
		$tptalpaidamt=0;
		$copyqt=0;
		
		$createdby="";
		$kindatten="";
		if($copyorder==1)
		{
			$ordermid=0;
			$copyqt= $copyorder;
		}
		date_default_timezone_set("Asia/Kolkata");
		$mdate= date('Y-m-d');
		$mdatetime= date('Y-m-d H:i:s');
		$orderyear='22-23';
		$orderprefix='SO-';
		$evelastyear = "select * from res_company_master where cmpmid=$cmpmid";
	$relastyear = mysqli_query($conn, $evelastyear);
	while($rtlastyear = mysqli_fetch_assoc($relastyear))
	{
		$orderyear=$rtlastyear['cmpyear'];
		$orderprefix=$rtlastyear['orderprefix'];
	}
		
		if($ordermid==0)
		{
			$maxordericemno=0;
			
			$evemaxq = "SELECT max( ordermno ) AS maxordermno FROM res_salesorder_master where orderyear='$orderyear' and cmpmid='$cmpmid'";
			$remaxq = mysqli_query($conn, $evemaxq);
			while($rtmaxq = mysqli_fetch_assoc($remaxq))
			{
				$maxordermno=$rtmaxq['maxordermno'];
			} 
			$maxordermno1=$maxordermno+1;
			$maxordermno2=$orderprefix.$maxordermno1;
			$orderpdf=$maxordermno2.'_'.date('YmdHis').rand(1000,9999).'.pdf';
			$eve77 = "select ordermid from res_salesorder_master where ordermno=$ordermno and orderyear='$orderyear' and cmpmid='$cmpmid'";
			$re77 = mysqli_query($conn, $eve77);
			if(mysqli_num_rows($re77) > 0)
			{
				$_SESSION['msg1'] = "order No. Already exists.";
				header('Location: salesordergenerate.php');
				return;
			}
			
				$eve1 = "INSERT INTO res_salesorder_master (cmpmid,orderstatus,orderprefix,ordermno,orderfordisplay,orderyear,addedby,addedon,ordertype,ordershipto,brmid,orderpdf) 
				VALUES($cmpmid,'In Review','$orderprefix','$maxordermno1','$maxordermno2','$orderyear','$salesmid','$mdatetime','i','$ordershipto','$brmid','$orderpdf')";
				if ($conn->query($eve1) === TRUE)
				{
					$ordermid = $conn->insert_id;
					if($qmid!=0)
					{
				$eve15 = "update res_quotation_master set qstatus='Converted To Sales' where qmid=$qmid";
						if ($conn->query($eve15) === TRUE)
						{
						
						}
					}
			}
		}
		date_default_timezone_set("Asia/Kolkata");
		$mdate= date('Y-m-d');
		$eve1 = "update res_salesorder_master set customermid='$cmid',orderterms='$orderterms',orderrefno='$orderrefno',orderdate='$orderdate',orderdeliverylotno='$orderdeliverylotno',orderdispatchthrough='$orderdispatchthrough',orderdestination='$orderdestination',orderremarks='$orderremarks',orderewaybillno='$orderewaybillno',agentmid='$agentmid',agentcommision='$agentcommision',agentcommisionamt='$agentcommisionamt',ordershipto='$ordershipto' where ordermid=$ordermid";
		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;
				$orderdid=$_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 = $_POST['pgst'][$n];
				$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'];
						$iunit=$rt_id_2['itemunit'];
						/* $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: ordergenerate.php');
					}
					else
					{ 
				       
						$query = "INSERT INTO res_salesorder_master (ordermid,itemid,itemname,itemunit,itemqty,itemiprice,itemamount,itemgstper,itemcgstamount,itemsgstamount,itemgstamount,itemtotalamount,itemhsncode,itemdesc,itemdiscper,itemdiscamt)
						VALUES('$ordermid','$itemid','$itemname','$iunit','$sqty','$srate','$samount','$ptax','$taxcalc','$taxcalc2','$taxcalctotal','$tamount','$hsncode','$sdesc','$pdiscper','$pdiscamt')";
						if ($conn->query($query) === TRUE)
						{
							$orderdid = $conn->insert_id;
						}
						$_SESSION['msg'] = "order Added";
		
					}
				}
				else
				{
					if($orderdid=='0')
					{
						if($itemid==0 || $sqty==0)
						{
							$_SESSION['msg1'] = "Pls select product ";
						header('Location: ordergenerate.php');
						}
						else
						{ 
					       
							$query = "INSERT INTO res_salesorder_detail (ordermid,itemid,itemname,itemunit,itemqty,itemiprice,itemamount,itemgstper,itemcgstamount,itemsgstamount,itemgstamount,itemtotalamount,itemhsncode,itemdesc,itemdiscper,itemdiscamt) 
							VALUES('$ordermid','$itemid','$itemname','$iunit','$sqty','$srate','$samount','$ptax','$taxcalc','$taxcalc2','$taxcalctotal','$tamount','$hsncode','$sdesc','$pdiscper','$pdiscamt')";
							if ($conn->query($query) === TRUE)
							{
								$orderdid = $conn->insert_id;
							}
							
						}						
					}
					else
					{
						if($itemid==0 || $sqty==0)
						{
							$query_del = "delete from res_salesorder_detail where orderdid=$orderdid";
							$result_del= mysqli_query($conn, $query_del) or die("Error");
						}
						else
						{
							
						 $query = "update res_salesorder_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 orderdid=$orderdid";
						$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('$ordermid','$orderdid','$itemid','order Out','Out','$mdate','$sqty','$sqty','$iunit','$iunitmaster','order Generated','$orderyear','$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','$orderreceivedamount','$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_salesorder_detail WHERE ordermid='$ordermid'";
			$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;
			$orderroundoffamount=$netamount1-$gtamount;
			/*  $eve3 = "update res_salesorder_master set orderroundoffamount='$orderroundoffamount',ordertotalitem='$sqty',ordertotaltaxamount='$totaltaxcalc1+$totaltaxcalc2',ordertotalamount='$subtotal',ordergrossamount='$grosstotal',ordernetamount='$netamount1' ,addedby='$salesmid',addedon='$mdatetime',orderreceivedamount=orderreceivedamount+$orderreceivedamount where ordermid='$ordermid'";  */
			
			$eve3 = "update res_salesorder_master set orderroundoffamount='$orderroundoffamount',ordertotalitem='$totalqty',ordertotaltaxamount='$totaltaxamt',ordertotalamount='$subtotal',ordergrossamount='$grosstotal',ordernetamount='$netamount1' ,addedby='$salesmid',addedon='$mdatetime'where ordermid='$ordermid'";
			$re3 = mysqli_query($conn, $eve3);
			//$_SESSION['msg'] = "order Added";
		//header("Location: generatepdf/orderpdf.php?ordermid=$ordermid");
		 $eve4 ="insert into res_paymenttransaction_detail (partymid,cmpmid,paymenttype,Paymentrefid,paymentrefno,paymentdate,paymentoutamount,paymentmode,paymentdetail)
				values('$cmid','$cmpmid','sales','$ordermid','$maxordermno2','$mdate','$netamount1','','')";
				$re4 = mysqli_query($conn, $eve4); 
		
			if($orderreceivedamount!=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', '$ordermid', '$mdate', '$orderreceivedamount', '$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','$orderreceivedamount','$tmode','$tremarks')";
							$re41 = mysqli_query($conn, $eve41); 
							}
							
			}
			
			$tptalpaidamt=$tptalpaidamt+$orderreceivedamount;
			
			/* $eve5 ="update res_customerpayment_master set receivedamount='$tptalpaidamt' where cpmid=$last_id";
			$re5 = mysqli_query($conn, $eve5);  */
		}
		$_SESSION['msg'] = "Sales Order Added";
		                header("Location: orderpdf.php?ordermid=$ordermid");
?>
