<?php



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

// GET /admin/reportes/calificados.php
// Query params: year, month

requireAdmin();

$db = getDB();

$year = (int)($_GET['year'] ?? date('Y'));
$month = (int)($_GET['month'] ?? date('m'));

// Get distributors qualified this month
$stmt = $db->prepare('
    SELECT i.id_inver, i.nombre, i.appat, i.apmat, i.email, i.califico,
           COUNT(DISTINCT id2.id_inver) as directos_calificados
    FROM inversionista i
    LEFT JOIN inversionista id2 ON id2.idprom = i.id_inver AND id2.califico = "S"
    WHERE i.estatus_idestatus = 1
    AND MONTH(i.estampa) <= ? 
    AND YEAR(i.estampa) <= ?
    GROUP BY i.id_inver
    HAVING (
        SELECT COUNT(*) FROM transacciones t 
        WHERE t.inversionista_id_inver = i.id_inver 
        AND MONTH(t.fecha) = ? 
        AND YEAR(t.fecha) = ?
    ) > 0
    ORDER BY i.nombre
');

$stmt->execute([$month, $year, $month, $year]);
$calificados = $stmt->fetchAll();

jsonOk(['calificados' => $calificados]);
