<?php

require_once __DIR__ . '/catchexception.php';
require_once __DIR__ . '/sales_payload_helper.php';

try {

    // Read POST parameters
    $devicecode   = urldecode($_POST['paradevicecode'] ?? '');
    $imeino       = urldecode($_POST['paraimeino'] ?? '');
    $salescount   = urldecode($_POST['parasalescount'] ?? '');
    $billdate     = urldecode($_POST['parabilldate'] ?? '');
 //99caf25cb19a70cb- test 5845b939143f1813-Bazullah Road , 982a2b98a9dcbb98 - srilanka, 0056896C37F2E58EADA72AF1FAEFA535-Mgr MCH Central , d5a95aca53e83388 - Mgr Central 2 Non Veg , 4774a6e2826617bd - Mgr Central 2 Veg, 99caf25cb19a70cb - 'Express Avenue'
    // if ($imeino === '5845b939143f1813' || $imeino === '982a2b98a9dcbb98' || $imeino === '0056896C37F2E58EADA72AF1FAEFA535' || $imeino === 'd5a95aca53e83388' || $imeino === '4774a6e2826617bd' || $imeino === '99caf25cb19a70cb')
    //     {

    // Convert app string '{"JSonObject":[{...}]}' → valid PHP array for Node JSON body
    try {
        $salesarray = mch_normalize_sales_payload($_POST['salesarray'] ?? '');
        $salesitem  = mch_normalize_sales_payload($_POST['salesitem'] ?? '');
    } catch (InvalidArgumentException $e) {
        header('Content-Type: application/json');
        http_response_code(400);
        echo json_encode(array(
            'status' => 400,
            'message' => $e->getMessage(),
            'body' => array(),
        ));
        exit;
    }

    // Prepare request body
    $postData = array(
        "paradevicecode" => $devicecode,
        "paraimeino"     => $imeino,
        "parasalescount" => $salescount,
        "parabilldate"   => $billdate,
        "salesarray"     => $salesarray,
        "salesitem"      => $salesitem
    );

//     $postData = array(
//     "paradevicecode" => "1289",
//     "paraimeino" => "99caf25cb19a70cb",
//     "parasalescount" => "1",
//     "parabilldate" => "1778005800000",

//     "salesarray" => array(
//         "JSonObject" => array(
//             array(
//                 "transactionno" => "196370",
//                 "voucherno" => "117",
//                 "devicecode" => "99caf25cb19a70cb123",
//                 "branchcode" => "124",
//                 "transactiondate" => "1778005800000",
//                 "grandtotal" => "260",
//                 "noofitems" => "3",
//                 "salestime" => "04:55 PM",
//                 "createddate" => "1778066674651",
//                 "syncflag" => "1",
//                 "statuscode" => "1",
//                 "cancelflag" => "0",
//                 "modeofpayment" => "3",
//                 "mobileno" => "",
//                 "customername" => " ",
//                 "cashamount" => "0",
//                 "creditamount" => "0",
//                 "onlineamount" => "260",
//                 "onlineorders" => "",
//                 "cgstamount" => "6.19",
//                 "sgstamount" => "6.19",
//                 "sessionid" => "1",
//                 "netamount" => "260",
//                 "discper" => "0",
//                 "discamount" => "0",
//                 "subtotal" => "247.62",
//                 "takername" => "default",
//                 "onlineorderamount" => "0",
//                 "creditcustomercode" => "0",
//                 "creditcustomeramount" => "0"
//             )
//         )
//     ),

//     "salesitem" => array(
//         "JSonObject" => array(
//             array(
//                 "autonum" => "337445",
//                 "transactionno" => "196370",
//                 "voucherno" => "117",
//                 "devicecode" => "99caf25cb19a70cb123",
//                 "branchcode" => "124",
//                 "itemcode" => "1",
//                 "qty" => "2",
//                 "price" => 60,
//                 "amount" => 120,
//                 "createddate" => 1778066674651,
//                 "updateddate" => 0,
//                 "syncflag" => 1,
//                 "basicrate" => 57.14,
//                 "basicamount" => 114.29
//             ),
//             array(
//                 "autonum" => "337446",
//                 "transactionno" => "196370",
//                 "voucherno" => "117",
//                 "devicecode" => "99caf25cb19a70cb123",
//                 "branchcode" => "124",
//                 "itemcode" => "316",
//                 "qty" => "2",
//                 "price" => 55,
//                 "amount" => 110,
//                 "createddate" => 1778066678526,
//                 "updateddate" => 0,
//                 "syncflag" => 1,
//                 "basicrate" => 52.38,
//                 "basicamount" => 104.76
//             ),
//             array(
//                 "autonum" => "337447",
//                 "transactionno" => "196370",
//                 "voucherno" => "117",
//                 "devicecode" => "99caf25cb19a70cb123",
//                 "branchcode" => "124",
//                 "itemcode" => "383",
//                 "qty" => "1",
//                 "price" => 30,
//                 "amount" => 30,
//                 "createddate" => 1778066708327,
//                 "updateddate" => 0,
//                 "syncflag" => 1,
//                 "basicrate" => 28.57,
//                 "basicamount" => 28.57
//             )
//         )
//     )
// );


    // Initialize cURL
    $ch = curl_init("http://localhost:8060/api/webservice/sales/bulk");
    //  $ch = curl_init("https://mchportalapi.trio-s.com/api/webservice/sales/bulk");
    // $ch = curl_init("http://172.16.1.201:8060/api/webservice/sales/bulk");

    curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "Cookie: Path=/"
        ),
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_TIMEOUT => 60
    ));

    // Execute request
    $response = curl_exec($ch);

    // Check for cURL errors
    if (curl_errno($ch)) {
        echo json_encode(array(
            "status" => false,
            "error" => curl_error($ch)
        ));
    } else {
        // Echo API response
        header('Content-Type: application/json');
        echo $response;
    }

    curl_close($ch);
        // } else {
        //     $response["salescount"] = array();
        //     $response["SalesTransactionDetails"] = array();
        //     $response["SalesItemDetails"] = array();

        //     $response1["TransactionDetails"]=array();
        //     array_push($response["salescount"], 0);  

        //     array_push($response1["TransactionDetails"], $response);

        //     echo json_encode($response1);
        // }

} catch (Exception $e) {
    echo json_encode(array(
        "status" => false,
        "message" => $e->getMessage()
    ));
}
?>