<?php

require __DIR__ . '/vendor/autoload.php';

use Dotenv\Dotenv;

date_default_timezone_set('America/Montreal');

$baseDir    = __DIR__;
$tokenFile  = $baseDir . "/token_prod.json";
$logFile    = $baseDir . "/logs.json";

// ---------------------------------------------------------
// LOG
// ---------------------------------------------------------
function logMsg($msg)
{
    global $logFile;
    file_put_contents($logFile, date("Y-m-d H:i:s") . " | $msg\n", FILE_APPEND);
}

function fail($msg)
{
    logMsg("ERROR: $msg");
    exit(1);
}

// ---------------------------------------------------------
// LOAD ENV
// ---------------------------------------------------------
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$clientId     = $_ENV['SF_CLIENT_ID'];
$clientSecret = $_ENV['SF_CLIENT_SECRET'];
$tokenUrl     = $_ENV['SF_TOKEN_URL'];
$refreshToken = $_ENV['SF_REFRESH_TOKEN'];

// ---------------------------------------------------------
// TOKEN
// ---------------------------------------------------------
function getToken()
{
    global $tokenFile, $clientId, $clientSecret, $refreshToken, $tokenUrl;

    if (file_exists($tokenFile)) {
        $data = json_decode(file_get_contents($tokenFile), true);
        if ($data && time() < ($data['expires_at'] ?? 0)) {
            logMsg("♻️ Token valide");
            return $data;
        }
    }

    logMsg("🔄 Refresh token");

    $payload = [
        "grant_type"    => "refresh_token",
        "client_id"     => $clientId,
        "client_secret" => $clientSecret,
        "refresh_token" => $refreshToken
    ];

    $ch = curl_init($tokenUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query($payload),
        CURLOPT_RETURNTRANSFER => true
    ]);

    $res = curl_exec($ch);

    if ($res === false) fail(curl_error($ch));

    $data = json_decode($res, true);

    if (!isset($data["access_token"])) {
        fail("OAuth error: " . $res);
    }

    $tokenData = [
        "access_token" => $data["access_token"],
        "instance_url" => $data["instance_url"],
        "expires_at"   => time() + 7000
    ];

    file_put_contents($tokenFile, json_encode($tokenData, JSON_PRETTY_PRINT));

    return $tokenData;
}

$token       = getToken();
$accessToken = $token["access_token"];
$instanceUrl = $token["instance_url"];

// ---------------------------------------------------------
// DESCRIBE
// ---------------------------------------------------------
$url = $instanceUrl . "/services/data/v62.0/sobjects/Asset/describe/";

logMsg("🌐 Describe URL: " . $url);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER     => ["Authorization: Bearer $accessToken"],
    CURLOPT_RETURNTRANSFER => true
]);

$response = curl_exec($ch);

if ($response === false) {
    fail(curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

logMsg("📡 HTTP code: " . $httpCode);

$data   = json_decode($response, true);
$fields = array_column($data['fields'] ?? [], 'name');

logMsg("📋 Champs disponibles (" . count($fields) . ") : " . implode(', ', $fields));