<?php
// auth.php

// API endpoint
$apiUrl = "https://einvapisandbox.irp5.in/irp5/irpauthapi/v1.0/apiAuth";

// Credentials and constants
$clientId = "6eb451cd-e858-4152-9398-690dd726ee3c";
$clientSecret = "taxassist";
$pan = "AZNPA2013P";
$passwordPlain = "Ana@8123030275";
$username = "gvaanand";

// Fixed appKey as provided
$appKey = "bzU7XCAAEFhLE0YwbzpTSgI6ODExDlZTdSIHA0ojcmA=";

// Token storage file
$tokenFile = __DIR__ . '/token.json';

// Function to get stored token if valid
function getStoredToken($tokenFile) {
    if (!file_exists($tokenFile)) {
        return null;
    }
    $tokenData = json_decode(file_get_contents($tokenFile), true);
    if (!$tokenData) {
        return null;
    }
    // Check expiry (assuming TokenExpiry is a timestamp)
    if (time() > strtotime($tokenData['TokenExpiry'])) {
        return null;
    }
    return $tokenData['AuthToken'];
}

// Function to save token
function saveToken($tokenFile, $tokenData) {
    file_put_contents($tokenFile, json_encode($tokenData));
}

// Function to authenticate and get new token
function authenticate($apiUrl, $clientId, $clientSecret, $pan, $username, $passwordPlain, $appKey) {
    $headers = [
        "Content-Type: application/json",
        "Client-Id: $clientId",
        "Client-Secret: $clientSecret",
        "PAN: $pan"
    ];
    $payload = [
        "UserName" => $username,
        "Password" => $passwordPlain,
        "AppKey" => $appKey,
        "ForceRefreshAccessToken" => true
    ];
// Debug: Output headers and payload for auth request
echo "Request Headers for auth:\n";
print_r($headers);
echo "Request Payload for auth:\n";
print_r($payload);

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($result === false || $httpCode != 200) {
        die("Failed to get Auth Token. cURL Error: " . curl_error($ch) . " HTTP Code: $httpCode");
    }
    $response = json_decode($result, true);
    curl_close($ch);
    if ($response && isset($response['Status']) && $response['Status'] == 1) {
        saveToken($GLOBALS['tokenFile'], $response['Data']);
        return $response['Data']['AuthToken'];
    } else {
        die("Authentication failed.<br>Response: " . htmlspecialchars($result));
    }
}

// Function to make API request with token
function makeApiRequest($url, $token, $payload) {
    $headers = [
        "Content-Type: application/json",
        "Authorization: Bearer $token"
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($response === false || $httpCode != 200) {
        die("API request failed. cURL Error: " . curl_error($ch) . " HTTP Code: $httpCode");
    }
    curl_close($ch);
    return $response;
}

// Main execution
$authToken = getStoredToken($tokenFile);
if (!$authToken) {
    $authToken = authenticate($apiUrl, $clientId, $clientSecret, $pan, $username, $passwordPlain, $appKey);
}

// Example API request payload (encrypted if needed)
$requestPayload = [
    // Your request data here
];

// Make API request
$response = makeApiRequest("https://einvapisandbox.irp5.in/irp5/irpauthapi/v1.0/apiAuth", $authToken, $requestPayload);

// Output response
echo "API Response: " . $response;
error Request Headers for auth: Array ( [0] => Content-Type: application/json [1] => Client-Id: 6eb451cd-e858-4152-9398-690dd726ee3c [2] => Client-Secret: taxassist [3] => PAN: AZNPA2013P ) Request Payload for auth: Array ( [UserName] => gvaanand [Password] => Ana@8123030275 [AppKey] => bzU7XCAAEFhLE0YwbzpTSgI6ODExDlZTdSIHA0ojcmA= [ForceRefreshAccessToken] => 1 ) Authentication failed.
Response: {"Status":0,"Data":null,"ErrorDetails":[{"ErrorCode":"1010","ErrorMessage":"Invalid Client-ID/Client-Secret."}],"InfoDtls":null}