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

$dbname = 'fmslogistics_venus_cargo';
$dbuser = 'fmslogistics_venus_cargo';
$dbpass = 'fmslogistics_venus_cargo';
define("BASE_URL", "https://venus-cargo.fms-logistics.in.net/admin-new/");


// Getting Admin url
define("ADMIN_URL", BASE_URL . "admin" . "/");

try {
	$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
	$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	ini_set('memory_limit', '2048M');
	$statement = $pdo->prepare("SET SESSION sql_mode = ''");
	$statement->execute();
}
catch( PDOException $exception ) {
	echo "Connection error :" . $exception->getMessage();
}


try {
    // Step 1: Define date range
    $start = new DateTime('2025-06-01');
    $today_date=date('Y-m-d');
    $end = new DateTime($today_date);

    // Loop from start to end date
    for ($date = $start; $date <= $end; $date->modify('+1 day')) {
        $currentdate = $date->format('d/m/Y');

        $url = $baseUrl . '/ewaybillapi/v1.03/ewayapi/getewaybillsfortransporter?email=' . urlencode($authemail) . '&date=' . urlencode($currentdate);
        $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 "<h3>Data for $currentdate</h3>";
        echo '<pre>';
        print_r($data);
        echo '</pre>';
        
        $message="get_data-praveen-success".json_encode($data);
        $stmt1 = $pdo->prepare("INSERT INTO eway_bill_auth (message) VALUES (:message)");
        $stmt1->bindParam(':message', $message);
        $stmt1->execute();

        // 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 for $currentdate completed successfully.<br>";
            
            $message="get_data-praveen-success".$data;
            $stmt1 = $pdo->prepare("INSERT INTO eway_bill_auth (message) VALUES (:message)");
            $stmt1->bindParam(':message', $message);
            $stmt1->execute();
    
        } else {
            echo "No data or invalid response for $currentdate.<br>";
            
            $message="get_data-praveen-failure".$data;
            $stmt1 = $pdo->prepare("INSERT INTO eway_bill_auth (message) VALUES (:message)");
            $stmt1->bindParam(':message', $message);
            $stmt1->execute();
        }
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
