<?php
session_start();
if (!isset($_SESSION['attuid']) || !in_array($_SESSION['rol'] ?? '', ['subdistribuidor', 'adminTi'])) {
    header('Location: ../../index.php');
    exit();
}
require_once __DIR__ . '/../includes/valida_posiciones.php';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8" />
    <title>Registrar Aspirante | Subdistribuidor</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- Bootstrap 5 + FontAwesome -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet" />
    <link href="../assets/css/recruiter.css" rel="stylesheet" />
</head>
<body class="bg-light">
<div class="d-flex">
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content w-100" id="mainContent">
        <?php include '../includes/topbar.php'; ?>

        <div class="container p-4">
            <div class="row justify-content-center">
                <div class="col-lg-10">
                    <div class="card shadow">
                        <div class="card-header bg-primary text-white">
                            <h4 class="mb-0"><i class="fas fa-user-plus me-2"></i>Registro de nuevo aspirante</h4>
                        </div>
                        <div class="card-body">
                            <form id="formRegistrarAspirante" autocomplete="off" novalidate>
                                <!-- Información Básica -->
                                <fieldset class="mb-4 border rounded p-3">
                                    <legend class="w-auto px-2">Información básica</legend>
                                    <div class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">Nombre(s) *</label>
                                            <input type="text" name="nombre" class="form-control" required maxlength="255" />
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">Apellido paterno *</label>
                                            <input type="text" name="apellido_paterno" class="form-control" required maxlength="255" />
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">Apellido materno *</label>
                                            <input type="text" name="apellido_materno" class="form-control" required maxlength="255" />
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">CURP *</label>
                                            <input type="text" name="curp" class="form-control" pattern="[A-Z0-9]{18}" maxlength="18" minlength="18" required style="text-transform:uppercase" />
                                            <div class="form-text">18 caracteres, en mayúsculas</div>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">NSS *</label>
                                            <input type="text" name="nss" class="form-control" pattern="[0-9]{11}" maxlength="11" minlength="11" required />
                                            <div class="form-text">11 dígitos</div>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">RFC *</label>
                                            <input type="text" name="rfc" class="form-control" pattern="[A-ZÑ&]{3,4}[0-9]{6}[A-Z0-9]{3}" maxlength="13" minlength="12" required style="text-transform:uppercase" />
                                            <div class="form-text">12 o 13 caracteres</div>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">Correo electrónico *</label>
                                            <input type="email" name="correo" class="form-control" maxlength="255" required />
                                        </div>
                                        <div class="col-md-4">
                                           <label class="form-label fw-bold">Teléfono *</label>
                                            <input type="tel" name="telefono" class="form-control" maxlength="20" pattern="[0-9]{10,20}" required />
                                            <div class="form-text">Solo números, 10 a 20 dígitos</div>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label fw-bold">Puesto *</label>
                                            <select name="puesto" class="form-select" required>
                                                <option value="">Selecciona</option>
                                                <option value="FED EJECUTIVO UNIVERSAL">Ejecutivo</option>
                                                <option value="FED GERENTE DE TIENDA">Gerente</option>
                                            </select>
                                        </div>
                                    </div>
                                </fieldset>

                                <!-- Información Médica -->
                                <fieldset class="mb-4 border rounded p-3">
                                    <legend class="w-auto px-2">Información médica</legend>
                                    <div class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Estado civil</label>
                                            <select class="form-select" name="estado_civil">
                                                <option value="">Selecciona una opción</option>
                                                <option value="SOLTERO/A">Soltero/a</option>
                                                <option value="CASADO/A">Casado/a</option>
                                                <option value="DIVORCIADO/A">Divorciado/a</option>
                                                <option value="SEPARADO/A EN PROCESO JUDICIAL">Separado/a en proceso judicial</option>
                                                <option value="VIUDO/A">Viudo/a</option>
                                                <option value="CONCUBINATO">Concubinato</option>
                                                <option value="UNION LIBRE">Unión libre</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Hijos</label>
                                            <input type="number" name="Numero_Hijos" class="form-control" />
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Talla</label>
                                            <input type="text" name="Talla" class="form-control" />
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Grupo sanguíneo</label>
                                            <input type="text" name="Grupo_sanguineo" class="form-control" />
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Alérgenos</label>
                                            <input type="text" name="Alergenos" class="form-control" />
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Enfermedades crónicas</label>
                                            <input type="text" name="Enfermedades_cronicas" class="form-control" />
                                        </div>
                                    </div>
                                </fieldset>

                                <!-- Contacto de Emergencia -->
                                <fieldset class="mb-4 border rounded p-3">
                                    <legend class="w-auto px-2">Contacto de emergencia</legend>
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Nombre contacto</label>
                                            <input type="text" name="Nombre_contacto_emergen" class="form-control" />
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Teléfono contacto</label>
                                            <input type="text" name="Tel_contacto_emergen" class="form-control" />
                                        </div>
                                    </div>
                                </fieldset>

                                <!-- Ubicación y contacto -->
                                <fieldset class="mb-4 border rounded p-3">
                                    <legend class="w-auto px-2">Ubicación y contacto</legend>
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Dirección</label>
                                            <input type="text" name="direccion" class="form-control" />
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Teléfono personal</label>
                                            <input type="text" name="Tel_personal" class="form-control" />
                                        </div>
                                    </div>
                                </fieldset>

                                <div class="text-end mt-4">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save me-2"></i>Registrar Aspirante
                                    </button>
                                    <a href="candidatos.php" class="btn btn-secondary ms-2">Cancelar</a>
                                </div>
                                <div id="formAlert" class="mt-3"></div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Convertir automáticamente a mayúsculas los campos relevantes
document.querySelectorAll(
    'input[name="nombre"], input[name="apellido_paterno"], input[name="apellido_materno"], input[name="curp"], input[name="rfc"], input[name="ubicacion"]'
).forEach(input => {
    input.addEventListener('input', function() {
        this.value = this.value.toUpperCase();
    });
});

// Validar y enviar formulario vía fetch
document.getElementById('formRegistrarAspirante').addEventListener('submit', function(e) {
    e.preventDefault();
    const form = e.target;
    const formData = new FormData(form);
    const alertDiv = document.getElementById('formAlert');
    alertDiv.innerHTML = '';

    // Validación HTML5
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        alertDiv.innerHTML = '<div class="alert alert-warning">Por favor, revisa los campos obligatorios y el formato de los datos.</div>';
        return;
    }

    // Envío al backend
    fetch('../../backend/subdistribuidor/guardar_aspirante.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            alertDiv.innerHTML = '<div class="alert alert-success">Aspirante registrado exitosamente.</div>';
            form.reset();
            form.classList.remove('was-validated');
        } else {
            alertDiv.innerHTML = `<div class="alert alert-danger">${data.message || 'Error al registrar.'}</div>`;
        }
    })
    .catch(err => {
        alertDiv.innerHTML = '<div class="alert alert-danger">Ocurrió un error al conectar con el servidor.</div>';
    });
});
</script>
</body>
</html>
