<? 
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(tot),invno,entrydate,sum(cgstamt),sum(sgstamt),sum(igstamt),brcode,sum(cessamt),sum(aprice),sum(adltcsamt),partcode from spareinvoice where invno='$invno' and brcode='$brcode'");
	$sss="select customer,sum(tot),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[tin];
    $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];
    $fraddr2=substr($fraddr2, 0, 50);
    $fraddr2=preg_replace("/[^ \w]+/", "", $fraddr2);
    $frpin=$frar[brtype];
    $mleft = substr($tobrcode,0,14);
    $mright = substr($tobrcode,-9);
    $toqry=mysqli_query($db,"select * from customer where left(acname,14)='$mleft' and right(acname,9)='$mright' and brcode='$brcode'");
    //print "select * from customer where left(acname,14)='$mleft' and right(acname,9)='$mright' and brcode='$brcode'";
    //exit;
    //print "select * from customer where left(acname,14)='$mleft' and right(acname,9)='$mright' and brcode='$brcode'";
    $toar=mysqli_fetch_array($toqry);
    $togstin=$toar[gst];
    $togstin=trim($togstin);
    if(strlen($togstin)=='15')
    {
      $custgstn=$togstin;
      $gstflg=1;
    }
    if(strtoupper($togstin)=='URP')
    {
      $custgstn='URP';
      $gstflg=1;
    }
    /*
    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($tobrcode<='')
    {
        print "<script>alert('Invalid Invoice'); </script>";
        print "<script>document.location='ewayinvoiceentry.php'</script>";
        $flag++;
    }
    if($gstflg!='1')
    {
        print "<script>alert('Customer GST not Updated!'); </script>";
        print "<script>document.location='ewayinvoiceentry.php'</script>";
        $flag++;
    }
    if($toar[state1]<='')
    {
        print "<script>alert('state empty'); </script>";
        print "<script>document.location='ewayinvoiceentry.php'</script>";
        $flag++;
    }
    $topin=$toar[pin1];
    if($topin<='')
    {
       print "<script>alert('PIN empty'); </script>";
        print "<script>document.location='ewayinvoiceentry.php'</script>"; 
        $flag++;
    }
     $stquery="select code from states where state=UPPER('$toar[state1]')";
     $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='ewayinvoiceentry.php'</script>"; 
        $flag++;
    }
    $entrydate=$rr1[entrydate];
    $entrydate1=implode('/', array_reverse(explode('-', $entrydate)));
    $bilinvno=$rr1[invno];
    if($flag==0)
    {
        $hsnftch=mysqli_query($db,"select location from partmaster where partcode='$rr1[11]'");
        	$hsnftch1=mysqli_fetch_array($hsnftch);
        $hsnval=$hsnftch1[0];
		$aftertxvl=$rr1[9]+$rr1[4]+$rr1[5]+$rr1[6]+$rr1[10];
	    $mtotinvvalue   = $aftertxvl;
	    $myJSON.='{"version":"1.0.0621","billLists":[';
	    $myJSON.=	'{"userGstin":"'.$frgstin.'","supplyType":"O","subSupplyType":"1","subSupplyDesc":"","docType":"INV","docNo":"'.addslashes($bilinvno).'","docDate":"'.addslashes($entrydate1).'","transType":"1","fromGstin":"'.$frgstin.'","fromTrdName":"'.$frbrnm.'","fromAddr1":"'.$fraddr1.'","fromAddr2":"'.$fraddr2.'","fromPlace":"'.$fraddr2.'","fromPincode":"'.$frpin.'","fromStateCode":"'.$frstcod.'","actualFromStateCode":"'.$frstcod.'","toGstin":"'.$custgstn.'","toTrdname":"'.$tobrnm.'","toAddr1":"'.$toaddr1.'","toAddr2":"'.$toaddr2.'","toPlace":"'.$toaddr2.'","toPincode":"'.$topin.'","toStateCode":"'.$tostcod.'","actualToStateCode":"'.$tostcod.'","totalValue":"'.addslashes($rr1[9]).'","cgstValue":"'.addslashes($rr1[4]).'","sgstValue":"'.addslashes($rr1[5]).'","igstValue":"'.addslashes($rr1[6]).'","cessValue":"0","TotNonAdvolVal":"1","OthValue":"'.addslashes($rr1[10]).'","totInvValue":"'.addslashes($mtotinvvalue).'","transMode":"1","transDistance":"'.addslashes($transdist).'","transporterName":"'.addslashes($trnspnm).'","transporterId":"'.addslashes($transid).'","transDocNo":"'.addslashes($docno).'","transDocDate":"'.addslashes($entrydate1).'","vehicleNo":"'.addslashes($vehicleno).'","vehicleType":"R","mainHsnCode":'.addslashes($hsnval).','; 
	    
	    
		$myJSON.= '"itemList":[';
		$re=mysqli_query($db,"select * from spareinvoice where invno='$invno' and brcode='$brcode'");
		$sql="select * from sparetransout where tr_no='$invno' and brcode='$brcode'";
		//echo $sql;
		$i=1;
		while($row=mysqli_fetch_array($re))
		{
		    $cessamtvl=$row[adltcsamt];
		    $hsnqry=mysqli_query($db,"select location from partmaster where partcode='$row[partcode]'");
		    $hsnarr=mysqli_fetch_array($hsnqry);
		    $hsncode=str_replace(" ", "", $hsnarr[0]);
		    //$partnamevl=preg_replace('/[^A-Za-z0-9\-]/', '', $row[partname]);
		    $partnamevl=preg_replace("/[^ \w]+/", "", $row[partname]);
			$myJSON1.= '{"itemNo":"'.$i++.'","productName":"'.addslashes($row[partcode]).'","productDesc":"'.addslashes($partnamevl).'","hsnCode":"'.addslashes($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++;
		}
		$myJSON1[strrpos($myJSON1, ',')] = '';
		//$myJSON1.= trim($myJSON1,',').']';
		//echo $myJSON1;
		$myJSON1=trim($myJSON1);
		$myJSON.=$myJSON1;
		//echo trim($myJSON,',').']';
		//echo '['.trim($myJSON,',').']';
		$myJSON.=']}]}';

		//echo $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;
		//print "<script>document.location='retreive.php'</script>";
		return;
	}
}
?>
