<?php
session_start();
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

if (empty($curp)) {
    echo json_encode(['success' => false, 'message' => 'CURP no recibido.']);
    exit;
}

$query = "SELECT solicitud_prm_enviada FROM Plantilla WHERE CURP = ? LIMIT 1";
$stmt = $conn->prepare($query);

if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Error al preparar la consulta']);
    error_log("❌ Error al preparar: " . $conn->error);
    exit;
}

$stmt->bind_param("s", $curp);
$stmt->execute();
$res = $stmt->get_result();

if ($res && $res->num_rows > 0) {
    $dato = $res->fetch_assoc();
    $yaEnviada = intval($dato['solicitud_prm_enviada']) === 1;

    echo json_encode([
        'success' => true,
        'enviada' => $yaEnviada
    ]);
} else {
    echo json_encode([
        'success' => true,
        'enviada' => false
    ]);
}
