<?php
// Centraliza autenticación Google: Service Account (primario) + OAuth refresh token (fallback)
// FASE 2: usa helpers/http.php + helpers/json.php para retry, SSL on, manejo errores robusto.

require_once __DIR__ . '/../helpers/http.php';
require_once __DIR__ . '/../helpers/json.php';

function dm_google_access_token(string $scope = 'https://www.googleapis.com/auth/adwords', int $client_id = 0): string {
    $cache_file = sys_get_temp_dir() . '/dm_goog_' . md5($scope . ':' . $client_id) . '.token';
    if (file_exists($cache_file)) {
        $cached = dm_json_decode(@file_get_contents($cache_file), ['silent'=>true]);
        if (is_array($cached) && ($cached['exp'] ?? 0) > time() + 60) return (string)($cached['token'] ?? '');
    }
    $token = '';
    // SA solo para Google Ads — GSC y otros scopes usan OAuth directamente
    $sa_path = defined('GOOGLE_SERVICE_ACCOUNT_JSON') ? GOOGLE_SERVICE_ACCOUNT_JSON : '';
    if ($sa_path && file_exists($sa_path) && strpos($scope, 'adwords') !== false) {
        $token = _dm_sa_token($sa_path, $scope);
    }
    if (!$token) {
        // Per-client token first (SaaS multi-tenant), fallback to global admin token
        $r = '';
        if ($client_id > 0 && function_exists('dm_get_credential')) {
            $r = dm_get_credential($client_id, 'google', 'refresh_token') ?: '';
        }
        if (!$r) {
            if (function_exists('dm_get_global_secret')) {
                $r = dm_get_global_secret('GOOGLE_REFRESH_TOKEN', 'GOOGLE_REFRESH_TOKEN');
            } else {
                $r = defined('GOOGLE_REFRESH_TOKEN') ? GOOGLE_REFRESH_TOKEN : '';
            }
        }
        $ci = defined('GOOGLE_CLIENT_ID')     ? GOOGLE_CLIENT_ID     : '';
        $cs = defined('GOOGLE_CLIENT_SECRET') ? GOOGLE_CLIENT_SECRET : '';
        if ($r && $ci && $cs) {
            $res = dm_http_post_form('https://oauth2.googleapis.com/token', [
                'client_id'     => $ci,
                'client_secret' => $cs,
                'refresh_token' => $r,
                'grant_type'    => 'refresh_token',
            ], [], ['timeout'=>10, 'retries'=>2]);
            if ($res['ok']) {
                $token = (string)dm_json_path($res['data'], 'access_token', '');
            } else {
                error_log("[google-auth] OAuth refresh failed: {$res['error_code']} — {$res['error']}");
            }
        }
    }
    if ($token) {
        @file_put_contents($cache_file, dm_json_encode(['token' => $token, 'exp' => time() + 3500]));
    }
    return $token;
}

function _dm_sa_token(string $json_path, string $scope): string {
    $key_raw = @file_get_contents($json_path);
    $key = dm_json_decode($key_raw, ['context'=>'google-auth.sa_load']);
    if (!is_array($key) || ($key['type'] ?? '') !== 'service_account') return '';
    $b64 = fn($s) => rtrim(strtr(base64_encode($s), '+/', '-_'), '=');
    $now     = time();
    $header  = $b64(dm_json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
    $payload = $b64(dm_json_encode([
        'iss'   => $key['client_email'],
        'scope' => $scope,
        'aud'   => 'https://oauth2.googleapis.com/token',
        'exp'   => $now + 3600,
        'iat'   => $now,
    ]));
    $input = $header . '.' . $payload;
    if (!openssl_sign($input, $sig, $key['private_key'], 'SHA256')) return '';
    $jwt = $input . '.' . $b64($sig);
    $res = dm_http_post_form('https://oauth2.googleapis.com/token', [
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion'  => $jwt,
    ], [], ['timeout'=>10, 'retries'=>2]);
    if (!$res['ok']) {
        error_log("[google-auth] SA token failed: {$res['error_code']} — {$res['error']}");
        return '';
    }
    return (string)dm_json_path($res['data'], 'access_token', '');
}
