<?php
include 'conexion.php';

$customer_id = $_GET['customer_id'] ?? null;
if (!$customer_id) {
    echo "<div class='alert alert-warning'>Cliente no especificado.</div>";
    exit;
}

// Cliente
$sqlCliente = "SELECT * FROM customers WHERE customer_id = ?";
$stmtCliente = $conn->prepare($sqlCliente);
$stmtCliente->bind_param("i", $customer_id);
$stmtCliente->execute();
$resCliente = $stmtCliente->get_result();
$cliente = $resCliente->fetch_assoc();

// Facturas: traigo igst
$sql = "
SELECT 
    i.invoice_id, 
    i.created_at,
    i.inv_type,
    i.status,
    p.subtotal,
    p.payable_amount,
    p.others_charge,
    p.paid_amount,
    p.return_amount,
    p.due,
    p.discount_amount,
    p.igst
FROM selling_info i
JOIN selling_price p ON i.invoice_id = p.invoice_id
WHERE i.customer_id = ?
ORDER BY i.created_at DESC
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$res = $stmt->get_result();

$facturas_ars = $facturas_usd = $remitos = [];
foreach ($res as $f) {
    if ($f['igst'] == 12) {
        $remitos[] = $f;
    } else if ($f['others_charge'] > 1) {
        $facturas_usd[] = $f;
    } else {
        $facturas_ars[] = $f;
    }
}

// Saldo y deuda global
$sql_cts = "SELECT balance, due FROM customer_to_store WHERE customer_id = ?";
$stmt_cts = $conn->prepare($sql_cts);
$stmt_cts->bind_param("i", $customer_id);
$stmt_cts->execute();
$res_cts = $stmt_cts->get_result();
$cts = $res_cts->fetch_assoc();

function sum_col($arr, $col) {
    $suma = 0;
    foreach($arr as $a) $suma += floatval($a[$col]);
    return $suma;
}

// Fechas para filtros por defecto (mes actual)
$primerDia = date('Y-m-01');
$ultimoDia = date('Y-m-t');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Estado de Cuenta de Cliente</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body { background: #f8f9fa; }
        .table th, .table td { vertical-align: middle; }
        #remitos-section {
            background: #fff3cd !important;
            border: 1px solid #ffeeba;
            border-radius: 0.5rem;
            padding: 1rem 1rem 0.2rem 1rem;
            margin-bottom: 2rem;
        }
        #remitos-section table {
            background: #fffde7 !important;
        }
        .btn-exportar {
            float: right;
            margin-bottom: 10px;
        }
        .filter-row input[type="date"] {
            max-width: 170px;
        }
        #saldo-venta-usd {
            max-width: 500px;
        }
    </style>
</head>
<body>
<div class="container mt-4 mb-5">
    <h4 class="mb-3">Estado de Cuenta de Cliente</h4>
    <div class="card mb-3 shadow-sm">
        <div class="card-body">
            <strong>Cliente:</strong> <?= htmlspecialchars($cliente['customer_name'] ?? '') ?><br>
            <strong>ID:</strong> <?= htmlspecialchars($cliente['customer_id'] ?? '') ?><br>
            <strong>Saldo global:</strong> <?= number_format($cts['balance'] ?? 0, 2) ?><br>
            <strong>Deuda global:</strong> <?= number_format($cts['due'] ?? 0, 2) ?><br>
            <hr>
            <b>Calculo de saldo por moneda:</b><br>
            <span class="text-primary">ARS: </span>
            <?= number_format(
                sum_col($facturas_ars, 'payable_amount') 
                - sum_col($facturas_ars, 'paid_amount') 
                - sum_col($facturas_ars, 'discount_amount') 
                - sum_col($facturas_ars, 'return_amount'), 2
            ) ?>
            <span class="text-success"> | USD: </span>
            <?= number_format(
                sum_col($facturas_usd, 'payable_amount') 
                - sum_col($facturas_usd, 'paid_amount') 
                - sum_col($facturas_usd, 'discount_amount') 
                - sum_col($facturas_usd, 'return_amount'), 2
            ) ?>
        </div>
    </div>
    <div class="row mb-2 filter-row">
        <div class="col-md-3">
            <input type="text" id="filtro" class="form-control" placeholder="Buscar en las tablas...">
        </div>
        <div class="col-md-3">
            <input type="date" id="fecha-desde" class="form-control" placeholder="Fecha desde" value="<?= $primerDia ?>">
        </div>
        <div class="col-md-3">
            <input type="date" id="fecha-hasta" class="form-control" placeholder="Fecha hasta" value="<?= $ultimoDia ?>">
        </div>
    </div>

<?php
function tabla_facturas($facturas, $moneda, $titulo = '', $tablaid = '') {
    if (!$facturas) {
        echo "<div class='alert alert-info mb-3'>No hay $titulo.</div>";
        return;
    }
    // Bot�n exportar a Excel solo si hay datos
    echo '<button class="btn btn-outline-success btn-sm btn-exportar" onclick="exportTableToExcel(\''.$tablaid.'\')">Exportar a Excel</button>';
?>
    <h5 class="mt-3"><?= $titulo ?></h5>
    <table class="table table-striped table-bordered estadoCuentaTabla" id="<?= $tablaid ?>">
        <thead class="table-dark">
            <tr>
                <th>Fecha</th>
                <th>Factura</th>
                <th>Tipo</th>
                <th>Moneda</th>
                <th>Cotizacion</th>
                <th>Importe pesos</th>
                <th>Importe</th>
                <th>Pagado</th>
                <th>Devolucion</th>
                <th>Descuento</th>
                <th>Pendiente</th>
                <th>Estado</th>
                <th>Items</th>
                <?php if ($moneda == 'REM') { echo '<th>Observacion</th>'; } ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($facturas as $f): ?>
                <tr>
                    <td><?= date('Y-m-d', strtotime($f['created_at'])) ?></td>
                    <td><?= htmlspecialchars($f['invoice_id']) ?></td>
                    <td><?= ($f['payable_amount'] == 0)
                                ? "<span class='badge bg-success'>RECIBO</span>"
                                : "<span class='badge bg-danger'>FACTURA</span>" ?></td>
                    <td><?= ($moneda == 'ARS' ? 'ARS' : ($moneda == 'USD' ? 'USD' : '-')) ?></td>
                    <td><?= number_format($f['others_charge'],2) ?></td>
                    <td><?= number_format($f['subtotal'], 2) ?></td>
                    <td><?= number_format($f['payable_amount'], 2) ?></td>
                    <td><?= number_format($f['paid_amount'], 2) ?></td>
                  <td><?= $f['others_charge'] != 0 ? number_format($f['return_amount'] / $f['others_charge'], 2) : '0.00' ?></td>

                    <td><?= number_format($f['discount_amount'], 2) ?></td>
                    <td>
                        <span class="<?= $f['due'] > 0 ? 'text-danger' : 'text-success' ?>">
                            <?= number_format($f['due'], 2) ?>
                        </span>
                    </td>
                    <td>
                        <?= ($f['status'] == 1)
                                ? "<span class='badge bg-success'>Activa</span>"
                                : "<span class='badge bg-secondary'>Cerrada</span>" ?>
                    </td>
                    <td>
                        <button class="btn btn-outline-primary btn-sm ver-items"
                                data-invoice="<?= htmlspecialchars($f['invoice_id']) ?>">
                            Ver Items
                        </button>
                    </td>
                    <?php if ($moneda == 'REM') { echo '<td><b>Remito</b></td>'; } ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot class="table-light">
            <tr>
                <th colspan="5" class="text-end">Totales visibles:</th>
                <th id="<?= $tablaid ?>-subtotal"></th>
                <th id="<?= $tablaid ?>-payable"></th>
                <th id="<?= $tablaid ?>-paid"></th>
                <th id="<?= $tablaid ?>-return"></th>
                <th id="<?= $tablaid ?>-discount"></th>
                <th id="<?= $tablaid ?>-due"></th>
                <th colspan="3"></th>
            </tr>
        </tfoot>
    </table>
<?php } ?>

<?php
tabla_facturas($facturas_ars, 'ARS', 'Facturas en Pesos', 'tablaARS');
tabla_facturas($facturas_usd, 'USD', 'Facturas en Dolares', 'tablaUSD');
?>
<div class="alert alert-info mt-2" id="saldo-venta-usd">
    <b>Saldo USD = Total a pagar - Total pagado:</b>
    <span id="saldo-usd-monto" class="fw-bold"></span>
</div>

<div id="remitos-section" class="mt-5" style="display: none;">
    <?php
    tabla_facturas($remitos, 'REM', 'Remitos', 'tablaREM');
    ?>
</div>
<button id="toggleRemitos" class="btn btn-warning btn-sm mb-3">
    Mostrar remitos
</button>

<!-- Modal para mostrar �tems de la factura -->
<div class="modal fade" id="modalItems" tabindex="-1" aria-labelledby="modalItemsLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Detalle de items de la factura</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body" id="contenedor-items">
        <div class="text-center"><span class="spinner-border"></span> Cargando...</div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Filtros
function aplicarFiltros() {
    let txt = document.getElementById('filtro').value.toLowerCase();
    let desde = document.getElementById('fecha-desde').value;
    let hasta = document.getElementById('fecha-hasta').value;

    document.querySelectorAll('.estadoCuentaTabla tbody tr').forEach(function(row) {
        let texto = row.textContent.toLowerCase();
        let fecha = row.cells[0].textContent; // yyyy-mm-dd

        let visible = texto.includes(txt);

        if(desde && fecha < desde) visible = false;
        if(hasta && fecha > hasta) visible = false;

        row.style.display = visible ? '' : 'none';
    });

    // Actualiza totales visibles
    actualizarTotales('tablaARS');
    actualizarTotales('tablaUSD');
    actualizarTotales('tablaREM');
}
document.getElementById('filtro').addEventListener('keyup', aplicarFiltros);
document.getElementById('fecha-desde').addEventListener('change', aplicarFiltros);
document.getElementById('fecha-hasta').addEventListener('change', aplicarFiltros);
window.onload = aplicarFiltros;

function actualizarTotales(tablaid) {
    let tabla = document.getElementById(tablaid);
    if(!tabla) return;
    let tbody = tabla.tBodies[0];
    let subtotal=0, payable=0, paid=0, retorno=0, discount=0, due=0;
    Array.from(tbody.rows).forEach(function(row){
        if(row.style.display === 'none') return;
        subtotal += parseFloat(row.cells[5].textContent.replace(/,/g, '')) || 0;
        payable  += parseFloat(row.cells[6].textContent.replace(/,/g, '')) || 0;
        paid     += parseFloat(row.cells[7].textContent.replace(/,/g, '')) || 0;
        retorno  += parseFloat(row.cells[8].textContent.replace(/,/g, '')) || 0;
        discount += parseFloat(row.cells[9].textContent.replace(/,/g, '')) || 0;
        due      += parseFloat(row.cells[10].textContent.replace(/,/g, '')) || 0;
    });
    document.getElementById(tablaid+'-subtotal').textContent = subtotal.toFixed(2);
    document.getElementById(tablaid+'-payable').textContent  = payable.toFixed(2);
    document.getElementById(tablaid+'-paid').textContent     = paid.toFixed(2);
    document.getElementById(tablaid+'-return').textContent   = retorno.toFixed(2);
    document.getElementById(tablaid+'-discount').textContent = discount.toFixed(2);
    document.getElementById(tablaid+'-due').textContent      = due.toFixed(2);

    // SOLO para tablaUSD, mostramos el saldo calculado debajo
    if(tablaid === 'tablaUSD') {
        let saldoUSD = payable - paid - retorno;
        document.getElementById('saldo-usd-monto').textContent = saldoUSD.toFixed(2);
    }
}

// Mostrar �tems con modal y AJAX
document.querySelectorAll('.ver-items').forEach(btn => {
    btn.addEventListener('click', function(){
        let invoice_id = this.dataset.invoice;
        let modal = new bootstrap.Modal(document.getElementById('modalItems'));
        let cont = document.getElementById('contenedor-items');
        cont.innerHTML = '<div class="text-center"><span class="spinner-border"></span> Cargando...</div>';
        modal.show();

        // Llama a un PHP que devuelve los �tems de esa factura
        fetch('obtener_items_factura.php?invoice_id=' + encodeURIComponent(invoice_id))
        .then(r => r.text())
        .then(html => {
            cont.innerHTML = html;
        })
        .catch(() => {
            cont.innerHTML = '<div class="alert alert-danger">No se pudo cargar el detalle.</div>';
        });
    });
});

// Mostrar/ocultar remitos
const remitosSection = document.getElementById('remitos-section');
const toggleRemitosBtn = document.getElementById('toggleRemitos');
let remitosVisibles = false;
toggleRemitosBtn.addEventListener('click', function() {
    remitosVisibles = !remitosVisibles;
    remitosSection.style.display = remitosVisibles ? 'block' : 'none';
    toggleRemitosBtn.innerText = remitosVisibles ? "Ocultar remitos" : "Mostrar remitos";
});

// Exportar a Excel (solo filas visibles)
function exportTableToExcel(tableID, filename = ''){
    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    if(!tableSelect) return;

    // Solo toma filas visibles del tbody
    let tbody = tableSelect.tBodies[0];
    let tbodyHTML = '';
    Array.from(tbody.rows).forEach(function(row){
        if(row.style.display === 'none') return;
        tbodyHTML += row.outerHTML;
    });
    let tableHTML = '<table>' + tableSelect.tHead.outerHTML + '<tbody>' + tbodyHTML + '</tbody>' + tableSelect.tFoot.outerHTML + '</table>';

    filename = filename ? filename + '.xls' : 'estado_cuenta.xls';
    downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], { type: dataType });
        navigator.msSaveOrOpenBlob( blob, filename );
    }else{
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
        downloadLink.download = filename;
        downloadLink.click();
    }
    document.body.removeChild(downloadLink);
}
</script>
</body>
</html>
