<?php
if (!isset($_SESSION['usu_id'])) {
    header("Location: login.php");
    exit();
}
$bd = new clsbdd();
?>

<div class="row mb-4 align-items-center">
    <div class="col">
        <h2 class="h3 text-dark fw-bold mb-0">
            <i class="fas fa-layer-group text-primary me-2"></i>Categorías y Niveles Técnicos
        </h2>
        <p class="text-muted small mb-0">Configura las divisiones de rendimiento (Platinum, Gold, Silver) por cada rango de edad.</p>
    </div>
    <div class="col-auto">
        <button class="btn btn-primary rounded-pill shadow-sm fw-bold" data-bs-toggle="modal" data-bs-target="#modalClasificacion" id="btnNuevaClas_">
            <i class="fas fa-plus me-2"></i>Nueva Clasificación
        </button>
    </div>
</div>

<div class="card border-0 shadow-sm rounded-4 mb-4">
    <div class="card-body p-4">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light text-muted small fw-bold text-uppercase">
                    <tr>
                        <th style="width: 10%">ID</th>
                        <th>Categoría Base (Edad)</th>
                        <th>Nivel de Rendimiento</th>
                        <th style="width: 15%">Estado</th>
                        <th class="text-center" style="width: 15%">Acciones</th>
                    </tr>
                </thead>
                <tbody class="small">
                    <?php
                    $sql = "SELECT * FROM bas_clasificaciones ORDER BY cla_categoria ASC, cla_nivel ASC";
                    $res = $bd->ejecutar($sql);

                    if ($res && $res->num_rows > 0) {
                        while ($row = $res->fetch_assoc()) {
                            $badge = ($row['cla_estado'] == 1) 
                                ? '<span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-3 py-1">Activo</span>' 
                                : '<span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle rounded-pill px-3 py-1">Inactivo</span>';
                            
                            echo "<tr>";
                            echo "<td class='text-muted fw-bold'>#" . $row['cla_id'] . "</td>";
                            echo "<td class='fw-bold text-dark'>" . htmlspecialchars($row['cla_categoria']) . "</td>";
                            echo "<td><span class='badge bg-light text-primary border px-3 py-1 fw-bold'><i class='fas fa-medal me-1 text-warning'></i>" . htmlspecialchars($row['cla_nivel']) . "</span></td>";
                            echo "<td>" . $badge . "</td>";
                            echo "<td class='text-center'>
                                    <button class='btn btn-sm btn-outline-secondary rounded-pill btn-editar-cla' 
                                            data-id='".$row['cla_id']."' 
                                            data-categoria='".htmlspecialchars($row['cla_categoria'], ENT_QUOTES)."' 
                                            data-nivel='".htmlspecialchars($row['cla_nivel'], ENT_QUOTES)."'
                                            data-estado='".$row['cla_estado']."'>
                                        <i class='fas fa-edit'></i>
                                    </button>
                                  </td>";
                            echo "</tr>";
                        }
                    } else {
                        echo "<tr><td colspan='5' class='text-center text-muted py-4'>No hay categorías configuradas.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- MODAL DE INGRESO / EDICIÓN -->
<div class="modal fade" id="modalClasificacion" data-bs-backdrop="static" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow rounded-4">
            <div class="modal-header bg-dark text-white border-0 py-3 rounded-top-4">
                <h5 class="modal-title fw-bold small text-uppercase" id="modalClasTitulo">
                    <i class="fas fa-layer-group me-2 text-primary"></i>Configurar Nivel
                </h5>
                <button type="button" class="btn-close btn-close-white small" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="controlador/ClasificacionController.php?action=guardar">
                <div class="modal-body p-4">
                    <input type="hidden" name="cla_id" id="cla_id">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Categoría (Edad) *</label>
                            <input type="text" class="form-control bg-light text-uppercase" name="cla_categoria" id="cla_categoria" placeholder="Ej: INFANTIL, JUVENIL, MAYORES" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Nivel / División de Rendimiento *</label>
                            <input type="text" class="form-control bg-light text-uppercase" name="cla_nivel" id="cla_nivel" placeholder="Ej: PLATINUM, GOLD, SILVER, NOVICIOS" required>
                        </div>
                        <div class="col-12" id="div_cla_estado" style="display:none;">
                            <label class="form-label text-muted small fw-bold">Estado</label>
                            <select class="form-select bg-light" name="cla_estado" id="cla_estado">
                                <option value="1">ACTIVO</option>
                                <option value="0">INACTIVO</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-light rounded-pill px-4 btn-sm fw-bold text-muted" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary rounded-pill px-4 btn-sm fw-bold text-white">Guardar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const btnNueva = document.getElementById('btnNuevaClas_');
    if(btnNueva){
        btnNueva.addEventListener('click', function(){
            document.getElementById('cla_id').value = '';
            document.getElementById('cla_categoria').value = '';
            document.getElementById('cla_nivel').value = '';
            document.getElementById('div_cla_estado').style.display = 'none';
        });
    }

    document.body.addEventListener('click', function(e) {
        const boton = e.target.closest('.btn-editar-cla');
        if (boton) {
            e.preventDefault();
            document.getElementById('cla_id').value = boton.getAttribute('data-id');
            document.getElementById('cla_categoria').value = boton.getAttribute('data-categoria');
            document.getElementById('cla_nivel').value = boton.getAttribute('data-nivel');
            document.getElementById('cla_estado').value = boton.getAttribute('data-estado');
            document.getElementById('div_cla_estado').style.display = 'block';

            const elModal = document.getElementById('modalClasificacion');
            const m = bootstrap.Modal.getInstance(elModal) || new bootstrap.Modal(elModal);
            m.show();
        }
    });
});
</script>