<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);
$admin = $_SESSION["admin_" . $dbname];
$success = false;
$zyear = right($zdb, 4);

$para = $_REQUEST['para'];


//$series = $_GET["series"];
//$invno = $_GET["invno"];
$zroot = $_SESSION["zdir"];
$date = date("Y-m-d");

$invdate = ($_REQUEST["invdate"]) ? $_REQUEST["invdate"] : $minvdate;
$billno = ($_REQUEST["invno"]) ? $_REQUEST["invno"] : $mbillno;
$series = ($_REQUEST["series"]) ? $_REQUEST["series"] : $mseries;


browse($invdate);
//if ($invdate < '2023-07-31') {
//    browse("Date Cannot be Less then October 1st");
//    echo "<script>"
//    . "window.close();"
//    . "</script>";
//}

if ($para != 'C') {
    $keyfld = "invno";
    $maindb = "billmain";
    $trandb = "billtran";
    $gstdb = "gsteinvoice";
    $deemexp = 'L';
    $suptype = "B2B";
    $revchg = 'N';
    $invtype = "INV";
} else {
    $keyfld = "vouchno";

    $maindb = "credmain";
    $trandb = "credtran";
    $deemexp = $series;
    $gstdb = "gsteinvoicecred";
    $invtype = "CRN";
    $suptype = "B2B";
    $revchg = 'N';
}
//$princo = ($_REQUEST["chkco"]) ? $_REQUEST["chkco"] : $mprinco;
?>

<script>



    var r = confirm("Are You Sure You want to Generate E Invoice?");

    if (r == true) {

    } else {
//        break;
        window.close();
    }



</script>
<?php

$myyear = $_SESSION[$myyear];

$invno = $billno;


$checks = (isset($_POST['check'])) ? $_POST['check'] : array();

$custcond = '';

if (count($checks) > 0) {
    foreach ($checks as $check) {
//        echo $check . ' ';
        $mycheck2[$count2++] .= "OR `vouchno` = '" . $check . "' ";
    }
    foreach ($mycheck2 as $g => $values2) {
        $mcheck2 .= $values2;
    }

    $custcond = " AND (`vouchno` = '' " . $mcheck2 . " )";
}
//$mainqry = mysqli_query($conn, "SELECT *, DATE_FORMAT(`date`, '%d/%m/%Y') AS chaldate FROM `gstmain` WHERE invno='$invno' AND `series`='$series'") or die(mysqli_error($conn));

$mainqry = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d/%m/%Y') AS chaldate FROM `$maindb`
                                WHERE vouchdt='$invdate' and party in 
                               (Select accode from accmast where gstno != '') and irn='' and `haltinv` != 'Y' $custcond") or die(mysqli_error($conn));
//                               (Select custcode from customer where gstno != '') and concat(invno,series)
//                                not in (Select concat(invno,series) from `gsteinvoice`)") or die(mysqli_error($conn));
//$data = mysqli_fetch_array($mainqry);
//print table($mainqry);
//die(); 
$actcomp = mysqli_query($conn, "SELECT * FROM $zroot.`company`")or die(mysqli_error($conn));
$compn = mysqli_fetch_array($actcomp);
$ginv = $tinv = $cinv = "";
$gstno = $compn['gstno'];
$a = 1;
if (strlen($gstno) < 3) {
    browse("Company GST No. Cannot Be Empty");
    $a = 0;
}
if ($compn['compname'] == "") {
    browse("Company Name Cannot Be Empty");
    $a = 0;
}
if ($compn['htel'] == "") {
    browse("Company Mobile Cannot Be Empty");
    $a = 0;
}
if ($compn['hocity'] == "") {
    browse("Company City Cannot Be Empty");
    $a = 0;
}
if ($compn['hopin'] == "") {
    browse("Company Pin Code Cannot Be Empty");
    $a = 0;
}
if ($compn['email'] == "") {
    browse("Company Email Id Cannot Be Empty");
    $a = 0;
}
if ($compn['statecode'] == "") {
    browse("Company State Code Cannot Be Empty");
    $a = 0;
}


while ($data = mysqli_fetch_array($mainqry)) {

//    if ($series != "RC") {
//        $cmpsrs = $series;
//    } else {
//        $cmpsrs = $data['frmsrs'];
//    }

    $billno = $data["vouchno"];

//    die();
    $getcust = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode`='$data[party]'")or die(mysqli_error($conn));
    $cust = mysqli_fetch_array($getcust);

    $gettrans = mysqli_query($conn, "SELECT * FROM `transport` WHERE `code`='$data[transporter]'")or die(mysqli_error($conn));
    $fettrans = mysqli_fetch_array($gettrans);
    $address = mysqli_real_escape_string($conn, $cust["address"]);

    $ad1 = substr($address, 0, 25);
    $ad2 = substr($address, 26, 70);
//    $ad3 = substr($address,71,50) ;

    $add1 = trim($cust['add1']);
    $add2 = trim($cust['add2']);
//    $add3 = trim($ad3);

    $cgstno = $cust['gstno'];
    $custname = $cust['name'];
    $custadd1 = $add1;
    $custadd2 = $add2;
    $custcity = $cust['city'];
    $custpin = $cust['pin'];
    $custstcd = $cust['statecode'];

    if ($cust['city'] == "") {
        browse("$cust[name] Customer City Cannot Be Empty");
        $a = 0;
    }
    if ($cust['pin'] == "") {
        browse("$cust[name] Customer Pin Code Cannot Be Empty");
        $a = 0;
    }
//    if ($cust['email'] == "") {
//        browse("Customer Email Id Cannot Be Empty");
//        $a = 0;
//    }
    if ($cust['statecode'] == "") {
        browse("$cust[name] Customer State Code Cannot Be Empty");
        $a = 0;
    }

    if (strlen($cgstno) < 3) {
        browse("$cust[name] Customer GST No. Cannot Be Empty");
        $a = 0;
    }



    $oms = $data['oms'];

//    $totpost = $data['postamt'];
//
//    $cpack1 = ( $totpost * 18 ) / 100;
//
//    $cgpack = $cpack1 / 2;
//
//    $cpack = number_format((float) $cgpack, 2, '.', '');
//    if ($oms != '1') {
//        $cpack = $cpack;
//        $ipack = 0;
//    } else {
//        $cpack = 0;
//        $ipack = number_format((float) $cpack1, 2, '.', '');
//    }


    $totcgst1 = $data['cgst5'] + $data['cgst12'] + $data['cgst18'] + $data['cgst28'];
    $totsgst1 = $data['cgst5'] + $data['cgst12'] + $data['cgst18'] + $data['cgst28'];
    $totigst1 = $data['igst5'] + $data['igst12'] + $data['igst18'] + $data['igst28'];
    $billamt = number_format((float) $data['billamt'], 2, '.', '');

    $totcgst = number_format((float) $totcgst1, 2, '.', '');
    $totsgst = number_format((float) $totsgst1, 2, '.', '');
    $totigst = number_format((float) $totigst1, 2, '.', '');

    $assval1 = $data['taxableamt'];
    $assval = number_format((float) $assval1, 2, '.', '');

//if ($cust['statecode'] != '27') {
//    $oms = 1;
//} else {
//    $oms = 0;
//} 
//if ($data['oms'] != 'is') {
//} else {
//    $oms = 0;
//}



    $delvchgs1 = $data['roundoff'];
    $delvchgs = number_format((float) $delvchgs1, 2, '.', '');
    $itemarray = array();

    $gettran = mysqli_query($conn, "SELECT * FROM `$trandb` WHERE vouchno='$data[vouchno]'")or die(mysqli_error($conn));

    $ctr = 0;
    $ctrn = 0;
    if ($data["ms"] == "S") {
        $issrvc = "Y";
        $unit = "NOS";
    } else {
        $unit = "PCS";
        $issrvc = "N";
    }
    while ($ftran = mysqli_fetch_array($gettran)) {

        $ctr++;
        $ctrn++;
        $discamt = $ftran['discamt'];
        $titemname = trim($ftran["descrip1"]) . " " . trim($ftran["descrip2"]);
//        $hsncode = $ftran['hsnportal']; stoped as it was not uploading
        $hsncode = $ftran['hsncode']; 
        $gstperc = $ftran['gstrate'];


        if ($oms == 1) {
            $igstamt1 = $ftran['igstamt'];
            $cgstamt = 0;
            $sgstamt = 0;
            $igstamt = number_format((float) $igstamt1, 2, '.', '');

            $itamt1 = $ftran['subtot'] + $igstamt;
        } else {
            $igstamt = 0;
            $cgstamt1 = $ftran['cgstamt'];
            $sgstamt1 = $ftran['sgstamt'];
            $cgstamt = number_format((float) $cgstamt1, 2, '.', '');
            $sgstamt = number_format((float) $sgstamt1, 2, '.', '');
            $itamt1 = $ftran['subtot'] + $cgstamt + $sgstamt;
        }
        $itamt = number_format((float) $itamt1, 2, '.', '');

        $itemarray[] = [
            "AttribDtls" => [
                [
                    "Nm" => "$titemname",
                    "Val" => $ftran['amount']
                ]
            ],
            "PrdSlNo" => $ctrn,
            "OrgCntry" => null,
            "OrdLineRef" => null,
            "TotItemVal" => $itamt,
            "OthChrg" => 0,
            "StateCesNonAdvlAmt" => 0,
            "StateCesAmt" => 0,
            "StateCesRt" => 0,
            "CesNonAdvlAmt" => 0,
            "CesAmt" => 0,
            "CesRt" => 0,
            "SgstAmt" => $sgstamt,
            "CgstAmt" => $cgstamt,
            "IgstAmt" => $igstamt,
            "Qty" => $ftran['qty'],
            "AssAmt" => $ftran['subtot'],
            "PreTaxVal" => 0,
            "Discount" => $discamt,
            "TotAmt" => $ftran['amount'],
            "UnitPrice" => $ftran['rate'],
            "Unit" => $unit,
            "FreeQty" => 0,
            "GstRt" => $ftran['gstrate'],
//            "Barcde" => "", // ask sir
//            "BchDtls" => [
//                "Nm" => "123456",
//                "ExpDt" => "01/08/2020",
//                "WrDt" => "01/09/2020"
//            ],
            "HsnCd" => $hsncode,
            "IsServc" => $issrvc,
            "PrdDesc" => $titemname,
            "SlNo" => "$ctr"
        ];
    }



    if ($para != 'C') {

        $docno = $data['billno'];
    } else {
        $docno = $data['billno'];
    }
    $docdt = $data['chaldate'];

//browse($docdt);
//browse($docno);
##for(){
#   $item = [
#   srno=>11,
#   itemname=>"adfas"
#   ];
#   itemarray.push($item)
#}

    if ($a == 1) {
        $payload = [
            "Version" => "1.1",
            "TranDtls" => [
                "TaxSch" => "GST",
                "SupTyp" => "$suptype",
                "RegRev" => "$revchg",
                "EcmGstin" => null,
                "IgstOnIntra" => "N"
            ],
            "DocDtls" => [
                "Typ" => "$invtype",
                "No" => "$docno",
                "Dt" => $docdt
            ],
            "BuyerDtls" => [
                "Gstin" => $cgstno,
                "LglNm" => $custname,
                "TrdNm" => $custname,
                "Pos" => $custstcd,
                "Addr1" => $custadd1,
                "Addr2" => $custadd2,
                "Loc" => $custcity,
                "Pin" => $custpin,
                "Stcd" => $custstcd
//            ,
//            "Ph" => $cust[tel],
//            "Em" => $cust[email]
            ],
            "SellerDtls" => [
                "Gstin" => $gstno,
                "LglNm" => $compn['compname'],
                "TrdNm" => $compn['compname'],
                "Addr1" => $compn['hoadd1'],
                "Addr2" => $compn['hoadd2'],
                "Loc" => $compn['hocity'],
                "Pin" => $compn['hopin'],
                "Stcd" => $compn['statecode'],
                "Ph" => $compn['mobile']
//            ,"Em" => $compn[mailto]
            ],
//    "DispDtls" => [
//        "Nm" => "",
//        "Addr1" => "",
//        "Addr2" => "",
//        "Loc" => "",
//        "Pin" => "",
//        "Stcd" => ""
//    ],
//    "ShipDtls" => [
//        "Gstin" => "",
//        "LglNm" => "",
//        "TrdNm" => "",
//        "Addr1" => "",
//        "Addr2" => "",
//        "Loc" => "",
//        "Pin" => "",
//        "Stcd" => ""
//    ],
//            "EwbDtls" => [
//                "TransId" => "$fettrans[gstno]",
//                "TransName" => "$fettrans[name]",
//                "TransMode" => null,
//                "Distance" => $data[distance],
//                "TransDocNo" => null,
//                "TransDocDt" => null,
//                "VehNo" => null,
//                "VehType" => null
//            ],
//    "ExpDtls" => [
//        "ShipBNo" => "",
//        "ShipBDt" => "",
//        "CntCode" => "",
//        "ForCur" => "",
//        "Port" => "",
//        "RefClm" => "",
//        "ExpDuty" => 0
//    ],
            "ItemList" => $itemarray,
            "ValDtls" => [
                "AssVal" => $assval,
                "CgstVal" => $totcgst,
                "SgstVal" => $totsgst,
                "IgstVal" => $totigst,
                "CesVal" => 0,
                "StCesVal" => 0,
                "RndOffAmt" => $delvchgs,
                "TotInvVal" => $billamt,
                "TotInvValFc" => 0,
                "Discount" => 0,
                "OthChrg" => 0
            ],
//    "PayDtls" => [
//        "Nm" => "",
//        "AccDet" => "",
//        "Mode" => "",
//        "FinInsBr" => "",
//        "CrTrn" => "",
//        "PayInstr" => "",
//        "PayTerm" => "",
//        "DirDr" => "",
//        "CrDay" => 0,
//        "PaidAmt" => 0,
//        "PaymtDue" => 0
//    ],
//    "RefDtls" => [
////        "InvRm" => "",
//        "PrecDocDtls" => [
//            [
//                "InvNo" => "",
//                "InvDt" => "",
//                "OthRefNo" => ""
//            ]
//        ],
//        "ContrDtls" => [
//            [
//                "RecAdvDt" => "",
//                "RecAdvRefr" => "",
//                "TendRefr" => "",
//                "ContrRefr" => "",
//                "ExtRefr" => "",
//                "ProjRefr" => "",
//                "PORefr" => "",
//                "PORefDt" => ""
//            ]
//        ],
//        "DocPerdDtls" => [
//            "InvStDt" => "$docdt",
//            "InvEndDt" => "$docdt"
//        ]
//    ],
            "AddlDocDtls" => [
                [
                    "Url" => "https://einv-apisandbox.nic.in",
                    "Docs" => "Test Doc",
                    "Info" => "Document Test"
                ]
            ]
        ];
        $json = json_encode($payload, true, JSON_UNESCAPED_SLASHES);
        $newjs = str_replace("\/", "/", $json);

/////////////    open this for checking issue //////////////////        
//  
//        print $newjs;
//        die();
//////////// and clos after  ////////////
//        
//    $test_url = 'https://testapi.mygstcafe.com/eicore/v1.03/Invoice';
        $prod_url = "https://api.mygstcafe.com/eicore/v1.03/Invoice";


        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $prod_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => "$newjs",
            CURLOPT_HTTPHEADER => array(
                "GSTIN:$gstno",
                "CustomerName:$compn[compname]",
                "Branch: $compn[city]",
                "Username: $compn[apiuser]",
                "Password: $compn[apipass]",
                'CustomerId: ASP10142',
                'APIId: eqGWltJk-PG1V-fcFG-UrED-RBJOgxRe',
                'APISecret: eqGWltJkPG1VfcFG',
                'Source: API',
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);

        $mres = json_decode($response, true);
//    print_r($mres);

        $irnno = $mres['response_data']['Irn'];
        $ackno = $mres['response_data']['AckNo'];
        $qrcode = $mres['response_data']['SignedQrCode'];
        $ewaybillno = $mres['response_data']['EwbNo'];
        $ewaydt = $mres['response_data']['EwbDt'];
        $ewbvaliddt = $mres['response_data']['EwbValidTill'];
        if ($irnno != "") {
            mysqli_query($conn, "Delete from `$gstdb` where invno ='$billno'") or die(mysqli_error($conn));

            mysqli_query($conn, "Insert into `$gstdb` (`invno`, `series`, `irno`, `ackno`, `qrcode`) VALUES ('$billno', '$series', '$irnno', '$ackno','$qrcode')") or die(mysqli_error($conn));
            mysqli_query($conn, "Update `$maindb` set uploaddate = '$date', irn ='$irnno' where `vouchno` ='$billno' ") or die(mysqli_error($conn));
            $ginv = $ginv . $docno . ",";
        } else {
            echo $docno;
            print_r($mres);


            $cinv = $cinv . $billno . ",";
        }
    } else {
        $tinv = $tinv . $billno . ",";
        print_r($mres);

//        browse("Not Uploaded  Invoice No. $billno. Fill Required Details in Customer");
//        echo "<script>"
//        . "window.close();"
//        . "</script>";
    }
}

Echo "Generate E-invoice are : $ginv<br>";
Echo "Not Generate E-invoice are : $tinv<br>";
Echo "Entries with Issue are : $cinv<br>";
echo "Please Check";











//"ItemList" => [
//        [
//            "AttribDtls" => [
//                [
//                    "Nm" => "Rice",
//                    "Val" => "10000"
//                ]
//            ],
//            "PrdSlNo" => "12345",
//            "OrgCntry" => null,
//            "OrdLineRef" => null,
//            "TotItemVal" => 20790.19,
//            "OthChrg" => 0,
//            "StateCesNonAdvlAmt" => 0,
//            "StateCesAmt" => 0,
//            "StateCesRt" => 0,
//            "CesNonAdvlAmt" => 0,
//            "CesAmt" => 0,
//            "CesRt" => 0,
//            "SgstAmt" => 0,
//            "CgstAmt" => 0,
//            "IgstAmt" => 2227.52,
//            "Qty" => 100.345,
//            "AssAmt" => 18562.67,
//            "PreTaxVal" => 0,
//            "Discount" => 0.07,
//            "TotAmt" => 18562.74,
//            "UnitPrice" => 883.94,
//            "Unit" => "BAG",
//            "FreeQty" => 10,
//            "GstRt" => 12,
//            "Barcde" => "123456",
//            "BchDtls" => [
//                "Nm" => "123456",
//                "ExpDt" => "01/08/2020",
//                "WrDt" => "01/09/2020"
//            ],
//            "HsnCd" => "1001",
//            "IsServc" => "N",
//            "PrdDesc" => "Rice",
//            "SlNo" => "1"
//        ],
//        [
//            "AttribDtls" => [
//                [
//                    "Nm" => "Rice",
//                    "Val" => "10000"
//                ]
//            ],
//            "PrdSlNo" => "12345",
//            "OrgCntry" => null,
//            "OrdLineRef" => null,
//            "TotItemVal" => 3225.6,
//            "OthChrg" => 0,
//            "StateCesNonAdvlAmt" => 0,
//            "StateCesAmt" => 0,
//            "StateCesRt" => 0,
//            "CesNonAdvlAmt" => 0,
//            "CesAmt" => 0,
//            "CesRt" => 0,
//            "SgstAmt" => 0,
//            "CgstAmt" => 0,
//            "IgstAmt" => 345.6,
//            "Qty" => 12,
//            "AssAmt" => 2880,
//            "PreTaxVal" => 0,
//            "Discount" => 0,
//            "TotAmt" => 2880,
//            "UnitPrice" => 240,
//            "Unit" => "PCS",
//            "FreeQty" => 0,
//            "GstRt" => 12,
//            "Barcde" => null,
//            "BchDtls" => [
//                "Nm" => "123456",
//                "ExpDt" => "01/08/2020",
//                "WrDt" => "01/09/2020"
//            ],
//            "HsnCd" => "9405",
//            "IsServc" => "N",
//            "PrdDesc" => null,
//            "SlNo" => "2"
//        ]
//    ],
