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

ini_set('display_errors', 1);
error_reporting(E_ERROR);

$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");
$saltype = $_REQUEST['saltype'];
// browse($saltype);

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

if ($para != 'C') {

    if ($saltype == 'R') {
        $maindb = 'rawmain';
        $trandb = 'rawtran';
        $itemdb = 'rawmat';
        $gstdb = "gsteinvoice";
        $deemexp = 'L';
        $suptype = "B2B";
        $revchg = 'N';
    } else {
        $maindb = 'gstmain';
        $trandb = 'gsttran';
        $itemdb = 'item';

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

<script>



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

    if (r == true) {

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



</script>
<?php

$compcd = $_SESSION["comp_" . $dbname];
$myyear = $_SESSION[$myyear];

$invno = $billno;


$mainqry = mysqli_query($conn, "SELECT *, DATE_FORMAT(`vouchdt`, '%d/%m/%Y') AS chaldate FROM `$maindb`
                                       WHERE invno = '$invno'") or die(mysqli_error($conn));
// print table($mainqry);
// die();

$data = mysqli_fetch_array($mainqry);
$irn = $data["irn"];

//if ($data['transmode'] != "" && $data['distance'] > 0) {
//browse($compcd)
$actcomp = mysqli_query($conn, "SELECT * FROM $zroot.`company` where code ='$compcd'")or die(mysqli_error($conn));
//print table($actcomp);
//die();
$compn = mysqli_fetch_array($actcomp);
$ginv = $tinv = $cinv = "";
$gstno = $compn['gst'];

$a = 1;
//browse($gstno);

$billno = $data["invno"];

//    die();
$getcust = mysqli_query($conn, "SELECT * FROM `accmast` WHERE `accode`='$data[party]'")or die(mysqli_error($conn));
// print table($getcust);
// die();
$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);
//browse($fettrans['name']);
//browse($fettrans['gstno']);


if ($data['transporter'] != "") {
    $tranname = "$fettrans[name]";
} else {
    $tranname = 'null';
}
if ($fettrans['gstno'] != "") {
    $trangst = "$fettrans[gstno]";
} else {
    $trangst = 'null';
}
//browse($trangst);
if ($data['vehno'] != "") {
    $vehno = "$data[vehno]";
} else {
    $vehno = '0';
}
//if ($data['delgstno'] == "") {
    $cgstno = $cust['gstno'];
//} else {
//    $cgstno = $data['delgstno'];
//}
//browse($cgstno);
//browse($cgstno);

if ($data['deladd1'] == "") {
    $custname = $cust['name'];
} else {
    $custname = $data['deladd1'];
}

if ($data['deladd2'] == "") {
    $custadd1 = $cust['add1'];
} else {
    $custadd1 = $data['deladd2'];
}

if ($data['deladd3'] == "") {
    $custadd2 = $cust['add2'];
} else {
    $custadd2 = $data['deladd3'];
}
if ($data['deladd4'] == "") {
    $custadd3 = $cust['add3'];
} else {
    $custadd3 = $data['deladd4'];
}
if ($data['delcity'] == "") {
    $custcity = $cust['city'];
} else {
    $custcity = $data['delcity'];
}
if ($data['delpin'] == "") {
    $custpin = $cust['pin'];
} else {
    $custpin = $data['delpin'];
}
if ($data['delstatecode'] == "") {
    $custstcd = $cust['statecode'];
} else {
    $custstcd = $data['delstatecode'];
}
    $actcuststcd = $cust['statecode'];

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

if ($irn != "") {
    if ($a == 1) {

        $curl = curl_init();

//        echo"{
//            'Irn': '$irn',
//            'Distance': 0,
//            'TransMode':  null,
//            'TransId': '$trangst',
//            'TransName': '$tranname',
//            'TransDocDt': null,
//            'TransDocNo': null,
//            'VehNo': $vehno,
//            'VehType': null}";
//        die();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.mygstcafe.com/eicore/v1.03/einvewb/ewaybill',
            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 => "{
            'Irn': '$irn',
            'Distance': 0,
            'TransMode':  null,
            'TransId': '$trangst',
            'TransName': '$tranname',
            'TransDocDt': null,
            'TransDocNo': null,
            'VehType': null}",
            CURLOPT_HTTPHEADER => array(
                "GSTIN: $gstno",
                "CustomerName: $compn[pname]",
                "Branch: $compn[state]",
                "Username: $compn[apiuser]",
                "Password: $compn[apipass]",
                'CustomerId: ASP10142',
                'APIId: eqGWltJk-PG1V-fcFG-UrED-RBJOgxRe',
                'APISecret: eqGWltJkPG1VfcFG',
                'Source: API',
//                'Environment-type: Production',
                'Content-Type: application/json'
            ),
        ));



        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;

        $mres = json_decode($response, true);

        print $mres['response_data'];
        $ewaybillno = $mres['response_data']['EwbNo'];
        $ewaydt = $mres['response_data']['EwbDt'];
        $ewbvaliddt = $mres['response_data']['EwbValidTill'];
        if ($ewaybillno != "") {
            mysqli_query($conn, "Update `$maindb` set ewaybillno = '$ewaybillno', ewaydt ='$ewaydt', ewbvaliddt='$ewbvaliddt' where irn ='$irn' ") or die(mysqli_error($conn));

            $ginv = $ginv . $billno . ",";
            echo "Generated Succesfully";
            print $mres;
        } else {
            $cinv = $cinv . $billno . ",";
        }
    } else {
        $tinv = $tinv . $billno . ",";
    }

//    Echo "Generate E-Way Bill are : $ginv<br>";
//    Echo "Not Generate E-invoice are : $tinv<br>";
//    Echo "Entries with Issue are : $cinv<br>";
} else {

    $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['cgst1'] + $data['cgst5'] + $data['cgst12'] + $data['cgst18'] + $data['cgst28'] - $cpack;
    $totsgst1 = $data['cgst1'] + $data['cgst5'] + $data['cgst12'] + $data['cgst18'] + $data['cgst28'] - $cpack;
    $totigst1 = $data['igst1'] + $data['igst5'] + $data['igst12'] + $data['igst18'] + $data['igst28'] - $ipack;
    $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'] - $totpost;
    $assval = number_format((float) $assval1, 2, '.', '');

    $delvchgs1 = $data['postamt'] + $data['tcsamt'] + $cpack1;
    $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;
    while ($ftran = mysqli_fetch_array($gettran)) {

        $ctr++;
        $discamt = $ftran['discamt'];
        $itmcode = $ftran['item'];
        $getitname = mysqli_query($conn, "SELECT * FROM `$itemdb` WHERE `code`='$itmcode'")or die(mysqli_error($conn));
        $titname = mysqli_fetch_array($getitname);
        $titemname = trim($titname["name"]);
        $unit = $titname['unit'];
        $hsncode = $titname['hsncode'];
        $qty = $ftran['qty'];
        $gstperc = $ftran['gstperc'];

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

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

        $itemarray[] = [
            "productName" => "$titemname",
            "productDesc" => "$titemname",
            "hsnCode" => $hsncode,
            "quantity" => $qty,
            "qtyUnit" => $ftran['unit'],
            "cgstRate" => $cgstrate,
            "sgstRate" => $cgstrate,
            "igstRate" => $igstrate,
            "cessRate" => 0,
            "cessNonadvol" => 0,
            "taxableAmount" => $ftran['subtot']
        ];
    }
//    if ($series != 'EX') {
    $sstype = '1';
//    } else {
//        $sstype = '3';
//    }
    $transtype = $data['transactype'];

//    $docno = $data['invno'];
    $docno = "$data[invno]/" . left($zyear, 2) . "-" . right($zyear, 2);


    $payload = [
        "supplyType" => "O",
        "subSupplyType" => "$sstype",
        "subSupplyDesc" => "",
        "docType" => "INV",
        "docNo" => "$docno",
        "docDate" => "$data[chaldate]",
        "fromGstin" => "$compn[gst]",
        "fromTrdName" => "$compn[pname]",
        "fromAddr1" => "$compn[add1]",
        "fromAddr2" => "$compn[add2]",
        "fromPlace" => "$compn[state]",
        "fromPincode" => $compn['pin'],
        "actFromStateCode" => $compn['statecode'],
        "fromStateCode" => $compn['statecode'],
        "toGstin" => $cgstno,
        "toTrdName" => $custname,
        "toAddr1" => $custadd1,
        "toAddr2" => $custadd2,
        "toPlace" => $custcity,
        "toPincode" => $custpin,
        "actToStateCode" => $custstcd,
        "toStateCode" => $actcuststcd,
        "transactionType" => $transtype,
        "otherValue" => "$delvchgs",
        "totalValue" => $assval,
        "cgstValue" => $totcgst,
        "sgstValue" => $totsgst,
        "igstValue" => $totigst,
        "cessValue" => 0,
        "cessNonAdvolValue" => 0,
        "totInvValue" => $billamt,
        "transporterId" => "$trangst",
        "transporterName" => "$tranname",
        "transDocNo" => "$data[lrno]",
        "transMode" => "",
        "transDistance" => 0,
        "transDocDate" => "$data[lrdt]",
        "vehicleNo" => "",
        "vehicleType" => "",
        "ItemList" => $itemarray,
        "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);
    $curl = curl_init();

//    print $newjs;
//    die();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://ewayapi.mygstcafe.com/managed/v1.03/GenerateEwayBill',
        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[pname]",
            "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',
            'Environment-type: Production'
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    $mres = json_decode($response, true);
    $ewaybillno = $mres['data']['ewayBillNo'];
    $ewaydt = $mres['data']['ewayBillDate'];
    $ewbvaliddt = $mres['data']['EwbValidTill'];
    if ($ewaybillno != "") {
        mysqli_query($conn, "Update `$maindb` set ewaybillno = '$ewaybillno', ewaydt ='$ewaydt', ewbvaliddt='$ewbvaliddt' where invno ='$billno' ") or die(mysqli_error($conn));
        $ginv = $ginv . $billno . ",";
    } else {
        echo $billno;
        print_r($mres);

        $cinv = $cinv . $billno . ",";
    }
}
//}
//else {
//    browse("No Transport Details Added. Please Check");
//    echo "<script>"
//    . "window.close();"
//            . "</script>";
//}