<?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-file-invoice-dollar text-success me-2"></i>Control de Mensualidades y Cobros
        </h2>
        <p class="text-muted small mb-0">Gestión de cuentas por cobrar, emisión de pensiones y registro de pagos recibidos.</p>
    </div>
    <div class="col-auto">
        <button class="btn btn-success text-white rounded-pill shadow-sm fw-bold" data-bs-toggle="modal" data-bs-target="#modalGenerarCobro">
            <i class="fas fa-plus me-2"></i>Generar Obligación / Mensualidad
        </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="tablaMensualidades">
                <thead class="table-light text-muted small fw-bold text-uppercase">
                    <tr>
                        <th>Bastonera / Alumna</th>
                        <th>Concepto</th>
                        <th>Monto Total</th>
                        <th>Saldo Pendiente</th>
                        <th style="width: 15%">Fecha Emisión</th>
                        <th style="width: 15%">Estado</th>
                        <th class="text-center" style="width: 12%">Acciones</th>
                    </tr>
                </thead>
                <tbody class="small">
                    <?php
                    try {
                        // Modificamos ligeramente la consulta para traer campos identificadores del origen si existen (ej: cxc_origen o cxc_tipo)
                        // Si no existen campos diferenciadores, agregamos lógica de detección en el bucle.
                        $sql = "SELECT cxc.*, b.bas_nombres, b.bas_apellidos, con.con_nombre 
                                FROM bas_cuentas_cobrar cxc
                                INNER JOIN bas_bastoneras b ON cxc.bas_id = b.bas_id
                                INNER JOIN bas_conceptos con ON cxc.con_id = con.con_id
                                ORDER BY cxc.cxc_fecha_emision DESC";
                        
                        $res = $bd->ejecutar($sql);

                        if ($res && $res->num_rows > 0) {
                            while ($row = $res->fetch_assoc()) {
                                
                                $badge = (strtoupper($row['cxc_estado']) === 'PAGADO') 
                                    ? '<span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-3 py-1">Pagado</span>' 
                                    : '<span class="badge bg-danger-subtle text-danger border border-danger-subtle rounded-pill px-3 py-1">Pendiente</span>';
                                
                                // ==========================================================
                                // CORRECCIÓN DEL CONCEPTO PARA VENTAS POS
                                // ==========================================================
                                $concepto_mostrar = $row['con_nombre'];
                                
                                // Opción A: Si tienes una columna que identifica que viene del POS (ej: cxc_origen o cxc_modulo)
                                if (isset($row['cxc_origen']) && strtoupper($row['cxc_origen']) === 'POS') {
                                    $concepto_mostrar = 'Venta POS';
                                } 
                                // Opción B: Si temporalmente identificas las ventas POS por montos específicos de tienda 
                                // o si el controlador de cobros del POS guarda una observación descriptiva (ej: cxc_observacion)
                                elseif (isset($row['cxc_observacion']) && (strpos(strtolower($row['cxc_observacion']), 'pos') !== false || strpos(strtolower($row['cxc_observacion']), 'venta') !== false)) {
                                    $concepto_mostrar = 'Venta POS';
                                }
                                // ==========================================================

                                echo "<tr>";
                                echo "<td class='fw-bold text-dark'>" . htmlspecialchars($row['bas_apellidos'] . " " . $row['bas_nombres']) . "</td>";
                                echo "<td>" . htmlspecialchars($concepto_mostrar) . "</td>";
                                echo "<td>$" . number_format($row['cxc_valor_final'], 2) . "</td>";
                                echo "<td class='fw-bold text-danger'>$" . number_format($row['cxc_saldo_pendiente'], 2) . "</td>";
                                echo "<td>" . date('d/m/Y', strtotime($row['cxc_fecha_emision'])) . "</td>";
                                echo "<td>" . $badge . "</td>";
                                echo "<td class='text-center'>";
                                if (strtoupper($row['cxc_estado']) !== 'PAGADO') {
                                    echo "<button class='btn btn-sm btn-outline-success rounded-pill btn-pagar' 
                                                  data-id='".$row['cxc_id']."' 
                                                  data-alumno='".htmlspecialchars($row['bas_apellidos']." ".$row['bas_nombres'], ENT_QUOTES)."' 
                                                  data-concepto='".htmlspecialchars($concepto_mostrar, ENT_QUOTES)."' 
                                                  data-saldo='".$row['cxc_saldo_pendiente']."'>
                                                <i class='fas fa-cash-register'></i>
                                          </button>";
                                } else {
                                    echo "<span class='text-muted small'><i class='fas fa-check-double text-success'></i> Listo</span>";
                                }
                                echo "</td>";
                                echo "</tr>";
                            }
                        } else {
                            echo "<tr><td colspan='7' class='text-center text-muted py-4'>No hay cuentas de cobro registradas todavía.</td></tr>";
                        }
                    } catch (Exception $e) {
                        echo "<tr><td colspan='7' class='text-center text-danger py-4'>⚠️ Error de base de datos: " . htmlspecialchars($e->getMessage()) . "</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalGenerarCobro" 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-file-invoice me-2 text-success"></i>Nueva Obligación de Pago
                </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/MensualidadController.php?action=generar_cobro">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Seleccionar Alumna *</label>
                            <select class="form-select bg-light" name="bas_id" required>
                                <option value="">-- Seleccione una Alumna --</option>
                                <?php
                                $alumnas = $bd->ejecutar("SELECT bas_id, bas_nombres, bas_apellidos FROM bas_bastoneras WHERE bas_estado = 1 ORDER BY bas_apellidos ASC");
                                if ($alumnas) {
                                    while($a = $alumnas->fetch_assoc()) {
                                        echo "<option value='".$a['bas_id']."'>".$a['bas_apellidos']." ".$a['bas_nombres']."</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Concepto de Pago *</label>
                            <select class="form-select bg-light" name="con_id" required>
                                <option value="">-- Seleccione Concepto --</option>
                                <?php
                                $conceptos = $bd->ejecutar("SELECT con_id, con_nombre, con_valor_base FROM bas_conceptos WHERE con_estado = 1 ORDER BY con_nombre ASC");
                                if ($conceptos) {
                                    while($c = $conceptos->fetch_assoc()) {
                                        echo "<option value='".$c['con_id']."'>".$c['con_nombre']." ($".number_format($c['con_valor_base'], 2).")</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted small fw-bold">Valor Total ($) *</label>
                            <input type="number" step="0.01" min="0" class="form-control bg-light" name="cxc_valor_base" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted small fw-bold">Fecha de Emisión *</label>
                            <input type="date" class="form-control bg-light" name="cxc_fecha_emision" value="<?php echo date('Y-m-d'); ?>" 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-success rounded-pill px-4 btn-sm fw-bold">Asignar Cobro</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalRegistrarPago" 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-success text-white border-0 py-3 rounded-top-4">
                <h5 class="modal-title fw-bold small text-uppercase"><i class="fas fa-cash-register me-2"></i>Procesar Pago Entrante</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/MensualidadController.php?action=registrar_pago">
                <div class="modal-body p-4">
                    <input type="hidden" name="cxc_id" id="pago_cxc_id">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold mb-0">Alumna:</label>
                            <p id="lbl_alumno" class="fw-bold text-dark mb-2"></p>
                            
                            <label class="form-label text-muted small fw-bold mb-0">Concepto Pendiente:</label>
                            <p id="lbl_concepto" class="text-secondary mb-2"></p>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted small fw-bold">Saldo Actual Pendiente</label>
                            <div class="input-group">
                                <span class="input-group-text">$</span>
                                <input type="text" class="form-control bg-light fw-bold text-danger" id="pago_saldo_actual" readonly>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted small fw-bold">Monto a Pagar ($) *</label>
                            <input type="number" step="0.01" min="0.01" class="form-control bg-light fw-bold" name="pag_monto" id="pago_monto_ingresar" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label text-muted small fw-bold">Método de Pago *</label>
                            <select class="form-select bg-light" name="pag_metodo" required>
                                <option value="EFECTIVO">EFECTIVO</option>
                                <option value="TRANSFERENCIA">TRANSFERENCIA BANCARIA</option>
                                <option value="DEPOSITO">DEPÓSITO</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-success rounded-pill px-4 btn-sm fw-bold">Confirmar Recibo</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tabla = document.getElementById('tablaMensualidades');
    if (tabla) {
        tabla.addEventListener('click', function(e) {
            const boton = e.target.closest('.btn-pagar');
            if (boton) {
                e.preventDefault();
                document.getElementById('pago_cxc_id').value = boton.getAttribute('data-id');
                document.getElementById('lbl_alumno').innerText = boton.getAttribute('data-alumno');
                document.getElementById('lbl_concepto').innerText = boton.getAttribute('data-concepto');
                
                const saldo = boton.getAttribute('data-saldo');
                document.getElementById('pago_saldo_actual').value = parseFloat(saldo).toFixed(2);
                document.getElementById('pago_monto_ingresar').value = parseFloat(saldo).toFixed(2);
                document.getElementById('pago_monto_ingresar').setAttribute('max', saldo);
                
                if (typeof bootstrap !== 'undefined') {
                    const elModal = document.getElementById('modalRegistrarPago');
                    const m = bootstrap.Modal.getInstance(elModal) || new bootstrap.Modal(elModal);
                    m.show();
                }
            }
        });
    }
});
</script>