<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../../config.php';

// Mostrar todos los headers recibidos
$allHeaders = array();
foreach ($_SERVER as $k => $v) {
    if (strpos($k, 'HTTP_') === 0) {
        $allHeaders[$k] = $v;
    }
}
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
    $allHeaders['REDIRECT_HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
}

// Extraer token manualmente
$token = _extractBearerToken();

// Buscar en admin_sessions
$row = null;
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
        DB_USER, DB_PASS,
        array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
    );
    $stmt = $pdo->prepare("SELECT token, db_remote, expira FROM admin_sessions WHERE token = ? LIMIT 1");
    $stmt->execute(array($token));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $row = array('error' => $e->getMessage());
}

// Intentar conectar a BD remota directamente
$remoteTest = null;
try {
    $pdo2 = new PDO(
        'mysql:host=' . DB_REMOTE_HOST . ';dbname=' . DB_REMOTE_NAME . ';charset=utf8mb4',
        DB_REMOTE_USER, DB_REMOTE_PASS,
        array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 5)
    );
    $r = $pdo2->query("SELECT COUNT(*) as cnt FROM transacciones LIMIT 1")->fetch();
    $remoteTest = array('ok' => true, 'count' => $r['cnt']);
} catch (Exception $e) {
    $remoteTest = array('ok' => false, 'error' => $e->getMessage());
}

echo json_encode(array(
    'token_extracted'  => $token ? substr($token, 0, 16) . '...' : 'NONE',
    'server_headers'   => $allHeaders,
    'session_in_db'    => $row,
    'remote_db_test'   => $remoteTest,
    'db_remote_flag'   => _dbRemoteFromSession(),
), JSON_PRETTY_PRINT);
