{% extends "macros/base.html" %}
{% from 'macros/modals.html' import confirm_modal, scanner_modal, render_receipt %}

{% block title %}Ventas{% endblock %}

{% block head %}
<style>
    /* Burn the ugly arrows */
    input[type="number"]::-webkit-inner-spin-button, 
    input[type="number"]::-webkit-outer-spin-button { 
        -webkit-appearance: none; 
        margin: 0; 
    }
    input[type="number"] {
        -moz-appearance: textfield;
    }
    
    /* Fix the weird focus line on the ticket input group */
    .ticket-group .input-group-text { border-right: none; }
    .ticket-group #ticket-filter { border-left: none; }
    .ticket-group #ticket-filter:focus {
        box-shadow: none;
        border-color: var(--border);
    }
</style>
{% endblock %}

{% block content %}
{{ render_receipt() }}

<div class="row g-3 mb-3">
    <div class="col-12 col-md-4">
        <div class="discord-card p-3 shadow-sm text-center">
            <h6 class="text-muted text-uppercase mb-1" style="font-size: 0.75rem; font-weight: 700;">Hoy</h6>
            <h2 class="price-cell mb-0" style="color: var(--accent); font-weight: 800;" data-value="{{ stats.daily }}"></h2>
        </div>
    </div>
    <div class="col-12 col-md-4">
        <div class="discord-card p-3 shadow-sm text-center">
            <h6 class="text-muted text-uppercase mb-1" style="font-size: 0.75rem; font-weight: 700;">Esta Semana</h6>
            <h2 class="price-cell mb-0" style="color: var(--accent); font-weight: 800;" data-value="{{ stats.week }}"></h2>
        </div>
    </div>
    <div class="col-12 col-md-4">
        <div class="discord-card p-3 shadow-sm text-center">
            <h6 class="text-muted text-uppercase mb-1" style="font-size: 0.75rem; font-weight: 700;">Este Mes</h6>
            <h2 class="price-cell mb-0" style="color: var(--accent); font-weight: 800;" data-value="{{ stats.month }}"></h2>
        </div>
    </div>
</div>

<div class="discord-card p-3 shadow-sm">
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h4 class="mb-0"><i class="bi bi-receipt-cutoff me-2"></i>Historial</h4>
        <div class="d-flex align-items-center gap-2 flex-wrap">
            
            <select id="payment-filter" class="form-select form-select-sm" onchange="applyFilters(1)"
                    style="width: auto; background: var(--input-bg); color: var(--text-main); border-color: var(--border);">
                <option value="">Cualquier Pago</option>
                <option value="efectivo" {% if selected_payment == 'efectivo' %}selected{% endif %}>Efectivo</option>
                <option value="tarjeta" {% if selected_payment == 'tarjeta' %}selected{% endif %}>Tarjeta</option>
                <option value="transferencia" {% if selected_payment == 'transferencia' %}selected{% endif %}>Transferencia</option>
            </select>

            <input type="date" id="date-filter" class="form-control form-control-sm"
                style="width: auto; background: var(--input-bg); color: var(--text-main); border-color: var(--border);"
                value="{{ selected_date or '' }}" onchange="applyFilters(1)">
            
            {% if selected_date or selected_payment %}
            <a href="/sales" class="btn btn-sm btn-outline-danger px-2" title="Limpiar filtros"><i class="bi bi-x-lg"></i></a>
            {% endif %}
        </div>
    </div>

    {% if selected_date or selected_payment or selected_ticket %}
    <div class="d-flex justify-content-between align-items-center mb-3 p-3 rounded shadow-sm" 
         style="background: rgba(var(--accent-rgb, 88, 101, 242), 0.1); border: 1px dashed var(--accent, #5865F2);">
        <div>
            <h6 class="mb-0 text-uppercase" style="font-size: 0.75rem; font-weight: 700; color: var(--accent, #5865F2);">
                <i class="bi bi-funnel-fill me-1"></i> Total Filtrado
            </h6>
            <small class="text-muted">{{ filtered_stats.count }} ventas encontradas</small>
        </div>
        <h3 class="price-cell mb-0" style="color: var(--accent, #5865F2); font-weight: 800;" data-value="{{ filtered_stats.total }}"></h3>
    </div>
    {% endif %}

    <div class="table-responsive">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Nº Ticket</th>
                    <th>Fecha y Hora</th>
                    <th>Método</th>
                    <th>Total</th>
                    <th class="text-nowrap" style="width: 1%;">Acciones</th>
                </tr>
            </thead>
            <tbody>
                {% for s in sales %}
                <tr>
                    <td class="font-monospace text-muted">#{{ s[0] }}</td>
                    <td class="utc-date">{{ s[1] }}</td>
                    <td class="text-capitalize">{{ s[3] }}</td>
                    <td class="price-cell fw-bold" data-value="{{ s[2] }}"></td>
                    <td class="text-nowrap">
                        <button class="btn btn-sm btn-outline-secondary py-0 px-2"
                                onclick="viewSale({{ s[0] }}, '{{ s[1] }}', {{ s[2] }})">
                            <i class="bi bi-eye"></i> <span class="d-none d-lg-inline">Ver Detalle</span>
                        </button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% if total_pages > 1 %}
    <nav aria-label="Navegación de páginas" class="mt-4">
        <ul class="pagination justify-content-center pagination-sm">
            <li class="page-item {% if current_page <= 1 %}disabled{% endif %}">
                <button class="page-link" onclick="applyFilters({{ current_page - 1 }})" style="background: var(--input-bg); color: var(--text-main); border-color: var(--border);">Anterior</button>
            </li>
            
            <li class="page-item disabled">
                <span class="page-link" style="background: var(--bg-main); color: var(--text-muted); border-color: var(--border);">
                    Página {{ current_page }} de {{ total_pages }}
                </span>
            </li>

            <li class="page-item {% if current_page >= total_pages %}disabled{% endif %}">
                <button class="page-link" onclick="applyFilters({{ current_page + 1 }})" style="background: var(--input-bg); color: var(--text-main); border-color: var(--border);">Siguiente</button>
            </li>
        </ul>
    </nav>
    {% endif %}
</div>

<div class="modal fade" id="receiptModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Detalle de Venta <span id="modal-ticket-id" class="text-muted small"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted small mb-2" id="modal-date"></p>
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Cant</th>
                            <th class="text-end">Subtotal</th>
                        </tr>
                    </thead>
                    <tbody id="receipt-items"></tbody>
                    <tfoot>
                        <tr>
                            <th colspan="2" class="text-end">TOTAL:</th>
                            <th class="text-end fs-5" id="modal-total" style="color: var(--accent);"></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div class="modal-footer d-flex justify-content-between border-0 pt-0">
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-danger btn-sm" id="btn-reverse-sale">
                        <i class="bi bi-arrow-counterclockwise me-1"></i>Anular Venta
                    </button>
                    <button class="btn btn-primary btn-sm" id="btn-print-modal">
                        <i class="bi bi-printer me-1"></i>Re-imprimir
                    </button>
                </div>
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="reverseConfirmModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-danger">
            <div class="modal-header pb-0 border-0">
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center pt-0 pb-4">
                <i class="bi bi-exclamation-triangle-fill text-danger mb-3" style="font-size: 3rem;"></i>
                <h4 class="mb-3">¿Anular Venta #<span id="reverse-modal-id"></span>?</h4>
                <p class="text-muted small px-3">Los productos regresarán automáticamente al inventario y el ticket
                    será eliminado permanentemente.</p>

                <div class="d-flex gap-2 justify-content-center mt-4 px-3">
                    <button class="btn btn-secondary w-50" data-bs-dismiss="modal">Cancelar</button>
                    <button class="btn btn-danger w-50" onclick="executeReverseSale()">Sí, Anular</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    const clp = new Intl.NumberFormat('es-CL', { style: 'currency', currency: 'CLP', minimumFractionDigits: 0 });
    let saleToReverse = null;

    // Format raw UTC dates from DB into friendly local time
    document.querySelectorAll('.utc-date').forEach(el => {
        const date = new Date(el.innerText + " UTC");
        if (!isNaN(date)) {
            el.innerText = date.toLocaleString('es-CL', {
                year: 'numeric', month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit'
            });
        }
    });

    // Format all prices
    document.querySelectorAll('.price-cell').forEach(td => {
        td.innerText = clp.format(td.getAttribute('data-value'));
    });

    async function viewSale(id, rawDate, total) {
        document.getElementById('modal-ticket-id').innerText = `#${id}`;
        document.getElementById('modal-total').innerText = clp.format(total);

        const localDate = new Date(rawDate + " UTC").toLocaleString('es-CL');
        document.getElementById('modal-date').innerText = localDate !== "Invalid Date" ? localDate : rawDate;

        // Configure the Anular button
        document.getElementById('btn-reverse-sale').setAttribute('onclick', `reverseSale(${id})`);
        
        // Configure the Print button
        document.getElementById('btn-print-modal').setAttribute('onclick', `reprintSale(${id}, ${total}, '${rawDate}')`);

        const tbody = document.getElementById('receipt-items');
        tbody.innerHTML = '<tr><td colspan="3" class="text-center text-muted">Cargando...</td></tr>';

        const modal = new bootstrap.Modal(document.getElementById('receiptModal'));
        modal.show();

        try {
            const res = await fetch(`/api/sale/${id}`);
            const items = await res.json();

            tbody.innerHTML = items.map(item => `
                <tr>
                    <td>
                        ${item.name}<br>
                        <small class="text-muted font-monospace" style="font-size: 0.7rem;">${item.barcode}</small>
                    </td>
                    <td>${item.qty}</td>
                    <td class="text-end">${clp.format(item.subtotal)}</td>
                </tr>
            `).join('');
        } catch (err) {
            tbody.innerHTML = '<tr><td colspan="3" class="text-center text-danger">Error cargando productos</td></tr>';
        }
    }

    async function reprintSale(id, total, rawDate) {
        const tbody = document.getElementById('receipt-items-print');
        
        try {
            const res = await fetch(`/api/sale/${id}`);
            const items = await res.json();

            tbody.innerHTML = items.map(item => `
                <tr>
                    <td>${item.qty}</td>
                    <td style="padding-left: 5px;">${item.name}</td>
                    <td style="text-align: right;">${clp.format(item.subtotal)}</td>
                </tr>
            `).join('');

            document.getElementById('receipt-ticket-id').innerText = id;
            document.getElementById('receipt-total-print').innerText = clp.format(total);
            document.getElementById('receipt-date').innerText = new Date(rawDate + " UTC").toLocaleString('es-CL');
            document.getElementById('receipt-payment-info').style.display = 'none';

            window.print();
        } catch (err) {
            console.error(err);
            alert("Error al preparar la impresión.");
        }
    }

    function applyFilters(page = 1) {
        const dateVal = document.getElementById('date-filter').value;
        const paymentVal = document.getElementById('payment-filter').value;

        const url = new URL(window.location.origin + '/sales');
        
        if (dateVal) url.searchParams.set('date', dateVal);
        if (paymentVal) url.searchParams.set('payment_method', paymentVal);
        if (page > 1) url.searchParams.set('page', page);

        window.location.href = url.toString();
    }

    function handleEnter(e) {
        if (e.key === 'Enter') applyFilters();
    }

    function reverseSale(id) {
        saleToReverse = id;
        document.getElementById('reverse-modal-id').innerText = id;

        // Hide the receipt modal so we don't have overlapping popups
        bootstrap.Modal.getInstance(document.getElementById('receiptModal')).hide();

        // Show the new confirmation modal
        const confirmModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('reverseConfirmModal'));
        confirmModal.show();
    }

    async function executeReverseSale() {
        if (!saleToReverse) return;

        try {
            const res = await fetch(`/api/sale/${saleToReverse}`, { method: 'DELETE' });

            if (res.ok) {
                window.location.reload(); // Refresh the dashboard
            } else {
                const data = await res.json();
                alert("Error anulando la venta: " + (data.error || "Desconocido"));
            }
        } catch (err) {
            console.error(err);
            alert("Error de conexión con el servidor.");
        }
    }
</script>
{% endblock %}