<?= $this->extend('layouts/main_layout') ?>
<?= $this->section('content') ?>

<div class="flex items-center justify-between mb-6">
    <h2 class="text-2xl font-bold text-gray-900"><i class="bi bi-cart3 text-2xl"></i> Ventas</h2>
    <div class="flex items-center gap-2">
        <div class="inline-flex rounded-lg overflow-hidden border border-gray-200">
            <a href="<?= site_url('sales') ?>" class="px-4 py-2 text-sm no-underline inline-flex items-center gap-2 <?= $showToday ? 'bg-emerald-600 text-white' : 'bg-emerald-300 text-gray-600 hover:bg-gray-50' ?>">
                <i class="bi bi-calendar3"></i> Hoy
            </a>
            <a href="<?= site_url('sales?periodo=todas') ?>" class="px-4 py-2 text-sm no-underline inline-flex items-center gap-2 border-l border-gray-200 <?= !$showToday ? 'bg-emerald-600 text-white' : 'bg-emerald-300 text-gray-600 hover:bg-gray-50' ?>">
                <i class="bi bi-calendar3"></i> Todas
            </a>
        </div>
        <a href="<?= site_url('sales/create') ?>" class="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-lg no-underline inline-flex items-center gap-2 shadow-sm transition">
            <i class="bi bi-plus-circle"></i> Nueva Venta
        </a>
    </div>
</div>

<div class="grid grid-cols-1 <?= session()->get('role') == 'admin' ? 'md:grid-cols-3' : '' ?> gap-5 mb-6">
    <div class="bg-emerald-300 rounded-xl shadow-sm border-l-4 border-emerald-500 p-5">
        <div class="flex justify-between items-start">
            <div>
                <p class="text-gray-500 text-xs font-semibold uppercase tracking-wide mb-1">Ventas del Dia</p>
                <h3 class="text-2xl font-extrabold text-gray-900 tracking-tight">S/ <?= number_format($totalVentasHoy, 2) ?></h3>
                <p class="text-gray-400 text-xs mt-1"><?= date('d/m/Y') ?></p>
            </div>
            <div class="w-12 h-12 bg-emerald-400 rounded-xl flex items-center justify-center">
                <i class="bi bi-cart-check text-xl text-emerald-700"></i>
            </div>
        </div>
    </div>
    <?php if (session()->get('role') == 'admin'): ?>
    <div class="bg-rose-300 rounded-xl shadow-sm border-l-4 border-rose-600 p-5"><div class="flex justify-between items-start"><div><p class="text-gray-500 text-xs font-semibold uppercase tracking-wide mb-1">Total Acumulado</p>
                <h3 class="text-2xl font-extrabold text-gray-900 tracking-tight">S/ <?= number_format($totalVentas, 2) ?></h3>
                <p class="text-gray-400 text-xs mt-1">Historial completo</p>
            </div>
            <div class="w-12 h-12 bg-emerald-400 rounded-xl flex items-center justify-center">
                <i class="bi bi-clock-history text-xl text-emerald-700"></i>
            </div>
        </div>
    </div>
    <div class="bg-violet-300 rounded-xl shadow-sm border-l-4 border-violet-600 p-5"><div class="flex justify-between items-start"><div><p class="text-gray-500 text-xs font-semibold uppercase tracking-wide mb-1">Ganancia Total</p>
                <h3 class="text-2xl font-extrabold text-gray-900 tracking-tight">S/ <?= number_format($totalGanancias, 2) ?></h3>
                <p class="text-gray-400 text-xs mt-1">Ganancia acumulada</p>
            </div>
            <div class="w-12 h-12 bg-emerald-400 rounded-xl flex items-center justify-center">
                <i class="bi bi-bar-chart-line text-xl text-emerald-700"></i>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php if ($showToday): ?>
<div class="bg-rose-50 border border-rose-200 text-rose-800 p-4 rounded-lg mb-6 flex items-center gap-3 text-sm">
    <i class="bi bi-calendar3 text-rose-700"></i>
    Mostrando <strong>ventas del dia de hoy</strong> (<?= date('d/m/Y') ?>)
    <a href="<?= site_url('sales?periodo=todas') ?>" class="text-rose-700 ml-auto font-medium whitespace-nowrap no-underline hover:underline">Ver todas &rarr;</a>
</div>
<?php endif; ?>

<div class="bg-emerald-100 rounded-xl shadow-sm border border-gray-100 overflow-hidden mb-6">
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="bg-gray-50">
                    <th class="text-left px-4 py-3 text-gray-500 text-xs uppercase tracking-wider font-semibold"># Ticket</th>
                    <th class="text-left px-4 py-3 text-gray-500 text-xs uppercase tracking-wider font-semibold">Fecha</th>
                    <th class="text-left px-4 py-3 text-gray-500 text-xs uppercase tracking-wider font-semibold">Usuario</th>
                    <th class="text-left px-4 py-3 text-gray-500 text-xs uppercase tracking-wider font-semibold">Productos</th>
                    <th class="text-right px-4 py-3 text-gray-500 text-xs uppercase tracking-wider font-semibold">Total</th>
                    <th class="text-left px-4 py-3 text-gray-500 text-xs uppercase tracking-wider font-semibold">Observaciones</th>
                    <th class="text-center px-4 py-3 text-gray-500 text-xs uppercase tracking-wider font-semibold">Accion</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
                <?php if (empty($sales)): ?>
                <tr>
                    <td colspan="7" class="text-center text-gray-400 py-8">
                        <i class="bi bi-inbox text-3xl block mb-2 mx-auto"></i>
                        No hay ventas registradas
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($sales as $sale): ?>
                <tr class="hover:bg-gray-50 transition-colors">
                    <td class="px-4 py-3"><span class="bg-emerald-100 text-emerald-700 rounded-lg px-2.5 py-1 text-xs font-semibold">#<?= $sale['id_venta'] ?></span></td>
                    <td class="px-4 py-3 text-gray-600"><?= date('d/m/Y H:i', strtotime($sale['fecha'])) ?></td>
                    <td class="px-4 py-3 text-gray-600"><?= $sale['username'] ?></td>
                    <td class="px-4 py-3 text-xs text-gray-600"><?= esc($sale['productos'] ?? 'Ninguno') ?></td>
                    <td class="px-4 py-3 text-right font-black tracking-tight text-gray-900">S/ <?= number_format($sale['total'], 2) ?></td>
                    <td class="px-4 py-3 text-gray-600"><?= $sale['observaciones'] ?? '-' ?></td>
                    <td class="px-4 py-3">
                        <div class="flex items-center justify-center gap-1">
                            <a href="<?= site_url('sales/' . $sale['id_venta']) ?>" class="bg-emerald-300 border border-gray-200 rounded-lg px-2 py-1 text-xs transition hover:bg-gray-50 text-gray-600 no-underline inline-flex items-center gap-1" title="Ver">
                                <i class="bi bi-eye"></i>
                            </a>
                            <?php if (session()->get('role') == 'admin' || session()->get('role') == 'vendedor'): ?>
                            <a href="<?= site_url('sales/' . $sale['id_venta'] . '/edit') ?>" class="bg-emerald-300 border border-gray-200 rounded-lg px-2 py-1 text-xs transition hover:bg-gray-50 text-gray-600 no-underline inline-flex items-center gap-1" title="Editar">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <a href="#" onclick="confirmDelete(<?= $sale['id_venta'] ?>)" class="bg-emerald-300 border border-gray-200 rounded-lg px-2 py-1 text-xs transition hover:bg-gray-50 text-gray-600 no-underline inline-flex items-center gap-1" title="Eliminar">
                                <i class="bi bi-trash3"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="bg-emerald-100 rounded-xl shadow-sm border border-gray-100 overflow-hidden">
    <div class="flex items-center justify-between px-5 py-3 border-b border-gray-100">
        <h5 class="font-semibold text-gray-900 flex items-center gap-2"><i class="bi bi-clock-history text-emerald-600"></i> Historial de Eliminaciones</h5>
        <span class="bg-emerald-100 text-emerald-700 rounded-lg px-2.5 py-1 text-xs font-semibold"><?= count($deletionBackups) ?></span>
    </div>
    <div class="overflow-x-auto" style="max-height: 300px; overflow-y: auto;">
        <table class="w-full text-sm">
            <thead class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider font-semibold sticky top-0">
                <tr>
                    <th class="text-left px-4 py-2">Fecha</th>
                    <th class="text-left px-4 py-2">Eliminado por</th>
                    <th class="text-left px-4 py-2">Producto</th>
                    <th class="text-center px-4 py-2">Cant. Devuelta</th>
                    <th class="text-center px-4 py-2">Venta #</th>
                    <?php if (session()->get('role') == 'admin'): ?>
                    <th class="text-center px-4 py-2">Accion</th>
                    <?php endif; ?>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
                <?php if (empty($deletionBackups)): ?>
                <tr>
                    <td colspan="6" class="text-center text-gray-400 py-4">No hay eliminaciones disponibles para restaurar</td>
                </tr>
                <?php else: ?>
                <?php foreach ($deletionBackups as $h): ?>
                <tr class="hover:bg-gray-50">
                    <td class="px-4 py-2 text-xs"><?= date('d/m/Y H:i', strtotime($h['fecha'])) ?></td>
                    <td class="px-4 py-2"><span class="bg-rose-100 text-rose-700 rounded-lg px-2.5 py-1 text-xs font-semibold"><?= esc($h['username']) ?></span></td>
                    <td class="px-4 py-2 text-xs text-gray-600"><?= esc($h['producto_nombre']) ?> (<?= esc($h['codigo_unico']) ?>)</td>
                    <td class="px-4 py-2 text-center"><span class="bg-emerald-100 text-emerald-700 rounded-lg px-2.5 py-1 text-xs font-semibold">+<?= $h['cantidad'] ?></span></td>
                    <td class="px-4 py-2 text-center"><span class="bg-rose-100 text-rose-700 rounded-lg px-2.5 py-1 text-xs font-semibold">#<?= $h['backup_data']['venta_id'] ?></span></td>
                    <?php if (session()->get('role') == 'admin'): ?>
                    <td class="px-4 py-2 text-center">
                        <form method="post" action="<?= site_url('sales/restore/' . $h['id_movimiento']) ?>">
                            <?= csrf_field() ?>
                            <button type="button" class="bg-teal-600 hover:bg-teal-700 text-white px-3 py-1.5 rounded-lg text-xs font-medium border-0 cursor-pointer inline-flex items-center gap-1 shadow-sm transition" onclick="confirmRestore(this)">
                                <i class="bi bi-arrow-counterclockwise"></i> Restaurar
                            </button>
                        </form>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
async function confirmRestore(btn) {
    const result = await Swal.fire({ icon: 'question', title: '¿Restaurar esta venta?', text: 'Se ajustará el stock.', showCancelButton: true, confirmButtonText: 'Sí, restaurar', cancelButtonText: 'Cancelar' });
    if (result.isConfirmed) btn.closest('form').submit();
}
async function confirmDelete(id) {
    const result = await Swal.fire({ icon: 'question', title: '¿Está seguro?', text: 'Se restaurará el stock.', showCancelButton: true, confirmButtonText: 'Sí, eliminar', cancelButtonText: 'Cancelar' });
    if (result.isConfirmed) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = '<?= site_url('sales') ?>/' + id;
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = '_method';
        input.value = 'DELETE';
        form.appendChild(input);
        document.body.appendChild(form);
        form.submit();
    }
}
<?php if (session()->getFlashdata('ticket_sale_id')): ?>
document.addEventListener('DOMContentLoaded', async function() {
    var saleId = <?= session()->getFlashdata('ticket_sale_id') ?>;
    var resp = await fetch('<?= site_url('sales') ?>/' + saleId + '/ticket-content');
    var html = await resp.text();
    Swal.fire({
        html: '<div style="overflow-y:auto;max-height:70vh;">' + html + '</div>' +
              '<button id="printTicketBtn" class="bg-teal-600 hover:bg-teal-700 text-white px-6 py-2.5 rounded-lg text-sm font-medium inline-flex items-center gap-2 border-0 cursor-pointer mt-3" onclick="printTicketContent()">' +
              '<i class="bi bi-printer"></i> Imprimir Ticket</button>',
        showConfirmButton: false,
        showCloseButton: true,
        width: 380,
        background: '#fff',
        customClass: { popup: 'rounded-3xl' }
    });
});
function printTicketContent() {
    var content = document.querySelector('.swal2-popup .ticket-content');
    if (!content) return;
    var win = window.open('', '_blank');
    win.document.write('<!DOCTYPE html><html><head><title>Ticket</title>');
    win.document.write('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">');
    win.document.write('<style>');
    win.document.write('@media print { body { margin: 0; padding: 8px; } }');
    win.document.write('body { font-family: Courier New, monospace; font-size: 12px; margin: 0; padding: 16px; width: 80mm; background: #fff; color: #000; }');
    win.document.write('</style></head><body>');
    win.document.write(content.outerHTML);
    win.document.write('<script>window.print();<' + '/script>');
    win.document.write('</body></html>');
    win.document.close();
}
<?php endif; ?>
</script>

<?= $this->endSection() ?>