<?php
header("Content-Type: application/json");
include "../inc/config.php"; // Ensure this file initializes $pdo properly

try {
    // Step 1: Fetch GSTIN Mappings
    $stmt = $pdo->prepare("SELECT * FROM `tbl_client_state_code_map` GROUP BY state_code");
    $stmt->execute();
    $gstins = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($gstins as $gst) {
        $stateCode = $gst['state_code'];
        
        $currentdate = "26/05/2025"; //date('d/m/Y');
        $url = $baseUrl . '/ewaybillapi/v1.03/ewayapi/getewaybillreportbytransporterassigneddate?email=' . urlencode($authemail) . '&date=' . urlencode($currentdate) . '&stateCode=' . urlencode($stateCode);
        $curl = curl_init();
        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 => 'GET',
            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_close($curl);

        // Step 4: Decode API response
        $data = json_decode($response, true);

        echo '<pre>';
        print_r($data);
        echo '</pre>';

        // Step 5: Insert or Update Database
        if (isset($data['data']) && is_array($data['data'])) {
            $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM ewaybills WHERE ewbNo = ?");
            $insertStmt = $pdo->prepare("
                INSERT INTO ewaybills 
                (`ewbNo`, `ewbDate`, `status`, `genGstin`, `docNo`, `docDate`, `delPinCode`, `delStateCode`, `delPlace`, `validUpto`, `extendedTimes`, `rejectStatus`)
                VALUES 
                (:ewbNo, :ewbDate, :status, :genGstin, :docNo, :docDate, :delPinCode, :delStateCode, :delPlace, :validUpto, :extendedTimes, :rejectStatus)
            ");
            $updateStmt = $pdo->prepare("
                UPDATE ewaybills SET
                    ewbDate = :ewbDate,
                    status = :status,
                    genGstin = :genGstin,
                    docNo = :docNo,
                    docDate = :docDate,
                    delPinCode = :delPinCode,
                    delStateCode = :delStateCode,
                    delPlace = :delPlace,
                    validUpto = :validUpto,
                    extendedTimes = :extendedTimes,
                    rejectStatus = :rejectStatus
                WHERE ewbNo = :ewbNo
            ");

            foreach ($data['data'] as $bill) {
                $ewbNo = $bill['ewbNo'];

                $checkStmt->execute([$ewbNo]);
                $exists = $checkStmt->fetchColumn();

                $params = [
                    ':ewbNo' => $bill['ewbNo'],
                    ':ewbDate' => $bill['ewbDate'],
                    ':status' => $bill['status'],
                    ':genGstin' => $bill['genGstin'],
                    ':docNo' => $bill['docNo'],
                    ':docDate' => $bill['docDate'],
                    ':delPinCode' => $bill['delPinCode'],
                    ':delStateCode' => $bill['delStateCode'],
                    ':delPlace' => $bill['delPlace'],
                    ':validUpto' => $bill['validUpto'],
                    ':extendedTimes' => $bill['extendedTimes'],
                    ':rejectStatus' => $bill['rejectStatus'],
                ];

                if (!$exists) {
                    $insertStmt->execute($params);
                } else {
                    $updateStmt->execute($params);
                }
            }

            echo "Insert/Update completed successfully.";
        } else {
            echo "Invalid response or no data found.";
        }
    }

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
