<?php
// Disable error reporting for this page
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);




header("Content-Type: application/json");
//ini_set('error_reporting', E_ALL);

// Setting up the time zone
date_default_timezone_set('Asia/Kolkata');

// Host Name
$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();
}


function get_random_string($valid_chars, $length)
    {

        $random_string = "";
        $num_valid_chars = strlen($valid_chars);

        for ($i = 0; $i < $length; $i++) {
            $random_pick = mt_rand(1, $num_valid_chars);

            $random_char = $valid_chars[$random_pick - 1];
            $random_string .= $random_char;
        }

        return $random_string;
    } 
    
function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 5; $i++) {
            $randstring.= $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }
    
    
        
    
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        // IP from shared internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // IP passed from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        // Direct IP address
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$statement = $pdo->prepare("SELECT * FROM api_auth_details where id = 2");
$statement->execute();
$auth_data = $statement->fetch(PDO::FETCH_ASSOC);

$authgstin = $auth_data['gstin'];
$authpassword = $auth_data['password'];
$authemail = $auth_data['email'];
$authusername = $auth_data['username'];
$authip_address = $auth_data['ip_address'];
$authclient_id = $auth_data['client_id'];
$authclient_secret = $auth_data['client_secret'];
$authip_address = getUserIP() ?? '192.168.1.100'; 
// $baseUrl = "https://apisandbox.whitebooks.in";
$baseUrl = "https://api.whitebooks.in";

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 = 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);


        // 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();
}
?>
