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

require_once '/mnt/www-live/TechOdyssey_Designs_Dashboard/src/envLoader.php';
loadEnv(__DIR__ . '/../../.env');

// Get API credentials from the environment
$client_id = $_ENV['P2G_CLIENT_ID'];
$client_secret = $_ENV['P2G_CLIENT_SECRET'];
$auth_url = $_ENV['P2G_API_AUTH_URL'];
$prepay_balance_url = 'https://www.parcel2go.com/api/me/prepay/balance';

// Function to get the API token
function getApiToken($client_id, $client_secret, $auth_url) {
    $ch = curl_init($auth_url);

    $data = http_build_query([
        'grant_type' => 'client_credentials',
        'scope' => 'public-api',
        'client_id' => $client_id,
        'client_secret' => $client_secret,
    ]);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: */*',
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);
    return $result['access_token'] ?? null;
}

// Function to fetch prepay balance
function getPrepayBalance($token, $prepay_balance_url) {
    $ch = curl_init($prepay_balance_url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $token",
        'Accept: application/json',
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}

// Main logic
$token = getApiToken($client_id, $client_secret, $auth_url);

if ($token) {
    $balance_info = getPrepayBalance($token, $prepay_balance_url);

    if ($balance_info) {
        echo json_encode(['success' => true, 'data' => $balance_info]);
    } else {
        http_response_code(402);
        echo json_encode(['success' => false, 'error' => 'Failed to fetch prepay balance.']);
    }
} else {
    http_response_code(402);
    echo json_encode(['success' => false, 'error' => 'Failed to authenticate.']);
}
?>
