<?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-tags text-primary me-2"></i>Conceptos de Pago
        </h2>
        <p class="text-muted small mb-0">Configuración de los valores base para mensualidades, inscripciones y uniformes.</p>
    </div>
    <div class="col-auto">
        <button class="btn btn-primary text-white rounded-pill shadow-sm fw-bold" data-bs-toggle="modal" data-bs-target="#modalNuevoConcepto">
            <i class="fas fa-plus me-2"></i>Nuevo Concepto
        </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" id="tablaConceptos">
                <thead class="table-light text-muted small fw-bold text-uppercase">
                    <tr>
                        <th style="width: 10%">ID</th>
                        <th>Nombre del Concepto</th>
                        <th>Valor Base Sugerido</th>
                        <th style="width: 15%">Estado</th>
                        <th class="text-center" style="width: 12%">Acciones</th>
                    </tr>
                </thead>
                <tbody class="small">
                    <?php
                    try {
                        $sql = "SELECT * FROM bas_conceptos ORDER BY con_nombre ASC";
                        $res = $bd->ejecutar($sql);

                        if ($res && $res->num_rows > 0) {
                            while ($row = $res->fetch_assoc()) {
                                // Control de estado por seguridad si la columna existe
                                $estado_val = isset($row['con_estado']) ? $row['con_estado'] : 1;
                                $badge = ($estado_val == 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['con_id'] . "</td>";
                                echo "<td class='fw-bold text-dark'>" . htmlspecialchars($row['con_nombre']) . "</td>";
                                echo "<td class='fw-bold text-primary'>$" . number_format($row['con_valor_base'], 2) . "</td>";
                                echo "<td>" . $badge . "</td>";
                                echo "<td class='text-center'>";
                                echo "<button class='btn btn-sm btn-outline-secondary rounded-pill btn-editar-concepto' 
                                              data-id='".$row['con_id']."' 
                                              data-nombre='".htmlspecialchars($row['con_nombre'], ENT_QUOTES)."' 
                                              data-valor='".$row['con_valor_base']."'
                                              data-estado='".$estado_val."'>
                                            <i class='fas fa-edit'></i>
                                      </button>";
                                echo "</td>";
                                echo "</tr>";
                            }
                        } else {
                            echo "<tr><td colspan='5' class='text-center text-muted py-4'>No hay conceptos configurados todavía.</td></tr>";
                        }
                    } catch (Exception $e) {
                        echo "<tr><td colspan='5' class='text-center text-danger py-4'>⚠️ Error al cargar conceptos: " . htmlspecialchars($e->getMessage()) . "</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalNuevoConcepto" data-bs-backdrop="static" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-md 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">
                    <i class="fas fa-tag me-2 text-primary"></i>Crear Rubro / Concepto
                </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/ConceptoController.php?action=crear">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Nombre del Concepto *</label>
                            <input type="text" class="form-control bg-light" name="con_nombre" placeholder="Ej. Mensualidad Julio" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Valor Base ($) *</label>
                            <input type="number" step="0.01" min="0" class="form-control bg-light fw-bold" name="con_valor_base" placeholder="0.00" required>
                        </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 Concepto</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditarConcepto" data-bs-backdrop="static" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-md modal-dialog-centered">
        <div class="modal-content border-0 shadow rounded-4">
            <div class="modal-header bg-primary text-white border-0 py-3 rounded-top-4">
                <h5 class="modal-title fw-bold small text-uppercase">
                    <i class="fas fa-edit me-2"></i>Modificar Concepto
                </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/ConceptoController.php?action=editar">
                <div class="modal-body p-4">
                    <input type="hidden" name="con_id" id="edit_con_id">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Nombre del Concepto *</label>
                            <input type="text" class="form-control bg-light" name="con_nombre" id="edit_con_nombre" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted small fw-bold">Valor Base ($) *</label>
                            <input type="number" step="0.01" min="0" class="form-control bg-light fw-bold" name="con_valor_base" id="edit_con_valor" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted small fw-bold">Estado del Rubro</label>
                            <select class="form-select bg-light" name="con_estado" id="edit_con_estado">
                                <option value="1">ACTIVO (Disponible)</option>
                                <option value="0">INACTIVO (Ocultar)</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">Actualizar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tabla = document.getElementById('tablaConceptos');
    if (tabla) {
        tabla.addEventListener('click', function(e) {
            const boton = e.target.closest('.btn-editar-concepto');
            if (boton) {
                e.preventDefault();
                
                document.getElementById('edit_con_id').value = boton.getAttribute('data-id');
                document.getElementById('edit_con_nombre').value = boton.getAttribute('data-nombre');
                document.getElementById('edit_con_valor').value = parseFloat(boton.getAttribute('data-valor')).toFixed(2);
                
                const selectorEstado = document.getElementById('edit_con_estado');
                if (selectorEstado) {
                    selectorEstado.value = boton.getAttribute('data-estado');
                }
                
                if (typeof bootstrap !== 'undefined') {
                    const elModal = document.getElementById('modalEditarConcepto');
                    const m = bootstrap.Modal.getInstance(elModal) || new bootstrap.Modal(elModal);
                    m.show();
                }
            }
        });
    }
});
</script>