<? 
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'];
$minvno = $invno;
if(strlen($invno)>0)
{
    //$re1=mysqli_query($db,"select config,netamt,ret_num,date,round(tax/2,2),round(tax/2,2),0,brcode,0,amt2,retfrom from crnote_gst  where ret_num='$invno' and brcode='$brcode'");
    $re1=mysqli_query($db,"select expense_head as config,expense_amount as netamt,refno as ret_num,date,cgstamt,sgstamt,igstamt,brcode,0,before_tax as amt2,vendor as retfrom from gst_creditnote where refno='$invno' and brcode='$brcode'");
    //print "select config,netamt,ret_num,date,tax/2,tax/2,0,brcode,0,amt2,retfrom from dbnote_gst  where ret_num='$invno' and brcode='$brcode'";
    $rr1=mysqli_fetch_array($re1);

    $r=mysqli_query($db,"select * from cust_master where code='$rr1[retfrom]' and branch='$brcode'");
    $cusrow=mysqli_fetch_array($r);
    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['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 custname='$rr1[retfrom]' ");
    //$sq="select * from customer where acname='$tobrcode'";
    //echo $sq; 
    $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);
    $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['stat']<='')
    {
        print "<script>alert('state empty'); </script>";
        print "<script>document.location='einvoice_dbnote_gst.php'</script>";
        $flag++;
    }
    $topin=$toar['pin'];
    if($topin<='')
    {
       print "<script>alert('PIN empty'); </script>";
        print "<script>document.location='einvoice_dbnote_gst.php'</script>"; 
        $flag++;
    }
     $stquery="select code from states where state=UPPER('$toar[stat]')";
     //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_dbnote_gst.php'</script>"; 
        $flag++;
    }
    $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=$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":"DBN",'.PHP_EOL.'        "No":"'.$minvno.'",'.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":"'.substr($togstin,0,2).'",'.PHP_EOL.'        "Addr1":"'.$toar['addr1'].'",'.PHP_EOL.'        "Addr2":null,'.PHP_EOL.'        "Loc":"'.$toar['stat'].'",'.PHP_EOL.'        "Pin":'.$toar['pin'].','.PHP_EOL.'        "Stcd":"'.substr($togstin,0,2).'",'.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];
    $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":'.$mcesval.','.PHP_EOL.'        "StCesVal":0,'.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 gst_creditnote where refno='$invno' and brcode='$brcode'");
    $i=1;
    while($row=mysqli_fetch_array($re))
    {
     
        //$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];
        $mhsncode='';
        $gstrt = $row['cgstp']+$row['sgstp']+$row['igstp'];
        $unitprice = $row['before_tax'];
        $totamt=$row['before_tax']+$row['cgstamt']+$row['sgstamt']+$row['igstamt'];
        $partnamevl=preg_replace("/[^ \w]+/", "", $row['expense_head']);
        $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['before_tax'].','.PHP_EOL.'                "Discount":0,'.PHP_EOL.'                "PreTaxVal":0,'.PHP_EOL.'                "AssAmt":'.$row['before_tax'].','.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":0,'.PHP_EOL.'                "StateCesAmt":0,'.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','CR Notes','$dttime','$user')");
   $ss="insert into tbl_einvoice (brcode,invno,invtype,createtime) values('$brcode','$invno','sprinv','$dttime')";
   
    $myJSON1 = rtrim($myJSON1,',');
    $myJSON1=substr($myJSON1,0,strlen($myJSON1)-1);
    $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;
    
}
}


?>
