<?php
$filters = $filters ?? [
    'cliente_id' => 0,
    'fecha_desde' => '',
    'fecha_hasta' => '',
    'estado' => 'todos',
];
$customers = $customers ?? [];
$aging = $aging ?? [
    'saldo_0_30' => 0,
    'saldo_31_60' => 0,
    'saldo_61_90' => 0,
    'saldo_91_mas' => 0,
    'cuentas_0_30' => 0,
    'cuentas_31_60' => 0,
    'cuentas_61_90' => 0,
    'cuentas_91_mas' => 0,
];
$exportCsvUrl = $exportCsvUrl ?? url('cuentas-cobrar/exportar');
$exportXlsxUrl = $exportXlsxUrl ?? url('cuentas-cobrar/exportar-xlsx');
$exportPdfUrl = $exportPdfUrl ?? url('cuentas-cobrar/exportar-pdf');
?>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
            <div>
                <h1 class="h6 mb-1">Filtros de cartera</h1>
                <p class="text-muted small mb-0">Refina resultados por cliente, fechas y estado. Exporta en un clic.</p>
            </div>
        </div>
        <form method="get" action="<?= e(url('cuentas-cobrar')) ?>" class="vx-receivables-filters">
            <div class="vx-receivables-control vx-receivables-control-client">
                <label class="form-label">Cliente</label>
                <select name="cliente_id" class="form-select">
                    <option value="0">Todos</option>
                    <?php foreach ($customers as $customer): ?>
                        <option value="<?= e((string) $customer['id']) ?>" <?= (int) ($filters['cliente_id'] ?? 0) === (int) $customer['id'] ? 'selected' : '' ?>>
                            <?= e($customer['nombre']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="vx-receivables-control">
                <label class="form-label">Fecha desde</label>
                <input type="date" class="form-control" name="fecha_desde" value="<?= e((string) ($filters['fecha_desde'] ?? '')) ?>">
            </div>
            <div class="vx-receivables-control">
                <label class="form-label">Fecha hasta</label>
                <input type="date" class="form-control" name="fecha_hasta" value="<?= e((string) ($filters['fecha_hasta'] ?? '')) ?>">
            </div>
            <div class="vx-receivables-control vx-receivables-control-state">
                <label class="form-label">Estado</label>
                <select name="estado" class="form-select">
                    <option value="todos" <?= ($filters['estado'] ?? 'todos') === 'todos' ? 'selected' : '' ?>>Todos</option>
                    <option value="pendiente" <?= ($filters['estado'] ?? 'todos') === 'pendiente' ? 'selected' : '' ?>>Pendiente</option>
                    <option value="parcial" <?= ($filters['estado'] ?? 'todos') === 'parcial' ? 'selected' : '' ?>>Parcial</option>
                </select>
            </div>
            <div class="vx-receivables-actions">
                <button class="btn btn-primary vx-receivables-btn" type="submit">
                    <i class="bx bx-filter-alt me-1"></i>Filtrar
                </button>
                <a class="btn btn-light vx-receivables-btn" href="<?= e(url('cuentas-cobrar')) ?>">
                    <i class="bx bx-refresh me-1"></i>Limpiar
                </a>
                <div class="btn-group vx-receivables-export-group" role="group" aria-label="Exportar cartera">
                    <a class="btn btn-outline-success vx-receivables-btn" href="<?= e($exportCsvUrl) ?>">
                        <i class="bx bx-file me-1"></i>CSV
                    </a>
                    <a class="btn btn-outline-success vx-receivables-btn" href="<?= e($exportXlsxUrl) ?>">
                        <i class="bx bx-table me-1"></i>XLSX
                    </a>
                    <a class="btn btn-outline-danger vx-receivables-btn" href="<?= e($exportPdfUrl) ?>">
                        <i class="bx bxs-file-pdf me-1"></i>PDF
                    </a>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Credito colocado</span>
                <h2 class="h5 mb-0"><?= e(money($summary['total_credito'] ?? 0)) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Total abonado</span>
                <h2 class="h5 mb-0 text-success"><?= e(money($summary['total_abonado'] ?? 0)) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Saldo por cobrar</span>
                <h2 class="h5 mb-0 text-danger"><?= e(money($summary['total_saldo'] ?? 0)) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card metric-card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Cuentas abiertas</span>
                <h2 class="h5 mb-0"><?= e((string) ((int) ($summary['cuentas_pendientes'] ?? 0) + (int) ($summary['cuentas_parciales'] ?? 0))) ?></h2>
                <small class="text-muted">
                    Pendientes: <?= e((string) ($summary['cuentas_pendientes'] ?? 0)) ?> |
                    Parciales: <?= e((string) ($summary['cuentas_parciales'] ?? 0)) ?>
                </small>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Vencimiento 0-30</span>
                <h3 class="h6 mb-1"><?= e(money($aging['saldo_0_30'] ?? 0)) ?></h3>
                <small class="text-muted"><?= e((string) ($aging['cuentas_0_30'] ?? 0)) ?> cuenta(s)</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Vencimiento 31-60</span>
                <h3 class="h6 mb-1"><?= e(money($aging['saldo_31_60'] ?? 0)) ?></h3>
                <small class="text-muted"><?= e((string) ($aging['cuentas_31_60'] ?? 0)) ?> cuenta(s)</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Vencimiento 61-90</span>
                <h3 class="h6 mb-1"><?= e(money($aging['saldo_61_90'] ?? 0)) ?></h3>
                <small class="text-muted"><?= e((string) ($aging['cuentas_61_90'] ?? 0)) ?> cuenta(s)</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Vencimiento 91+</span>
                <h3 class="h6 mb-1 text-danger"><?= e(money($aging['saldo_91_mas'] ?? 0)) ?></h3>
                <small class="text-muted"><?= e((string) ($aging['cuentas_91_mas'] ?? 0)) ?> cuenta(s)</small>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
        <h1 class="h5 mb-3">Ventas con saldo pendiente</h1>
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>Venta</th>
                    <th>Fecha</th>
                    <th>Cliente</th>
                    <th>Cajero</th>
                    <th>Total</th>
                    <th>Abonado</th>
                    <th>Saldo</th>
                    <th>Dias</th>
                    <th>Rango</th>
                    <th>Estado</th>
                    <th>Accion</th>
                </tr>
                </thead>
                <tbody>
                <?php if ($accounts === []): ?>
                    <tr>
                        <td colspan="11" class="text-center text-muted py-4">
                            No hay cuentas por cobrar pendientes.
                        </td>
                    </tr>
                <?php endif; ?>
                <?php foreach ($accounts as $account): ?>
                    <tr>
                        <td>#<?= e((string) $account['id']) ?></td>
                        <td><?= e($account['fecha']) ?></td>
                        <td><?= e($account['cliente'] ?? 'Consumidor final') ?></td>
                        <td><?= e($account['cajero'] ?? '') ?></td>
                        <td><?= e(money($account['total'] ?? 0)) ?></td>
                        <td><span class="text-success fw-semibold"><?= e(money($account['pagado'] ?? 0)) ?></span></td>
                        <td><span class="text-danger fw-semibold"><?= e(money($account['saldo'] ?? 0)) ?></span></td>
                        <td><?= e((string) ($account['dias_cartera'] ?? 0)) ?></td>
                        <td><span class="badge text-bg-light"><?= e((string) ($account['rango_antiguedad'] ?? '0-30')) ?></span></td>
                        <td>
                            <?php $estadoCobro = (string) ($account['estado_cobro'] ?? 'pendiente'); ?>
                            <span class="badge <?= $estadoCobro === 'parcial' ? 'text-bg-warning' : 'text-bg-danger' ?>">
                                <?= e($estadoCobro) ?>
                            </span>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collectForm<?= e((string) $account['id']) ?>">
                                Registrar abono
                            </button>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="11" class="bg-light">
                            <div class="collapse" id="collectForm<?= e((string) $account['id']) ?>">
                                <form action="<?= e(url('cuentas-cobrar/' . $account['id'] . '/abonar')) ?>" method="post" class="row g-2 p-2">
                                    <?= csrf_field() ?>
                                    <div class="col-md-2">
                                        <label class="form-label">Monto</label>
                                        <input
                                            type="number"
                                            step="0.01"
                                            min="0.01"
                                            max="<?= e((string) ($account['saldo'] ?? 0)) ?>"
                                            class="form-control"
                                            name="monto"
                                            value="<?= e(number_format((float) ($account['saldo'] ?? 0), 2, '.', '')) ?>"
                                            required
                                        >
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Metodo</label>
                                        <select class="form-select" name="metodo_pago" required>
                                            <option value="efectivo">Efectivo</option>
                                            <option value="tarjeta">Tarjeta</option>
                                            <option value="transferencia">Transferencia</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Referencia</label>
                                        <input class="form-control" name="referencia" placeholder="Comprobante, banco, etc.">
                                    </div>
                                    <div class="col-md-4 d-flex align-items-end">
                                        <button class="btn btn-primary w-100" type="submit">Guardar abono</button>
                                    </div>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h2 class="h5 mb-3">Abonos recientes</h2>
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>ID pago</th>
                    <th>Venta</th>
                    <th>Cliente</th>
                    <th>Fecha</th>
                    <th>Metodo</th>
                    <th>Referencia</th>
                    <th>Monto</th>
                </tr>
                </thead>
                <tbody>
                <?php if ($payments === []): ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">Sin abonos registrados.</td>
                    </tr>
                <?php endif; ?>
                <?php foreach ($payments as $payment): ?>
                    <tr>
                        <td><?= e((string) $payment['id']) ?></td>
                        <td>#<?= e((string) $payment['venta_id']) ?></td>
                        <td><?= e($payment['cliente'] ?? 'Consumidor final') ?></td>
                        <td><?= e($payment['fecha_pago'] ?? '') ?></td>
                        <td><?= e($payment['metodo_pago'] ?? '') ?></td>
                        <td><?= e($payment['referencia'] ?? '') ?></td>
                        <td class="text-success fw-semibold"><?= e(money($payment['monto'] ?? 0)) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
