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

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

try {
    $db = getDB();
    
    // Probar la query principal de calificados
    $mesInicio = '2026-02-01';
    $mesFin    = '2026-02-28';
    
    $stmt = $db->prepare(
        "SELECT i.id_inver, i.referencia, i.rfc,
                TRIM(CONCAT(i.nombre, ' ', i.appat, ' ', COALESCE(i.apmat,''))) AS nombre_completo,
                SUM(d.puntos) AS puntos_propios
         FROM transacciones t
         JOIN depositos d ON t.idtransacciones = d.transacciones_idtransacciones
         JOIN inversionista i ON t.inversionista_id_inver = i.id_inver
         WHERE (t.tipostr_idtipostr = 10 OR t.tipostr_idtipostr = 12)
           AND t.fechat BETWEEN :inicio AND :fin
         GROUP BY i.id_inver, i.referencia, i.rfc, i.nombre, i.appat, i.apmat
         HAVING SUM(d.puntos) >= 624
         ORDER BY SUM(d.puntos) DESC
         LIMIT 5"
    );
    $stmt->execute([':inicio' => $mesInicio, ':fin' => $mesFin]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'count' => count($rows),
        'sample' => $rows
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
}
