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

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

{% block head %}
<!--HEAD-->
{% 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;">
                {% if selected_date %}Día Seleccionado{% else %}Ventas de Hoy{% endif %}
            </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;">Últimos 7
                Días</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">
        <h4 class="mb-0"><i class="bi bi-receipt-cutoff me-2"></i>Historial</h4>
        <div class="d-flex align-items-center gap-2">
            <label for="date-filter" class="form-label mb-0 text-muted small d-none d-sm-block">Filtrar
                Día:</label>
            <input type="date" id="date-filter" class="form-control form-control-sm"
                style="background: var(--input-bg); color: var(--text-main); border-color: var(--border);"
                value="{{ selected_date or '' }}" onchange="filterByDate(this.value)">
            {% if selected_date %}
            <a href="/sales" class="btn btn-sm btn-outline-secondary" title="Limpiar filtro"><i
                    class="bi bi-x-lg"></i></a>
            {% endif %}
        </div>
    </div>
    <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>
</div>
</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-body">
            </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 filterByDate(dateVal) {
        if (dateVal) {
            window.location.href = `/sales?date=${dateVal}`;
        } else {
            window.location.href = `/sales`;
        }
    }

    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 %}