<? 
session_start();
$brcode=$_SESSION['brcode'];
$user=$_SESSION['user'];
if(strlen($brcode)<=0)
{
 print "<script> alert('Session timed out'); parent.document.location='../index.php'; </script>";
 return;
}
include("test.php");
include("../opendb.php");
include ("../test.php");
$invno=$_REQUEST['trnsno'];
$invstrtdt=$_REQUEST['invstrtdt'];
$invenddt=$_REQUEST['invenddt'];
$transdist=$_REQUEST['transdist'];
$vehicleno=$_REQUEST['vehno'];
$docno=$_REQUEST['docno'];
$deleterec=$_REQUEST['deleterec'];

//echo "<br>";
if($deleterec!='')
{      
    $id = array();
	$id = $_REQUEST['del'];
	//print_r($id);
    if (count($id) > 0)
  	{
  	    $myJSON.='[';
        foreach ($id as $id2)
     	{



$re1=mysqli_query($db,"select customer,sum(aprice+cgstamt+sgstamt+igstamt+cessamt+other_charges),invno,entrydate,sum(cgstamt),sum(sgstamt),sum(igstamt),brcode,sum(cessamt),sum(aprice),sum(other_charges),buygstn,buyaddr1,buyaddr2,buyaddr2,buypin,buystate,doctype,sum((aprice+cgstamt+sgstamt+igstamt+cessamt)*.075/100) from sap_einvoice where invno='$id2' and brcode='$brcode' group by invno");
$sss="select customer,sum(aprice+cgstamt+sgstamt+igstamt+cessamt+other_charges),invno,entrydate,sum(cgstamt),sum(sgstamt),sum(igstamt),brcode,sum(cessamt),sum(aprice),sum(other_charges),buygstn,buyaddr1,buyaddr2,buyaddr2,buypin,buystate,doctype,sum((aprice+cgstamt+sgstamt+igstamt+cessamt)*.075/100) from sap_einvoice where invno='$id2' and brcode='$brcode' group by invno";
//echo $sss;

//echo "select customer,sum(aprice+cgstamt+sgstamt+igstamt+cessamt+adltcsamt),invno,entrydate,sum(cgstamt),sum(sgstamt),sum(igstamt),brcode,sum(cessamt),sum(aprice),sum(adltcsamt) from spareinvoice where invno='$invno' and brcode='$brcode'";
$chkflg=1;
$rr1=mysqli_fetch_array($re1);
//while($rr1=mysqli_fetch_array($re1))
//{
    $tobrcode=$rr1['customer'];
    $invno=$rr1['invno'];
    $frqry=mysqli_query($db,"select * from branch where brcode='$brcode'");
    $frar=mysqli_fetch_array($frqry);
    $frgstin=$frar['cstno'];
    $frstcod = substr($frgstin, 0, 2);
    $frbrnm='PSN AUTOMOTIVE MARKETING PVT LTD';
    $fraddr1=$frar['braddr'];
    $fraddr1=substr($fraddr1, 0, 50);
    $fraddr1=preg_replace("/[^ \w]+/", "", $fraddr1);
    $fraddr2=$frar['brcity'];
    $brstate=$frar['brstate'];
    $fraddr2=substr($fraddr2, 0, 50);
    $fraddr2=preg_replace("/[^ \w]+/", "", $fraddr2);
    $frpin=substr($frar['brcity'],-6);
    
    
    
    $toqry=mysqli_query($db,"select * from customer where acname='$tobrcode'");
    $sq="select * from customer where acname='$tobrcode'";

 
  
    $toar=mysqli_fetch_array($toqry);
    $togstin=$rr1['buygstn'];
    $togstin=trim($togstin);
    if($togstin<='')
    {
      $togstin='URP';  
    }
    else
    {
        $prltr=substr($togstin,0,2);
        if((strtoupper($prltr)=='UN')||(strtoupper($prltr)=='NO'))
        {
            $togstin='URP';
        }
        else
        {
            $togstin=$togstin;
        }
    }
   
    $tobrnm=$rr1['customer'];
    $tobrnm=preg_replace("/[^ \w]+/", "", $tobrnm);
    $toaddr1=$rr1['buyaddr1'];
    $toaddr1=substr($toaddr1, 0, 50);
    $toaddr1=preg_replace("/[^ \w]+/", "", $toaddr1);
    $toaddr2=$rr1['buyaddr2'];
    $toaddr2=substr($toaddr2, 0, 50);
    $toaddr2=preg_replace("/[^ \w]+/", "", $toaddr2);
    $flag=0;
    if($rr1['buystate']<='')
    {
        print "<script>alert('state empty'); </script>";
        print "<script>document.location='sap_spareinvoicejson.php'</script>";
        $flag++;
    }
    $topin=$rr1['buypin'];
    if($topin<='')
    {
       print "<script>alert('PIN empty'); </script>";
        print "<script>document.location='sap_spareinvoicejson.php'</script>"; 
        $flag++;
    }
     $stquery="select code from states where state=UPPER('$rr1[buystate]')";
     $streslt=mysqli_query($db,$stquery);
     $statecode=mysqli_fetch_array($streslt);
     
    $tostcod = $statecode['code'];
    if($tostcod<='')
    {
        print "<script>alert('Invalid state'); </script>";
        print "<script>document.location='sap_spareinvoicejson.php'</script>"; 
        $flag++;
    }
    if($togstin=='URP')
    {
        $statecodeval=$tostcod;
        
    }
    else
    {
       $statecodeval= substr($togstin,0,2);
    }
    
    $entrydate=$rr1['entrydate'];
    //$entrydate1=implode('/', array_reverse(explode('-', $entrydate)));
    
    
     
if($brcode == 'HUBCHI')
{
    $prefx='CHI';
}
else if($brcode == 'HUBEKA')
{
$prefx='ILK';
}
else if($brcode == 'HUBHOS')
{
$prefx='HOS';
}
else if($brcode == 'PAT649')
{
$prefx='TLA';
}
else if($brcode == 'KAN248')
{
$prefx='KAN';
}
else if($brcode == 'KAN332')
{
$prefx='KHD';
}
else
{
$prefx= substr($brcode,0,3);
}
//$bilinvno=$prefx.$rr1[invno];
 $bilinvno=$rr1['invno'];  
 
 if($rr1['doctype']=='Credit Note')
 {
  $doctype1='CRN';   
 }
 
 else
 {
     $doctype1='INV';
 }
 
 
    $invdate = substr($rr1[3],8,2).'/'.substr($rr1[3],5,2).'/'.substr($rr1[3],0,4);   
    if($flag==0)
    {
    
    $aftertxvl=$rr1[9]+$rr1[4]+$rr1[5]+$rr1[6]+$rr1[8]+$rr1[10];
    /*
    $toqry_tcs=mysqli_query($db,"select corp from customer where cst='$togstin'");
    $toar_tcs=mysqli_fetch_array($toqry_tcs);
    $tcsflg = $toar_tcs[0];
    
    $mtotinvvalue   = $aftertxvl;
   */
    if($chkflg==1)
    {
        
    }
    else
    {
      $myJSON.=',';  
    }
    $myJSON.=PHP_EOL.'{'.PHP_EOL.'"Version":"1.1",'.PHP_EOL.'"TranDtls":';
    $myJSON.= '{'.PHP_EOL.'        "TaxSch":"GST",'.PHP_EOL.'        "SupTyp":"B2B",'.PHP_EOL.'        "IgstOnIntra":"N",'.PHP_EOL.'        "RegRev":"N",'.PHP_EOL.'        "EcmGstin":null'.PHP_EOL.'},';
    $myJSON.=PHP_EOL.'"DocDtls":{'.PHP_EOL.'        "Typ":"'.$doctype1.'",'.PHP_EOL.'        "No":"'.$invno.'",'.PHP_EOL.'        "Dt":"'.$invdate.'"'.PHP_EOL.'},';
    $myJSON.=PHP_EOL.'"SellerDtls":{'.PHP_EOL.'        "Gstin":"'.$frgstin.'",'.PHP_EOL.'        "LglNm":"'.$frbrnm.'",'.PHP_EOL.'        "TrdNm":null,'.PHP_EOL.'        "Addr1":"'.$fraddr1.'",'.PHP_EOL.'        "Addr2":"'.$fraddr2.'",'.PHP_EOL.'        "Loc":"'.$brstate.'",'.PHP_EOL.'        "Pin":'.$frpin.','.PHP_EOL.'        "Stcd":"'.$frstcod.'",'.PHP_EOL.'        "Ph":null,'.PHP_EOL.'        "Em":null'.PHP_EOL.'},';
    $myJSON.=PHP_EOL.'"BuyerDtls":{'.PHP_EOL.'        "Gstin":"'.$togstin.'",'.PHP_EOL.'        "LglNm":"'.$tobrnm.'",'.PHP_EOL.'        "TrdNm":null,'.PHP_EOL.'        "Pos":"'.$statecodeval.'",'.PHP_EOL.'        "Addr1":"'.$toaddr1.'",'.PHP_EOL.'        "Addr2":null,'.PHP_EOL.'        "Loc":"'.$rr1['buystate'].'",'.PHP_EOL.'        "Pin":'.$topin.','.PHP_EOL.'        "Stcd":"'.$statecodeval.'",'.PHP_EOL.'        "Ph":null,'.PHP_EOL.'        "Em":null'.PHP_EOL.'},';
    $myJSON.=PHP_EOL.'"DispDtls":null,';
    $myJSON.=PHP_EOL.'"ShipDtls":null,';
    $massval  = $rr1[9];
    $migstval = $rr1[6];
    $mcgstval = $rr1[4];
    $msgstval = $rr1[5];
    $mcesval  = $rr1[8];
    $mother  =$rr1[10];
    $totinvval= $rr1[1];
    /*
    if($tcsflg=='Yes')
    {
        $mtot_tcs = 0;
        $re_tcs1=mysqli_query($db,"select * from sap_einvoice where invno='$id2' and brcode='$brcode'");
        while($row_tcs1=mysqli_fetch_array($re_tcs1))
        {
            $mtot_tcs = $mtot_tcs + round(($row_tcs1[aprice]+$row_tcs1[cgstamt]+$row_tcs1[sgstamt]+$row_tcs1[igstamt]+$row_tcs1[cessamt])*.075/100,2);
        }
        //$mtot_tcs = round($rr1[18],2);
        $totinvval =$totinvval+$mtot_tcs;
    }
    */
    $myJSON.=PHP_EOL.'"ValDtls":{'.PHP_EOL.'        "AssVal":'.$massval.','.PHP_EOL.'        "IgstVal":'.$migstval.','.PHP_EOL.'        "CgstVal":'.$mcgstval.','.PHP_EOL.'        "SgstVal":'.$msgstval.','.PHP_EOL.'        "CesVal":0,'.PHP_EOL.'        "StCesVal":'.$mcesval.','.PHP_EOL.'        "Discount":0,'.PHP_EOL.'        "OthChrg":0,'.PHP_EOL.'        "RndOffAmt":0,'.PHP_EOL.'        "TotInvVal":'.$totinvval.''.PHP_EOL.'},';
    $myJSON.=PHP_EOL.'"ExpDtls":{'.PHP_EOL.'        "ShipBNo":null,'.PHP_EOL.'        "ShipBDt":null,'.PHP_EOL.'        "Port":null,'.PHP_EOL.'        "RefClm":null,'.PHP_EOL.'        "ForCur":null,'.PHP_EOL.'        "CntCode":null,'.PHP_EOL.'        "ExpDuty":0'.PHP_EOL.'},';
    
    $myJSON.=PHP_EOL.'"EwbDtls":null,'.PHP_EOL.'            "ItemList":[';
    
    
    
    $re=mysqli_query($db,"select * from sap_einvoice where invno='$id2' and brcode='$brcode'");
    $sq="select * from sap_einvoice where invno='$invno' and brcode='$brcode'";
    //echo $sq;
    //echo "<br>";
    $i=1;
    $myJSON1='';
    while($row=mysqli_fetch_array($re))
    {
        //echo $i;
        //echo "<br>";
        //$hsnqry=mysqli_query($db,"select hsncode from partmaster where partcode='$row[partcode]'");
        //$hsnarr=mysqli_fetch_array($hsnqry);
        $gstrt = $row['gstp'];
        $mqty = $row['qty'];
        if($row['qty']>0)
        {
            $unitprice = round($row['aprice']/$row['qty'],2);
        }
        else
        {
            $unitprice =$row['aprice'];
            $mqty = 1;
        }
        $totamt=$row['aprice']+$row['igstamt']+$row['cgstamt']+$row['sgstamt']+$row['cessamt']+$row['other_charges'];
        $partnamevl=preg_replace("/[^ \w]+/", "", $row['proddesc']);
        $mtcs_amt=0;
        
        /*
        if($tcsflg=='Yes')
        {
            $mtcs_amt = round($totamt*0.075/100,2);
            $totamt=$totamt+$mtcs_amt;
        }
        */
        //echo $partnamevl;
        
        //$mtcs_amt = round($totamt*0.075/100,2);
            //$totamt=$totamt+$mtcs_amt;
            $mtcs_amt=$row['other_charges'];
        if($row['srvflg']=='YES')
        {
            $srvflg='Y';
        }
        if($row['srvflg']=='NO')
        {
            $srvflg='N';
        }
        $myJSON1.=PHP_EOL.'               {'.PHP_EOL.'                "SlNo":"'.$i++.'",'.PHP_EOL.'                "PrdDesc":"'.addslashes($partnamevl).'",'.PHP_EOL.'                "IsServc":"'.$srvflg.'",'.PHP_EOL.'                "HsnCd":"'.$row['hsncode'].'",'.PHP_EOL.'                "Barcde":null,'.PHP_EOL.'                "Qty":'.$mqty.','.PHP_EOL.'                "FreeQty":0,'.PHP_EOL.'                "Unit":"NOS",'.PHP_EOL.'                "UnitPrice":'.$unitprice.','.PHP_EOL.'                "TotAmt":'.$row['aprice'].','.PHP_EOL.'                "Discount":0,'.PHP_EOL.'                "PreTaxVal":0,'.PHP_EOL.'                "AssAmt":'.$row['aprice'].','.PHP_EOL.'                "GstRt":'.$gstrt.','.PHP_EOL.'                "IgstAmt":'.$row['igstamt'].','.PHP_EOL.'                "CgstAmt":'.$row['cgstamt'].','.PHP_EOL.'                "SgstAmt":'.$row['sgstamt'].','.PHP_EOL.'                "CesRt":0,'.PHP_EOL.'                "CesAmt":0,'.PHP_EOL.'                "CesNonAdvlAmt":0,'.PHP_EOL.'                "StateCesRt":'.$row['cessp'].','.PHP_EOL.'                "StateCesAmt":'.$row['cessamt'].','.PHP_EOL.'                "StateCesNonAdvlAmt":0,'.PHP_EOL.'                "OthChrg":'.$mtcs_amt.','.PHP_EOL.'                "TotItemVal":'.$totamt.','.PHP_EOL.'                "BchDtls":null';
        $myJSON1.=PHP_EOL.'               },';
        
        //"productName":"'.addslashes($row[partcode]).'","productDesc":"'.addslashes($partnamevl).'","hsnCode":"'.addslashes($hsnarr[hsncode]).'","quantity":"'.addslashes($row[qty]).'","qtyUnit":"NOS","taxableAmount":"'.addslashes($row[aprice]).'","sgstRate":"'.addslashes($row[sgstp]).'","cgstRate":"'.addslashes($row[cgstp]).'","igstRate":"'.addslashes($row[igstp]).'","cessRate":"'.addslashes($row[cessp]).'","cessNonAdvol":"0"},';	 	 
   
    }

    $dttime=date("Y-m-d h:i:s");
    $re1=mysqli_query($db,"insert into tbl_einvoice (brcode,invno,invtype,createtime,user1) values('$brcode','$invno','sprinv','$dttime','$user')");

   //echo $myJSON1;
   //echo "<br>";
   $myJSON1=substr($myJSON1,0,strlen($myJSON1)-1);
    //$myJSON1[strrpos($myJSON1, ',')] = '';
    $myJSON1=trim($myJSON1);
    $myJSON.=$myJSON1;
    $myJSON.=']'.PHP_EOL.'},';
    
    $chkflg++;
    
    }
//}



}
$myJSON=rtrim($myJSON, ',');
$myJSON.=']';
}
}

//echo $myJSON;
//$myJSON=rtrim($myJSON, ',');

    
    $json_data = $myJSON;
    file_put_contents('results.json', $json_data);
    //$filename='sprjson.json';
    # send the file to the browser as a download
    header('Content-disposition: attachment; filename=sprjson.json');
    header('Content-type: application/json');
    echo $json_data;
    
    
    
    return;
    




?>
