<? 
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'];
$trnspnm=$_REQUEST['trnspnm'];
$transid=$_REQUEST['transid'];
$transdist=$_REQUEST['transdist'];
$vehicleno=$_REQUEST['vehno'];
$docno=$_REQUEST['docno'];

if($invno>0)
{
$re1=mysqli_query($db,"select customer,sum(aprice+cgstamt+sgstamt+igstamt+cessamt),invno,entrydate,sum(cgstamt),sum(sgstamt),sum(igstamt),brcode,sum(cessamt),sum(aprice),tin from spareinvoice where invno='$invno' and brcode='$brcode'");
$sss="select customer,sum(aprice+cgstamt+sgstamt+igstamt+cessamt),invno,entrydate,sum(cgstamt),sum(sgstamt),sum(igstamt),brcode,sum(cessamt),sum(aprice),tin from spareinvoice where invno='$invno' and brcode='$brcode'";
//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'";

$rr1=mysqli_fetch_array($re1);
$tobrcode=$rr1[customer];
if(mysqli_num_rows($re1)<=0)
 {
    print "Invoice No does not exist";
    return;
 }
     $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=$frar[brphone];
    $mleft = substr($tobrcode,0,14);
    $mright = substr($tobrcode,-9);
    $toqry=mysqli_query($db,"select * from customer where acname='$tobrcode'");
    $ss="select * from customer where acname='$tobrcode' ";
  
    $toar=mysqli_fetch_array($toqry);
    $togstin=$rr1[tin];
    $togstin=trim($togstin);
    if(strlen($togstin)=='15')
    {
      $custgstn=$togstin;
      $gstflg=1;
    }
    if(strtoupper($togstin)=='URP')
    {
      $custgstn='URP';
      $gstflg=1;
    }
    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);
    $toaddr1=$toar[addr1];
    $toaddr1=substr($toaddr1, 0, 50);
    $toaddr1=preg_replace("/[^ \w]+/", "", $toaddr1);
    $toaddr2=$toar[dist1];
    $toaddr2=substr($toaddr2, 0, 50);
    $toaddr2=preg_replace("/[^ \w]+/", "", $toaddr2);
    $flag=0;
    
    if($toar[state1]<='')
    {
        print "<script>alert('state empty'); </script>";
        print "<script>document.location='einvoice_spareinvoicemak.php'</script>";
        $flag++;
    }
    $topin=$toar[pin1];
    if($topin<='')
    {
       print "<script>alert('PIN empty'); </script>";
        print "<script>document.location='einvoice_spareinvoicemak.php'</script>"; 
        $flag++;
    }
   
     $stquery="select code from states where state=UPPER('$toar[state1]')";
     //echo $stquery;
     $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='einvoice_spareinvoicemak.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];   
    $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];
    
    
    $mtotinvvalue   = $aftertxvl;
    $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":"INV",'.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[state1].'",'.PHP_EOL.'        "Pin":'.$toar[pin1].','.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  = 0;
    $totinvval= $rr1[1];
    $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":'.$mother.','.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 spareinvoice where invno='$invno' and brcode='$brcode'");
    $i=1;
    while($row=mysqli_fetch_array($re))
    {
        
        $gstrt = $row[igstp]+$row[cgstp]+$row[sgstp];
        $unitprice = round($row[aprice]/$row[qty],2);
        $totamt=$row[aprice]+$row[igstamt]+$row[cgstamt]+$row[sgstamt]+$row[cessamt];
        $partnamevl=preg_replace("/[^ \w]+/", "", $row[partname]);
        
        $qry="select hsncode from partmaster where partcode='$row[partcode]'";
		//echo $qry;
		$rsqr=mysqli_query($db,$qry);
		$rsrw=mysqli_fetch_array($rsqr);
        
        
        $myJSON1.=PHP_EOL.'               {'.PHP_EOL.'                "SlNo":"'.$i++.'",'.PHP_EOL.'                "PrdDesc":"'.addslashes($partnamevl).'",'.PHP_EOL.'                "IsServc":"N",'.PHP_EOL.'                "HsnCd":"'.addslashes($rsrw[hsncode]).'",'.PHP_EOL.'                "Barcde":null,'.PHP_EOL.'                "Qty":'.$row[qty].','.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":0,'.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"},';	 	 
    //$i++;
    }
    $dttime=date("Y-m-d h:i:s");
    $re1=mysqli_query($db,"insert into tbl_einvoice (brcode,invno,invtype,createtime,user1) values('$brcode','$invno','sprinvoth','$dttime','$user')");
   //$ss="insert into tbl_einvoice (brcode,invno,invtype,createtime) values('$brcode','$invno','sprinv','$dttime')";
   
   
    $myJSON1[strrpos($myJSON1, ',')] = '';
    $myJSON1=trim($myJSON1);
    $myJSON.=$myJSON1;
    $myJSON.=']'.PHP_EOL.'}]';
    $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;
    
    //print "<script>document.location='retreive.php'</script>";
    
    return;
    
}
}


?>
