<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
$token      = str_replace('Bearer ', '', $authHeader);
if (empty($token)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Token requerido']);
    exit;
}
$db  = getDB();
$now = date('Y-m-d H:i:s');
$stmtSess = $db->prepare("SELECT s.idusuarios_sist FROM admin_sessions s WHERE s.token = ? AND s.expira > ? LIMIT 1");
$stmtSess->execute([$token, $now]);
if (!$stmtSess->fetch()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Sesión inválida']);
    exit;
}

// Test simple query
try {
    $r = $db->query("SELECT COUNT(*) as total FROM transacciones WHERE tipostr_idtipostr IN (6,10,11) AND fechat >= '2026-03-01'")->fetch(PDO::FETCH_ASSOC);
    echo json_encode(['success' => true, 'total_trans' => $r['total']]);
} catch(Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
