<? 
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 config,netamt,ret_num,date,round(tax/2,2),round(tax/2,2),tax,brcode,0,amt2,retfrom,mcode from crnote_gst  where ret_num='$id2' and brcode='$brcode'");
//$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 "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['retfrom'];
    $invno=$rr1['ret_num'];
    $frqry=mysqli_query($db,"select * from branch where brcode='$brcode'");
    $frar=mysqli_fetch_array($frqry);
    $frgstin=$frar['gst'];
    $frstcod = substr($frgstin, 0, 2);
    $frbrnm='PSN AUTOMOBILES PVT LTD';
    $fraddr1=$frar['braddr'];
    $fraddr1=substr($fraddr1, 0, 50);
    $fraddr1=preg_replace("/[^ \w]+/", "", $fraddr1);
    $fraddr2=$frar['brcity'];
    $brstate='Kerala';
    $fraddr2=substr($fraddr2, 0, 50);
    $fraddr2=preg_replace("/[^ \w]+/", "", $fraddr2);
    $frpin=substr($frar['brcity'],-6);
    
    
    
    $toqry=mysqli_query($db,"select * from cust_master where code='$tobrcode'");

  
    $toar=mysqli_fetch_array($toqry);
    $togstin=$toar['tin'];
    $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=$toar['acname'];
    $tobrnm=preg_replace("/[^ \w]+/", "", $tobrnm);
    $tobrnm = preg_replace('/\s\s+/', ' ', $tobrnm);
    $toaddr1=$toar['addr1'];
    $toaddr1=substr($toaddr1, 0, 50);
    $toaddr1=preg_replace("/[^ \w]+/", "", $toaddr1);
    $toaddr1 = preg_replace('/\s\s+/', ' ', $toaddr1);
    $toaddr2=$toar['addr2'];
    $toaddr2=substr($toaddr2, 0, 50);
    $toaddr2=preg_replace("/[^ \w]+/", "", $toaddr2);
    $flag=0;
    if($toar['stat']<='')
    {
        print "<script>alert('state empty'); </script>";
        print "<script>document.location='sap_creditnotejson.php'</script>";
        $flag++;
    }
    $topin=$toar['pin'];
    if($topin<='')
    {
       print "<script>alert('PIN empty'); </script>";
        print "<script>document.location='sap_creditnotejson.php'</script>"; 
        $flag++;
    }
     $stquery="select code from states where state=UPPER('$toar[stat]')";
     $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_creditnotejson.php'</script>"; 
        $flag++;
    }
    if($togstin=='URP')
    {
        $statecodeval=$tostcod;
        
    }
    else
    {
       $statecodeval= substr($togstin,0,2);
    }
    
    $entrydate=$rr1['date'];
    //$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';
 }
 
  $doctype1='CRN';
    $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];
    
    /*
    $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":"'.$toar['stat'].'",'.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];
    if($rr1[11]=='INTERSTATE')
    {
        $migstval = $rr1[6];
        $mcgstval = 0;
        $msgstval = 0;
    }
    else
    {
        $migstval = 0;
        $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 crnote_gst where ret_num='$id2' and brcode='$brcode'");
    //echo $sq;
    //echo "<br>";
    $i=1;
    $myJSON1='';
    while($row=mysqli_fetch_array($re))
    {
        //echo $i;
        //echo "<br>";
        
        $descqry=mysqli_query($db,"select config from veh_invoice where invno='$row[sale_invoice]'");
        $descarr=mysqli_fetch_array($descqry);
        $prddescc=$descarr[0];
        $gstrt = $row['taxp'];
        $unitprice = $row['amt2'];
        $totamt=$row['netamt'];
        $partnamevl=preg_replace("/[^ \w]+/", "", $prddescc);
        $partnamevl = preg_replace('/\s\s+/', ' ', $partnamevl);
        $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['mcode']=='INTERSTATE')
        {
            $migstamt=$row['tax'];
            $mcgstamt=0;
            $msgstamt=0;
        }
        else
        {
            $migstamt=0;
            $mcgstamt=round($row['tax']/2,2);
            $msgstamt=round($row['tax']/2,2);;
        }
        $hsnquery="select hsncode from veh_invoice where da='$row[da]'";
        //echo $stquery;
        $hsnreslt=mysqli_query($db,$hsnquery);
        $mhsnrow=mysqli_fetch_array($hsnreslt);
        $mhsncode = $mhsnrow[0];
        
        $myJSON1.=PHP_EOL.'               {'.PHP_EOL.'                "SlNo":"'.$i++.'",'.PHP_EOL.'                "PrdDesc":"'.addslashes($partnamevl).'",'.PHP_EOL.'                "IsServc":"N",'.PHP_EOL.'                "HsnCd":"'.$mhsncode.'",'.PHP_EOL.'                "Barcde":null,'.PHP_EOL.'                "Qty":0,'.PHP_EOL.'                "FreeQty":0,'.PHP_EOL.'                "Unit":"NOS",'.PHP_EOL.'                "UnitPrice":'.$unitprice.','.PHP_EOL.'                "TotAmt":'.$row['amt2'].','.PHP_EOL.'                "Discount":0,'.PHP_EOL.'                "PreTaxVal":0,'.PHP_EOL.'                "AssAmt":'.$row['amt2'].','.PHP_EOL.'                "GstRt":'.$gstrt.','.PHP_EOL.'                "IgstAmt":'.$migstamt.','.PHP_EOL.'                "CgstAmt":'.$mcgstamt.','.PHP_EOL.'                "SgstAmt":'.$msgstamt.','.PHP_EOL.'                "CesRt":0,'.PHP_EOL.'                "CesAmt":0,'.PHP_EOL.'                "CesNonAdvlAmt":0,'.PHP_EOL.'                "StateCesRt":0,'.PHP_EOL.'                "StateCesAmt":0,'.PHP_EOL.'                "StateCesNonAdvlAmt":0,'.PHP_EOL.'                "OthChrg":0,'.PHP_EOL.'                "TotItemVal":'.$row['netamt'].','.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;
    




?>
