<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

error_log("Cron started at " . date('Y-m-d H:i:s'));

// 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)
    {

        // start with an empty random string
        $random_string = "";

        // count the number of chars in the valid chars string so we know how many choices we have
        $num_valid_chars = strlen($valid_chars);

        // repeat the steps until we've created a string of the right length
        for ($i = 0; $i < $length; $i++) {
            // pick a random number from 1 up to the number of valid chars
            $random_pick = mt_rand(1, $num_valid_chars);

            // take the random character out of the string of valid chars
            // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
            $random_char = $valid_chars[$random_pick - 1];

            // add the randomly-chosen char onto the end of our string so far
            $random_string .= $random_char;
        }

        // return our finished random string
        return $random_string;
    } // end of get_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 {
    
    // $date=date('d/m/Y');
    $date='08/06/2025';
    $date1=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 e.validUpto != ''
                AND s.id NOT IN (5, 7)
                AND e.ewbNo IN (
               201975787479,271975958625,251976088912,201976713080,271976714141,261976739240,211976928070,201976931088,251976947709,201976950926,261976966525,221976976605,261976984093,261976991022,241976993105,251976993418,271977039379,261977061296,251977087736,241977090393,211977100325,271977099766,241977100845,271977103153,271977103252,231977107418,231977113457,241977123433,211977131846,221977169569,291977180433,271977181063,211977184275,251977188282,261977191832,201977203605,281977247818,241977267252,231977273313,251977276066,291977286210,261977288923,251977291001,201977293383,291977299023,261977304005,261977320410,231977325250,281977329174,251977334153,261977336037,221977338862,271977339026,261977342146,221977347280,251977347825,261977349118,201977356334,261977357450,291977363597,251977365236,241977374565,271977374647,241977380588,251977381357,211977386318,201977386414,291977389212,211977391099,201977392523,281977393872,201977394532,241977397603,201977399975,271977401002,261977358958,261977684879,251977788826,231977890211,281977915928,221977918028,251978009854,231978013958,291978023702,281978123195,211978123404,261978126086,291978173812,291978202385,211978027078,291978027241,211978040666,201978175613,231978224183,291978313335,211978359140,211978377452,241978402849,211978410393,281978444926,251978447504,221978452260,271978469153,221978474053,211978476337,291978490430,271978497477,251978502168,281978506028,221978511532,261978512298,231978533104,231978548546,281978551255,241978561236,261978565458,221978568228,231978602839,211978611404,281978612846,291978618470,261978618947,271978629137,201978631467,291978648732,221978649507,201978651746,291978651855,231978652425,271978652922,261978654347,211978654508,281978654567,261978655098,291978655183,221978655434,221978655773,231978655875,221978666593,291978666664,231978667461,291978667740,261978667910,281978669251,201978670837,211978670814,201978672903
)

            HAVING 
                vehicle_number IS NOT NULL");*/
                
        $stmt1 = $pdo->prepare("SELECT 
    e.validUpto,
    e.ewbDate,
    e.ewbNo	
FROM pickup_entry
LEFT JOIN tbl_user ON pickup_entry.client_id = tbl_user.id 
LEFT JOIN tbl_branch ON pickup_entry.branch_id = tbl_branch.id 
LEFT JOIN tbl_status ON tbl_status.id = pickup_entry.status_code 
LEFT JOIN tbl_client_new ON tbl_client_new.id = pickup_entry.new_client_id
LEFT JOIN ewaybills e ON e.ewbNo = pickup_entry.ewaybill  
WHERE 
    pickup_entry.date_added BETWEEN DATE('2025-06-01') AND DATE($date1)
    AND pickup_entry.status IN ('OUT FOR DELIVERY', 'MANIFEST')
    AND DATE(STR_TO_DATE(e.validUpto, '%d/%m/%Y')) = CURDATE() - INTERVAL 1 DAY
    AND e.ewbDate IS NOT NULL");   
        $stmt1->execute(); 
   $ewbNos = array_column($arrayData1, 'ewbNo');
$ew_no = implode(', ', $ewbNos);
       if($arrayData1){         
                  
      $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 
                e.ewbNo IN ($ew_no) HAVING vehicle_number IS NOT NULL;");          
                
                
                
                
                
                

                
                
                
                
    $stmt->execute(); 
    
    $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
    ]);
    $data=json_encode([
        'status_cd' => count($failure_ids) > 0 ? '0' : '1',
        'success_ids' => $success_ids,
        'failure_ids' => $failure_ids,
        'errors' => $errors
    ]);
    $message="extend-praveen-success".$data;
    $stmt2 = $pdo->prepare("INSERT INTO eway_bill_auth (message) VALUES (:message)");
    $stmt2->bindParam(':message', $message);
    $stmt2->execute();
    
    error_log(json_encode([
        'status_cd' => count($failure_ids) > 0 ? '0' : '1',
        'success_ids' => $success_ids,
        'failure_ids' => $failure_ids,
        'errors' => $errors
    ]));



}
catch( PDOException $exception ) {
	echo "Connection error :" . $exception->getMessage();
}

?>