<?php
require_once __DIR__ . '/env_loader.php';

function obtenerAccessTokenZoom()
{
    $clientId     = env('ZOOM_CLIENT_ID');
    $clientSecret = env('ZOOM_CLIENT_SECRET');

    if (!$clientId || !$clientSecret || $clientId === 'PENDIENTE') {
        error_log('[zoom_token] Credenciales Zoom no configuradas');
        return false;
    }

    $cacheFile = sys_get_temp_dir() . '/zoom_token_cache_' . md5($clientId) . '.json';
    if (file_exists($cacheFile)) {
        $cache = json_decode(file_get_contents($cacheFile), true);
        if ($cache && isset($cache['access_token'], $cache['expires_at']) && $cache['expires_at'] > time()) {
            return $cache['access_token'];
        }
    }

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => 'https://zoom.us/oauth/token',
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => http_build_query(['grant_type'=>'account_credentials','account_id'=>env('ZOOM_ACCOUNT_ID','')]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Authorization: Basic '.base64_encode($clientId.':'.$clientSecret),'Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT        => 15,
    ]);

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

    if ($httpCode !== 200) { error_log('[zoom_token] HTTP '.$httpCode.': '.$response); return false; }

    $data = json_decode($response, true);
    if (!isset($data['access_token'])) return false;

    $expiresIn = isset($data['expires_in']) ? (int)$data['expires_in'] : 3599;
    file_put_contents($cacheFile, json_encode([
        'access_token' => $data['access_token'],
        'expires_at'   => time() + $expiresIn - 120,
    ]));
    chmod($cacheFile, 0600);
    return $data['access_token'];
}
