<?php

include('../inc/config.php');

 $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);
print_r($response_data);
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!";
} else {
    // echo "Authentication failed. Status code: " . $response_data['status_cd'];
    // echo "\n" . $response_data['status_desc']; // Print additional status description for failure
}

?>
