<?php
// vista/usuarios/pagos_adelantos.php
$db = new clsbdd();
$db->ejecutar("SET NAMES 'utf8'");

// GESTIÓN DE MENSAJES DE RETROALIMENTACIÓN
$mensaje = "";
$alerta = "success";
if (isset($_GET['msj'])) {
    switch ($_GET['msj']) {
        case 'pago_ok': $mensaje = "Registro completado con éxito."; break;
        case 'error_db': $mensaje = "Error interno en los parámetros de la base de datos."; $alerta = "danger"; break;
    }
}
?>

<div class="row g-4 mb-4">
    <div class="col-12 col-xl-8 mx-auto">
        <div class="card shadow border-0" style="border-radius: 15px;">
            <div class="card-header py-3 bg-primary text-white" style="border-radius: 15px 15px 0 0;">
                <h6 class="m-0 font-weight-bold"><i class="fas fa-wallet me-2"></i> Registro de Pagos / Liquidación Semanal</h6>
            </div>
            <div class="card-body p-4">
                <?php if ($mensaje): ?>
                    <div class="alert alert-<?= $alerta ?> alert-dismissible fade show" role="alert">
                        <?= $mensaje ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <form action="controlador/car_PagosControlador.php" method="POST" id="form-pagos-autocalculo">
                    
                    <div class="row mb-4 bg-light p-3 rounded border">
                        <div class="col-md-6 mb-2 mb-md-0">
                            <label class="form-label fw-bold text-dark">1. Seleccione el Operario</label>
                            <select name="ope_id" id="ope_id" class="form-select form-select-lg fw-bold border-primary" required onchange="consultarAdelantosBase(this.value)">
                                <option value="">-- Buscar / Seleccionar --</option>
                                <?php 
                                $sql_ope = "SELECT ope_id, ope_nombre FROM car_operarios WHERE ope_estado = 1 ORDER BY ope_nombre ASC";
                                $res_ope = $db->ejecutar($sql_ope);
                                if ($res_ope) {
                                    while($ope = $res_ope->fetch_assoc()) {
                                        echo '<option value="'.$ope['ope_id'].'">'.htmlspecialchars($ope['ope_nombre']).'</option>';
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-dark">2. Tipo de Movimiento</label>
                            <select name="pgo_tipo" id="pgo_tipo" class="form-select form-select-lg fw-bold border-primary" required onchange="alternarModoFormulario(this.value)">
                                <option value="Adelanto">Adelanto</option>
                                <option value="Pago Semanal">Liquidación</option>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold text-primary" id="lbl-monto-principal">Monto del Adelanto ($)</label>
                            <div class="input-group input-group-lg">
                                <span class="input-group-text fw-bold">$</span>
                                <input type="number" step="0.01" name="input_monto_interactivo" id="input_monto_interactivo" class="form-control fw-bold text-dark" required placeholder="0.00" oninput="calcularRestaAutomatica()">
                            </div>
                        </div>

                        <div class="col-md-6 mb-3 d-none" id="div-descuento-adelantos">
                            <label class="form-label fw-bold text-danger">(-) Adelantos Pendientes (Carga Automática)</label>
                            <div class="input-group input-group-lg">
                                <span class="input-group-text fw-bold text-danger">-$</span>
                                <input type="number" step="0.01" name="pgo_descuento_adelantos" id="pgo_descuento_adelantos" class="form-control fw-bold text-danger bg-white" value="0.00" readonly>
                            </div>
                            <small class="text-muted"><i class="fas fa-filter text-danger"></i> Sumando solo adelantos activos no liquidados.</small>
                        </div>
                    </div>

                    <div class="p-3 mb-4 rounded border text-center d-none shadow-sm" id="box-saldo-final" style="background-color: #f8f9fa;">
                        <span class="text-uppercase small d-block fw-bold text-secondary mb-1">Saldo Neto Real a Entregar en Caja</span>
                        <h2 class="fw-bold mb-0" id="lbl-saldo-final" style="color: #212529;">$0.00</h2>
                        
                        <input type="hidden" name="pgo_monto" id="pgo_monto">
                        <input type="hidden" name="pgo_monto_bruto" id="pgo_monto_bruto">
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-4 mb-3 mb-md-0">
                            <label class="form-label fw-bold">Método de Pago</label>
                            <select name="pgo_metodo" class="form-select">
                                <option value="Efectivo">Efectivo</option>
                                <option value="Transferencia">Transferencia</option>
                            </select>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label fw-bold">Observación</label>
                            <input type="text" name="pgo_observacion" id="pgo_observacion" class="form-control" placeholder="Detalle adicional...">
                        </div>
                    </div>

                    <div class="text-end">
                        <button type="submit" class="btn btn-primary btn-lg fw-bold px-5 shadow">
                            <i class="fas fa-check-circle me-1"></i> PROCESAR Y GUARDAR
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="card shadow border-0" style="border-radius: 15px;">
    <div class="card-header py-3 bg-white border-0">
        <h6 class="m-0 font-weight-bold text-dark"><i class="fas fa-history me-2"></i> Estado de Cuentas y Últimos Registros</h6>
    </div>
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="bg-light text-secondary">
                <tr style="font-size: 0.75rem; text-transform: uppercase;">
                    <th class="ps-3">Fecha</th>
                    <th>Operario</th>
                    <th>Tipo</th>
                    <th>Monto Final</th>
                    <th>Estado de Cobro</th>
                    <th>Observación / Registro Analítico</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $sql_hist = "SELECT p.*, o.ope_nombre 
                             FROM car_pagos_operarios p
                             INNER JOIN car_operarios o ON p.ope_id = o.ope_id
                             ORDER BY p.pgo_fecha DESC LIMIT 15";
                $res_hist = $db->ejecutar($sql_hist);
                if ($res_hist && $res_hist->num_rows > 0) {
                    while($h = $res_hist->fetch_assoc()) {
                        $badge = ($h['pgo_tipo'] == 'Adelanto') ? 'bg-warning text-dark' : 'bg-success text-white';
                        
                        $estado_cobro = '<span class="text-muted">-</span>';
                        if($h['pgo_tipo'] == 'Adelanto') {
                            if(str_contains($h['pgo_observacion'] ?? '', '[LIQUIDADO')) {
                                $estado_cobro = '<span class="badge bg-light text-secondary border"><i class="fas fa-check-double text-success me-1"></i> Ya Cruzado</span>';
                            } else {
                                $estado_cobro = '<span class="badge bg-danger-soft text-danger border border-danger"><i class="fas fa-clock me-1"></i> Pendiente</span>';
                            }
                        } else {
                            $estado_cobro = '<span class="badge bg-success-soft text-success border border-success"><i class="fas fa-wallet me-1"></i> Cierre Efectuado</span>';
                        }

                        echo "<tr>
                                <td class='ps-3 small'>".date('d/m H:i', strtotime($h['pgo_fecha']))."</td>
                                <td class='fw-bold text-dark'>".htmlspecialchars($h['ope_nombre'])."</td>
                                <td><span class='badge $badge rounded-pill px-3'>".$h['pgo_tipo']."</span></td>
                                <td class='fw-bold text-primary'>$".number_format($h['pgo_monto'], 2)."</td>
                                <td>$estado_cobro</td>
                                <td class='small text-muted'>".htmlspecialchars($h['pgo_observacion'] ?? 'Sin observaciones')."</td>
                              </tr>";
                    }
                } else {
                    echo "<tr><td colspan='6' class='text-center py-4 text-muted'>No hay registros de nómina aún.</td></tr>";
                }
                ?>
            </tbody>
        </table>
    </div>
</div>

<script>
let adelantosBD = 0;

function obtenerRutaRaiz() {
    const loc = window.location;
    const path = loc.pathname;
    const baseDir = path.substring(0, path.indexOf('/', 1) + 1);
    return loc.protocol + "//" + loc.host + (baseDir.includes('index.php') ? '/' : baseDir);
}

function consultarAdelantosBase(idOperario) {
    if (!idOperario) {
        adelantosBD = 0;
        document.getElementById('pgo_descuento_adelantos').value = '0.00';
        calcularRestaAutomatica();
        return;
    }

    const urlBase = obtenerRutaRaiz();
    const urlDestino = `${urlBase}controlador/car_PagosControlador.php?accion=obtener_adelantos&ope_id=${idOperario}`;

    fetch(urlDestino)
        .then(response => response.json())
        .then(data => {
            adelantosBD = parseFloat(data.total_adelantos) || 0;
            document.getElementById('pgo_descuento_adelantos').value = adelantosBD.toFixed(2);
            calcularRestaAutomatica();
        })
        .catch(err => {
            fetch(`controlador/car_PagosControlador.php?accion=obtener_adelantos&ope_id=${idOperario}`)
                .then(r => r.json())
                .then(d => {
                    adelantosBD = parseFloat(d.total_adelantos) || 0;
                    document.getElementById('pgo_descuento_adelantos').value = adelantosBD.toFixed(2);
                    calcularRestaAutomatica();
                }).catch(e => console.error("No se pudo conectar al endpoint:", e));
        });
}

function alternarModoFormulario(tipo) {
    const lblMonto = document.getElementById('lbl-monto-principal');
    const divAdelantos = document.getElementById('div-descuento-adelantos');
    const boxSaldo = document.getElementById('box-saldo-final');
    const inputObs = document.getElementById('pgo_observacion');
    
    document.getElementById('input_monto_interactivo').value = '';
    document.getElementById('pgo_monto').value = '';
    document.getElementById('pgo_monto_bruto').value = '';

    if (tipo === 'Pago Semanal') {
        lblMonto.innerText = "Total Ganado en la Semana ($)";
        divAdelantos.classList.remove('d-none');
        boxSaldo.classList.remove('d-none');
        inputObs.value = "Liquidación semanal de haberes.";
    } else {
        lblMonto.innerText = "Monto del Adelanto ($)";
        divAdelantos.classList.add('d-none');
        boxSaldo.classList.add('d-none');
        inputObs.value = "";
    }
    calcularRestaAutomatica();
}

function calcularRestaAutomatica() {
    const tipo = document.getElementById('pgo_tipo').value;
    const bruto = parseFloat(document.getElementById('input_monto_interactivo').value) || 0;
    
    let netoFinal = bruto;

    if (tipo === 'Pago Semanal') {
        netoFinal = bruto - adelantosBD;
        
        const labelSaldo = document.getElementById('lbl-saldo-final');
        const contenedorSaldo = document.getElementById('box-saldo-final');
        
        labelSaldo.innerText = '$' + netoFinal.toFixed(2);

        if (netoFinal < 0) {
            contenedorSaldo.style.backgroundColor = '#ffebee';
            labelSaldo.style.color = '#c62828';
        } else if (netoFinal > 0) {
            contenedorSaldo.style.backgroundColor = '#e8f5e9';
            labelSaldo.style.color = '#2e7d32';
        } else {
            contenedorSaldo.style.backgroundColor = '#f8f9fa';
            labelSaldo.style.color = '#212529';
        }
        
        // Guardamos el bruto ingresado para el controlador
        document.getElementById('pgo_monto_bruto').value = bruto.toFixed(2);
    } else {
        document.getElementById('pgo_monto_bruto').value = '0.00';
    }

    document.getElementById('pgo_monto').value = netoFinal.toFixed(2);
}
</script>

<style>
.bg-danger-soft { background-color: #fff5f5; }
.bg-success-soft { background-color: #f4fbf7; }
</style>