<?php

/**
 * FetchContacts.php
 * -----------------
 * 1. Auth → refresh token si expiré (même .env que FinDeVisite.php)
 * 2. Fetch contacts (ID, names, email, phone)
 * 3. Grouping par Account
 * 4. Transformation en structure Client + SecondaryClients
 */

// ---------------------------------------------------------------------
// DEBUG
// ---------------------------------------------------------------------
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

if (!function_exists('curl_init')) {
    die("❌ PHP cURL n'est pas activé");
}

// ---------------------------------------------------------------------
// LOAD ENV (même .env que FinDeVisite.php)
// ---------------------------------------------------------------------
require __DIR__ . '/vendor/autoload.php';

use Dotenv\Dotenv;

$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'];
$instanceUrl  = $_ENV['SF_INSTANCE_URL'];
$tokenFile    = __DIR__ . '/token.json';   // partagé avec FinDeVisite
$logFile      = __DIR__ . '/contacts.log';
$outputFile   = __DIR__ . '/contacts.json';
$apiVersion   = 'v62.0';

// ---------------------------------------------------------------------
// LOG
// ---------------------------------------------------------------------
function logMsg(string $msg): void
{
    global $logFile;
    @file_put_contents(
        $logFile,
        json_encode([
            "timestamp" => date("Y-m-d H:i:s"),
            "message"   => $msg
        ], JSON_PRETTY_PRINT) . "\n",
        FILE_APPEND
    );
}

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

    // Réutilise le token.json partagé avec FinDeVisite si encore valide
    if (file_exists($tokenFile)) {
        $saved = json_decode(file_get_contents($tokenFile), true);
        if (!empty($saved["access_token"]) && time() < ($saved["expires_at"] ?? 0)) {
            logMsg("♻️ Token valide (cache)");
            return $saved["access_token"];
        }
    }

    logMsg("🔄 Refresh token");

    $ch = curl_init($tokenUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query([
            "grant_type"    => "refresh_token",
            "client_id"     => $clientId,
            "client_secret" => $clientSecret,
            "refresh_token" => $refreshToken,
        ]),
        CURLOPT_RETURNTRANSFER => true,
    ]);

    $res = curl_exec($ch);
    if ($res === false) die("❌ Token CURL error: " . curl_error($ch));
    curl_close($ch);

    $tok = json_decode($res, true);
    if (empty($tok["access_token"])) {
        die("❌ Refresh token échoué — le refresh_token est peut-être révoqué. Réponse: $res");
    }

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

    file_put_contents($tokenFile, json_encode($tokenData, JSON_PRETTY_PRINT));
    logMsg("✅ Nouveau token obtenu");

    return $tokenData["access_token"];
}

/* ============================================================================
   FETCH CONTACTS
   ============================================================================ */
$accessToken = getAccessToken();

$fields = implode(", ", [
    "Id",
    "FirstName",
    "LastName",
    "Email",
    "Phone",
    "MobilePhone",
    "AccountId",
    "Account.Name",
    "Account.Building__c"
]);

$soql = urlencode("SELECT $fields FROM Contact");
$url  = "$instanceUrl/services/data/v61.0/query/?q=$soql";

$records = [];
$next = $url;

/* ============================================================================
   PAGINATION
   ============================================================================ */
while ($next) {

    $ch = curl_init($next);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    if ($response === false) die("CURL: " . curl_error($ch));
    curl_close($ch);

    $json = json_decode($response, true);

    if (isset($json["records"])) {
        $records = array_merge($records, $json["records"]);
    }

    $next = isset($json["nextRecordsUrl"])
        ? $instanceUrl . $json["nextRecordsUrl"]
        : null;
}

logMsg("📥 Contacts trouvés : " . count($records));

/* ============================================================================
   GROUPING BY ACCOUNT (TON OUTPUT ACTUEL)
   ============================================================================ */
$accounts = [];

foreach ($records as $c) {

    $accId = $c["AccountId"] ?? null;
    if (!$accId) continue;

    if (!isset($accounts[$accId])) {
        $accounts[$accId] = [
            "AccountId"   => $accId,
            "AccountName" => $c["Account"]["Name"] ?? "",
            "Building"    => $c["Account"]["Building__c"] ?? "",
            "Contacts"    => []
        ];
    }

    $phone = $c["MobilePhone"] ?: ($c["Phone"] ?: "");

    $accounts[$accId]["Contacts"][] = [
        "Id"        => $c["Id"],
        "FirstName" => $c["FirstName"] ?? "",
        "LastName"  => $c["LastName"] ?? "",
        "Email"     => $c["Email"] ?? "",
        "Phone"     => $phone
    ];
}

/* ============================================================================
   TRANSFORM → CLIENT + SECONDARYCLIENTS
   ============================================================================ */
$output = [];

foreach ($accounts as $acc) {

    // Si aucun contact → skip
    if (count($acc["Contacts"]) === 0) continue;

    // Premier contact = Client principal
    $main = $acc["Contacts"][0];

    // Tous les autres = SecondaryClients (ID only)
    $secondary = [];

    for ($i = 1; $i < count($acc["Contacts"]); $i++) {
        $secondary[] = $acc["Contacts"][$i]["Id"];
    }

    $output[] = [
        "Name" => $acc["AccountId"],

        "Client" => [
            "FirstName" => $main["FirstName"],
            "LastName"  => $main["LastName"],
            "Email"     => $main["Email"],
            "Phone"     => $main["Phone"]
        ],

        "SecondaryClients" => $secondary
    ];
}

/* ============================================================================
   SAVE
   ============================================================================ */
file_put_contents(
    $outputFile,
    json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
);

logMsg("✔ contacts.json transformé et généré avec succès");

echo "✔ contacts.json transformé généré\n";
