{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        clifford: '#da373d',
                    }
                }
            }
        }
    </script>
</head>

<body class="bg-white p-8 max-w-4xl mx-auto">
    <div class="mb-8">
        <div class="flex mb-6 space-x-2">
            <img src="{% static 'img/Logo2.png' %}" alt="Logo" class="h-10 w-auto">
            <h1 class="text-3xl font-bold text-amber-950 mb-6">Invoice</h1>
        </div>

        <!-- Invoice Details -->
        <div class="w-full flex flex-col md:flex-row justify-between gap-4 md:gap-6 mb-8 text-sm">
            <!-- Left Column -->
            <div class="w-full md:w-1/2 space-y-2">
                <p class="flex flex-wrap items-center text-gray-600">
                    <span class="font-semibold w-24">Invoice ID</span>
                    <span>: #{{ transaction.id }}</span>
                </p>
                <p class="flex flex-wrap items-center text-gray-600">
                    <span class="font-semibold w-24">Date</span>
                    <span>: {{ transaction.transaction_date }}</span>
                </p>
                <p class="flex flex-wrap items-center text-gray-600">
                    <span class="font-semibold w-24">Employee</span>
                    <span>: {{ transaction.employee.name }}</span>
                </p>
            </div>

            <!-- Right Column -->
            <div class="w-full md:w-1/2 space-y-2 md:text-right">
                <p class="flex flex-wrap items-center text-gray-600 md:justify-end">
                    <span class="w-full md:w-auto">{{ transaction.customer.name }}</span>
                </p>
                <p class="flex flex-wrap items-center text-gray-600 md:justify-end">
                    <span class="w-full md:w-auto break-words">{{ transaction.customer.address }}</span>
                </p>
                <p class="flex flex-wrap items-center text-gray-600 md:justify-end">
                    <span class="w-full md:w-auto">{{ transaction.customer.phone_number }}</span>
                </p>
            </div>
        </div>

        <!-- Invoice Table -->
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border border-gray-200">
                <thead>
                    <tr class="bg-gray-50">
                        <th
                            class="px-3 py-3 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            No
                        </th>
                        <th
                            class="px-6 py-3 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Name
                        </th>
                        <th
                            class="px-3 py-3 border-b text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Qty
                        </th>
                        <th
                            class="px-6 py-3 border-b text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Price
                        </th>
                        <th
                            class="px-6 py-3 border-b text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            Subtotal
                        </th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    {% for item in transaction_items %}
                    <tr class="hover:bg-gray-50">
                        <td class="px-3 py-3 text-sm text-gray-600">
                            {{ forloop.counter }}
                        </td>
                        <td class="px-6 py-3 text-sm text-gray-600 break-words">
                            <div class="truncate sm:whitespace-normal">
                                {{ item.product.name }}
                            </div>
                        </td>
                        <td class="px-3 py-3 text-right text-sm text-gray-600 whitespace-nowrap">
                            {{ item.qty }}
                        </td>
                        <td class="price px-6 py-3 text-right text-sm text-gray-600 whitespace-nowrap"
                            data-value="{{ item.unit_price|stringformat:'f' }}">
                            Rp {{ item.unit_price|floatformat:2 }}
                        </td>
                        <td class="subtotal px-6 py-3 text-right text-sm text-gray-600 whitespace-nowrap"
                            data-value="{{ item.subtotal|stringformat:'f' }}">
                            Rp {{ item.subtotal|floatformat:2 }}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
                <tfoot>
                    <tr class="bg-gray-50 border-t">
                        <td colspan="4" class="px-6 py-1 text-right text-sm font-semibold text-gray-700">
                            Total Payment:
                        </td>
                        <td id="total-amount" class="px-6 py-1 text-right text-sm font-semibold text-gray-700"
                            data-value="{{ transaction.total_amount }}">
                            Rp {{ transaction.total_amount|floatformat:2 }}
                        </td>
                    </tr>
                    <tr class="bg-gray-50">
                        <td colspan="4" class="px-6 py-1 text-right text-sm font-semibold text-gray-700">
                            Total Paid:
                        </td>
                        <td id="total-paid" class="px-6 py-1 text-right text-sm font-semibold text-gray-700"
                            data-value="{{ transaction.paid_amount }}">
                            Rp {{ transaction.paid_amount|floatformat:2 }}
                        </td>
                    </tr>
                    <tr class="bg-gray-50">
                        <td colspan="4" class="px-6 py-1 text-right text-sm font-semibold text-gray-700">
                            Total Change:
                        </td>
                        <td id="total-change" class="px-6 py-1 text-right text-sm font-semibold text-gray-700"
                            data-value="{{ transaction.change_amount }}">
                            Rp {{ transaction.change_amount|floatformat:2 }}
                        </td>
                    </tr>
                    <tr class="bg-gray-50">
                        <td colspan="4" class="px-6 py-1 text-right text-sm font-semibold text-gray-700">
                            Payment Status:
                        </td>
                        <td class="px-6 py-1 text-right text-sm font-semibold text-gray-700">
                            {{ transaction.status }}
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>


        <!-- Footer -->
        <div class="mt-8 text-center text-sm text-gray-500">
            <p>Thank you for your business!</p>
            <p class="mt-1">For any inquiries, please contact our customer service.</p>
        </div>
    </div>

    <!-- Print Button (optional) -->
    <div class="text-center mt-8 print:hidden">
        <button class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded"
            onclick="printInvoice('{{ transaction.id }}')">
            Print Invoice
        </button>
    </div>

    <script>
        function printInvoice(transactionId) {
            // Membuka halaman PDF baru berdasarkan URL yang ditentukan
            window.open(`/kasir/print-invoice/${transactionId}/pdf/`, '_blank');
        }

        // Fungsi Format Rupiah yang Lebih Robust
        function formatRupiah(amount) {
            // Konversi ke float dan handling untuk nilai null/undefined
            const number = parseFloat(amount);
            if (isNaN(number)) return "Rp 0,00";

            // Format angka dengan Intl.NumberFormat
            const formatter = new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });

            // Format dan bersihkan output yang tidak diinginkan
            return formatter.format(number)
                .replace(/IDR/g, 'Rp')
                .replace(/\s+/g, ' ')
                .trim();
        }

        // Fungsi untuk memformat semua elemen harga
        function formatAllPrices() {
            document.querySelectorAll('.price, .subtotal').forEach(function (element) {
                const value = element.getAttribute('data-value');
                if (value) {
                    element.textContent = formatRupiah(value);
                }
            });

            // Format total amount jika ada
            const totalAmountElement = document.getElementById('total-amount');
            if (totalAmountElement) {
                const totalAmount = totalAmountElement.getAttribute('data-value');
                if (totalAmount) {
                    totalAmountElement.textContent = formatRupiah(totalAmount);
                }
            }
            const totalPaidElement = document.getElementById('total-paid');
            if (totalPaidElement) {
                const totalPaid = totalPaidElement.getAttribute('data-value');
                if (totalPaid) {
                    totalPaidElement.textContent = formatRupiah(totalPaid);
                }
            }
            const totalChangeElement = document.getElementById('total-change');
            if (totalChangeElement) {
                const totalChange = totalChangeElement.getAttribute('data-value');
                if (totalChange) {
                    totalChangeElement.textContent = formatRupiah(totalChange);
                }
            }
        }

        // Jalankan format pertama kali
        document.addEventListener('DOMContentLoaded', formatAllPrices);

        // Observer untuk perubahan dinamis
        const observer = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'data-value') {
                    const element = mutation.target;
                    const value = element.getAttribute('data-value');
                    if (value) {
                        element.textContent = formatRupiah(value);
                    }
                }
            });
        });

        // Observe elements setelah DOM loaded
        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.price, .subtotal, #total-amount, #total-paid, #total-change').forEach(function (element) {
                observer.observe(element, {
                    attributes: true,
                    attributeFilter: ['data-value']
                });
            });
        });
    </script>
</body>

</html>