<?php
session_start();
header('Content-Type: application/json');

// Permitir acceso a subdistribuidor o adminTi
if (!isset($_SESSION['attuid']) || !in_array($_SESSION['rol'] ?? '', ['subdistribuidor', 'adminTi'])) {
    echo json_encode(['success' => false, 'data' => [], 'total' => 0]);
    exit;
}

require_once(__DIR__ . '/../db/conexion.php');

// Filtros desde GET
$busqueda = $_GET['busqueda'] ?? '';
$estado   = $_GET['estado'] ?? '';
$page     = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit    = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$offset   = ($page - 1) * $limit;

// Obtener el ATTUID del subdistribuidor actual
$attuid = $_SESSION['attuid'] ?? '';

// Consulta base filtrada por attuid
$sql = "SELECT id, folio, nombre, apellido_paterno, apellido_materno, curp, nss, rfc, telefono, ubicacion, estatus_actual 
        FROM aspirantes 
        WHERE attuid = ?";
$params = [$attuid];
$types = "s";

// Filtro de búsqueda
if ($busqueda !== '') {
    $sql .= " AND (nombre LIKE ? OR apellido_paterno LIKE ? OR apellido_materno LIKE ? OR curp LIKE ? OR folio LIKE ?)";
    $searchParam = "%$busqueda%";
    $params = array_merge($params, array_fill(0, 5, $searchParam));
    $types .= str_repeat("s", 5);
}

// Filtro de estado
if ($estado !== '') {
    $sql .= " AND estatus_actual = ?";
    $params[] = $estado;
    $types .= "s";
}

// Conteo total para paginación
$countSql = "SELECT COUNT(*) as total FROM ($sql) as tmp";
$countStmt = $conn->prepare($countSql);
if ($types) $countStmt->bind_param($types, ...$params);
$countStmt->execute();
$totalRes = $countStmt->get_result();
$total = $totalRes->fetch_assoc()['total'] ?? 0;
$countStmt->close();

// Paginación
$sql .= " ORDER BY fecha_registro DESC LIMIT ?, ?";
$params[] = $offset;
$params[] = $limit;
$types .= "ii";

// Consulta final
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    $row['nombre_completo'] = "{$row['nombre']} {$row['apellido_paterno']} {$row['apellido_materno']}";
    $row['estado'] = $row['estatus_actual'];
    $data[] = $row;
}

echo json_encode(['success' => true, 'data' => $data, 'total' => $total]);
?>
