<?php
// Disable error reporting for this page
// ini_set('display_errors', 0);
// ini_set('display_startup_errors', 0);
// error_reporting(0);
//ini_set('error_reporting', E_ALL);
error_log('praveen cron running');
// 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";




 $url = $baseUrl . "/ewaybillapi/v1.03/authenticate?email=" . $authemail . '&username=' . $authusername . '&password=' . $authpassword;
$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(
    'ip_address: ' . $authip_address,
    'client_id: ' . $authclient_id,
    'client_secret: ' . $authclient_secret,
    'gstin: ' . $authgstin,
    'Accept: application/json'
  ),
));

// Execute cURL request and get the response
$response = curl_exec($curl);

// Close cURL session
curl_close($curl);

// Decode the response JSON into an associative array
$response_data = json_decode($response, true);
error_log(json_encode($response));

// Validate if the status_cd is 1 and store token if available
if (isset($response_data['status_cd']) && $response_data['status_cd'] == '1') {
    // echo "Authentication successful!";

    // Assuming the token is in the response data
    $token = true; 
    // Adjust this according to the actual response structure

    // Prepare the SQL query to update the token (no need to reconnect to the DB, use the existing PDO connection)
    $stmt = $pdo->prepare("UPDATE api_auth_details 
                           SET token = :token 
                           WHERE gstin = :gstin");

    // Bind the parameters
    $stmt->bindParam(':token', $token);
    $stmt->bindParam(':gstin', $gstin);

    // Execute the statement to update the database
    $stmt->execute();
    echo "Token has been updated successfully!";
    
    $message="auth-success";
    $stmt1 = $pdo->prepare("INSERT INTO eway_bill_auth (message) VALUES (:message)");
    $stmt1->bindParam(':message', $message);
    $stmt1->execute();

    
    
} else {
    // echo "Authentication failed. Status code: " . $response_data['status_cd'];
    // echo "\n" . $response_data['status_desc']; // Print additional status description for failure
}
// error_log("auth run sucessfully".date('Y-m-d H:i:s'));
?>
