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

if (!isset($_SESSION['attuid'])) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "No autorizado"]);
    exit();
}

include __DIR__ . '/../db/conexion.php';

function limpiarTexto($texto) {
    $texto = trim($texto);
    $texto = preg_replace('/[\x00-\x1F\x7F]/u', '', $texto); // elimina caracteres invisibles
    $texto = mb_strtoupper($texto, 'UTF-8'); // convierte a mayúsculas
    $texto = strtr($texto, "ÁÉÍÓÚÑÜáéíóúñü", "AEIOUNUAEIOUNU"); // quita acentos
    return $texto;
}

$aspirante_id = $_POST['aspirante_id'] ?? null;
$curp = limpiarTexto($_POST['curp'] ?? '');

if (!$aspirante_id || !$curp) {
    echo json_encode(["status" => "error", "message" => "Datos incompletos"]);
    exit();
}

if (!preg_match('/^[A-Z]{4}\d{6}[A-Z0-9]{8}$/', $curp)) {
    echo json_encode(["status" => "error", "message" => "CURP inválido"]);
    exit();
}

$stmt = $conn->prepare("UPDATE aspirantes SET curp = ? WHERE id = ?");
$stmt->bind_param("si", $curp, $aspirante_id);

if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "CURP actualizado"]);
} else {
    echo json_encode(["status" => "error", "message" => "Error al guardar CURP"]);
}

$stmt->close();
$conn->close();
exit();
