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

require_once __DIR__ . '/../db/conexion.php';
require_once __DIR__ . '/../utils/normalizar_texto.php';

if (!isset($_SESSION['attuid'])) {
    echo json_encode(['success' => false, 'message' => 'Sesión no válida.', 'items' => []]);
    exit;
}

$term = trim($_GET['q'] ?? '');
$term = limpiarTexto($term);

if ($term === '' || strlen($term) < 2) {
    echo json_encode(['success' => true, 'items' => []]);
    exit;
}

$sql = "SELECT
            CURP,
            CONCAT(
                IFNULL(NOMBRES, ''), ' ',
                IFNULL(`APELLIDO PATERNO`, ''), ' ',
                IFNULL(`APELLIDO MATERNO`, '')
            ) AS nombre_completo
        FROM Plantilla
        WHERE ESTATUS = 'ACTIVO'
          AND CONCAT(
                IFNULL(NOMBRES, ''), ' ',
                IFNULL(`APELLIDO PATERNO`, ''), ' ',
                IFNULL(`APELLIDO MATERNO`, '')
          ) LIKE CONCAT('%', ?, '%')
        ORDER BY nombre_completo ASC
        LIMIT 20";

$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $term);
$stmt->execute();
$res = $stmt->get_result();

$items = [];
while ($row = $res->fetch_assoc()) {
    $items[] = [
        'curp' => $row['CURP'],
        'nombre_completo' => preg_replace('/\s+/', ' ', trim($row['nombre_completo']))
    ];
}

$stmt->close();

echo json_encode(['success' => true, 'items' => $items]);
