<?php
ob_start();
session_start();
header("Content-Type: application/json");
include "inc/config.php";

$input = file_get_contents("php://input");
$data = json_decode($input, true);

$date= date('Y-m-d');

        $stmt = $pdo->prepare("
                SELECT 
                br.name AS branch_name,
                br.state_code,
                pk.shipper_name,
                pk.shipper_pincode,
                e.ewbNo,
                e.delPinCode,
                e.delStateCode,
                s.name AS status_name,
                e.validUpto,
                (
                    SELECT m.vehicle_no
                    FROM manifest m
                    WHERE FIND_IN_SET(pk.id, m.ids)
                    ORDER BY m.id DESC
                    LIMIT 1
                ) AS vehicle_number
            FROM 
                ewaybills e
            LEFT JOIN 
                pickup_entry pk ON pk.ewaybill = e.ewbNo
            LEFT JOIN 
                tbl_branch br ON br.id = pk.branch_id
            LEFT JOIN 
                tbl_status s ON s.id = pk.status_code
            WHERE 
                pk.shipper_name IS NOT NULL
                AND s.id NOT IN (5, 7)
                AND e.ewbNo='201966209052'
            HAVING 
                vehicle_number IS NOT NULL LIMIT 1");
$stmt->execute(); 
//   SELECT       --  AND DATE(STR_TO_DATE(e.validUpto, '%d/%m/%Y %h:%i:%s %p')) = '$date'
//     br.pincode, 
//     br.name AS branchname, 
//     br.state_code,
//     pk.shipper_name,
//     pk.shipper_pincode, 
//     e.ewbNo, 
//     e.delPinCode, 
//     e.delStateCode,
//     s.name AS status_name,
//     e.validUpto AS expairedin,
//     (
//         SELECT m.vehicle_no 
//         FROM manifest m 
//         WHERE FIND_IN_SET(pk.id, m.ids) 
//         ORDER BY m.id DESC 
//         LIMIT 1
//     ) AS vehicle_number
// FROM ewaybills e
// LEFT JOIN pickup_entry pk ON pk.ewaybill = e.ewbNo 
// LEFT JOIN tbl_branch br ON br.id = pk.branch_id
// LEFT JOIN tbl_status s ON s.id = pk.status_code
// WHERE 
//     pk.shipper_name IS NOT NULL 
//     AND s.id NOT IN (5, 7)
//     AND STR_TO_DATE(e.validUpto, '%d/%m/%Y %r') <= NOW();
$arrayData = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Result containers
$success_ids = [];
$failure_ids = [];
$errors = [];

foreach ($arrayData as $ewbRow) {
    if (empty($ewbRow['ewbNo'])) continue;

    $fromPlace = $ewbRow['branch_name'];
    $fromState = $ewbRow['state_code'];
    $ewbNo = $ewbRow['ewbNo'];
    $veh = $ewbRow['vehicle_number'];
    $transMode = 1;
    $extnRsnCode = 4;
    $extnRemarks = 'Transshipment';
    $fromPincode = $ewbRow['shipper_pincode'];
    $consignmentStatus = 'M';

    $curl = curl_init();
    $url = $baseUrl . "/ewaybillapi/v1.03/ewayapi/extendvalidity?email=" . urlencode($authemail);
    error_log("cURL URL: " . $url);
    curl_setopt_array($curl, array(
        CURLOPT_URL => $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 =>'{
          "ewbNo": '.$ewbNo.',
          "vehicleNo": "'.$veh.'",
          "fromPlace": "'.$fromPlace.'",
          "fromState": '.$fromState.',
          "remainingDistance": 0,
          "transMode": "1",
          "extnRsnCode": '.$extnRsnCode.',
          "extnRemarks": "'.$reasons.'",
          "fromPincode": '.$fromPincode.',
          "consignmentStatus": "'.$consignmentStatus.'",
          "transitType": "",
          "addressLine1": "",
          "addressLine2": "",
          "addressLine3": ""
        }',
        // CURLOPT_POSTFIELDS => json_encode([

            
            
            
        /*{
  "ewbNo": 101011455738,
  "vehicleNo": "ABC1234",
  "fromPlace": "FRAZER TOWN",
  "fromState": 29,
  "remainingDistance": 0,
  "transDocNo": "12",
  "transDocDate": "11/05/2025",
  "transMode": "1",
  "extnRsnCode": 1,
  "extnRemarks": "Nature Calamity",
  "fromPincode": 560001,
  "consignmentStatus": "M",
  "transitType": "",
  "addressLine1": "",
  "addressLine2": "",
  
  
              "ewbNo" => $ewbNo,
            "vehicleNo" => "'.$veh.'",
            "fromPlace" =>  "'.$fromPlace.'",
            "fromState" =>   $fromState,
            "remainingDistance" => 0,
            "transMode" =>  "'.$transMode.'",
            "extnRsnCode" => $extnRsnCode.'",
            "extnRemarks" =>  "'.$extnRemarks.'",
            "fromPincode" =>   $fromPincode,
            "consignmentStatus" =>  "'.$consignmentStatus
  
  
  */    
            
        // ]),  
        CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json",
            "Accept: application/json",
            "ip_address: $authip_address",
            "client_id: $authclient_id",
            "client_secret: $authclient_secret",
            "gstin: $authgstin"
        ),
    ));

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

    if ($curl_error) {
        $failure_ids[] = $ewbNo;
        $errors[] = "Eway Bill No: $ewbNo failed: cURL Error - $curl_error";
        continue;
    }

    $resp = json_decode($response, true);

    if (isset($resp['status_cd']) && $resp['status_cd'] == '1') {
        $success_ids[] = $ewbNo;

        $ewayBillNo = $resp['data']['ewayBillNo'];
        $validUpto = $resp['data']['validUpto'];

        $updateStmt = $pdo->prepare("UPDATE ewaybills SET validUpto = :validUpto WHERE ewbNo = :ewayBillNo");
        $updateStmt->execute([
            ':validUpto' => $validUpto,
            ':ewayBillNo' => $ewayBillNo
        ]);
    } else {
        $failure_ids[] = $ewbNo;
        $errordetails = 'Unknown error';

        // Error parsing
        $errorMessage = $resp['error']['message'] ?? '';
        $msg = json_decode($errorMessage, true);

        if (json_last_error() === JSON_ERROR_NONE && isset($msg['errorCodes'])) {
            $codes = trim($msg['errorCodes'], ", ");
            $codeArray = explode(",", $codes);
            $Err = [];

            foreach ($codeArray as $code) {
                $stmt = $pdo->prepare("SELECT errorDesc FROM api_error WHERE errorCode = :code");
                $stmt->execute(['code' => trim($code)]);
                $ErrData = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($ErrData && isset($ErrData['errorDesc'])) {
                    $Err[] = $ErrData['errorDesc'];
                }
            }

            if (!empty($Err)) {
                $errordetails = implode(", ", $Err);
            } else {
                $errordetails = 'Error code(s) not found in api_error table';
            }

        } else {
            // If not JSON or no errorCodes
            $errordetails = is_string($errorMessage) ? $errorMessage : 'Unknown API error format';
        }

        // Log error to DB
        $insertStmt = $pdo->prepare("
            INSERT INTO api_ewb_extend_logs (ewbNo, errorDetails) 
            VALUES (:ewbNo, :errorDetails)
        ");
        $insertStmt->execute([
            'ewbNo' => $ewbNo,
            'errorDetails' => $errordetails
        ]);

        $errors[] = "Eway Bill No: $ewbNo failed: $errordetails";
    }
}

// Final output
echo json_encode([
    'status_cd' => count($failure_ids) > 0 ? '0' : '1',
    'success_ids' => $success_ids,
    'failure_ids' => $failure_ids,
    'errors' => $errors
]);


error_log(json_encode([
        'status_cd' => count($failure_ids) > 0 ? '0' : '1',
        'success_ids' => $success_ids,
        'failure_ids' => $failure_ids,
        'errors' => $errors
    ]));
