{% extends "base.html" %}
{% load static %}

{% block content %}
<div class="min-h-screen bg-gray-100 py-6">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900">
                Cashier
            </h1>
            <p class="mt-2 text-sm text-gray-700">
                Masukkan produk yang dibeli, lalu lengkapi transaksi dengan memilih karyawan, dan pelanggan.
            </p>
        </div>

        <!-- Cart -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <!-- Product List -->
            <div class="md:col-span-2">
                <div class="bg-white shadow rounded-lg p-6">
                    <h2 class="text-xl font-semibold mb-4">Cart Items</h2>

                    <div class="relative flex gap-4 py-4 mb-4">
                        <div class="relative flex-1"> <!-- Added container for input and dropdown -->
                            <input type="text" id="product-name"
                                class="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500"
                                placeholder="Enter product name" autocomplete="off" required>
                            <div id="product-list"
                                class="absolute left-0 right-0 mt-1 bg-white border rounded-lg shadow-lg hidden z-10 max-h-60 overflow-y-auto">
                                <!-- Dropdown akan diisi dengan hasil pencarian -->
                            </div>
                        </div>
                        <button id="add-product-btn" onclick="addProductFromDropdown()"
                            class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
                            Add Product
                        </button>
                    </div>

                    <div class="overflow-x-auto py-4">
                        <table class="w-full text-sm text-gray-850 py-4">
                            <thead class="text-sm uppercase">
                                <tr class="border-b">
                                    <th class="text-left p-2">Product</th>
                                    <th class="text-right p-2">Price</th>
                                    <th class="text-right p-2">Qty</th>
                                    <th class="text-right p-2">Subtotal</th>
                                    <th class="text-center p-2">Action</th>
                                </tr>
                            </thead>
                            <tbody id="cart-items">
                                <!-- Cart items will be inserted here -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="md:col-span-1 space-y-6">
                <!-- Transaction Section -->
                <div class="bg-white shadow rounded-lg p-6">
                    <h2 class="text-xl font-semibold mb-4">Transaction</h2>
                    <div class="space-y-4">
                        <!-- Tanggal -->
                        <div class="py-1 md:grid md:grid-cols-2 hover:bg-gray-50 md:space-y-0 space-y-1">
                            <label class="self-center text-gray-850">Tanggal </label>
                            <div class="relative z-0 w-full mb-5">
                                <!-- Wrapper div for relative positioning -->
                                <div
                                    class="pb-2 px-4 w-full bg-transparent border-0 border-b-2 appearance-none focus:outline-none focus:ring-0 focus:border-black border-gray-200 pr-8">
                                    <span class="text-gray-850" id="current-date"></span>
                                    <script>
                                        const currentDate = new Date();
                                        const formattedDate = currentDate.toLocaleDateString(); // Format lokal, seperti "12/01/2025" atau "1/12/2025"
                                        document.getElementById('current-date').textContent = formattedDate;
                                    </script>
                                </div>
                            </div>
                        </div>

                        <!-- Employee -->
                        <div id="autocomplete-employee"
                            class="py-1 md:grid md:grid-cols-2 hover:bg-gray-50 md:space-y-0 space-y-1">
                            <label for="employee" class="self-center text-gray-850">Employee</label>
                            <div class="relative z-20 w-full mb-5">
                                <input id="employee-input" type="text" list="employee-list" data-id=""
                                    class="px-4 block w-full bg-transparent border-0 border-b-2 appearance-none focus:outline-none focus:ring-0 focus:border-black border-gray-200"
                                    placeholder="Select employee" required>
                                <div id="employee-list"
                                    class="absolute z-20 w-full max-h-60 bg-white border border-gray-300 rounded-md shadow-md overflow-y-auto hidden">
                                    <!-- Options will be dynamically populated using JavaScript -->
                                </div>
                            </div>
                        </div>

                        <!-- Customer -->
                        <div id="autocomplete-customer"
                            class="py-1 md:grid md:grid-cols-2 hover:bg-gray-50 md:space-y-0 space-y-1">
                            <label for="customer" class="self-center text-gray-850">Customer</label>
                            <div class="relative z-0 w-full mb-5">
                                <input id="customer-input" type="text" list="customer-list" data-id=""
                                    class="px-4 block w-full bg-transparent border-0 border-b-2 appearance-none focus:outline-none focus:ring-0 focus:border-black border-gray-200"
                                    placeholder="Select customer" required>
                                <div id="customer-list"
                                    class="absolute z-10 w-full max-h-60 bg-white border border-gray-300 rounded-md shadow-md overflow-y-auto hidden">
                                    <!-- Options will be dynamically populated using JavaScript -->
                                </div>
                            </div>
                        </div>
                        <span class="text-sm text-gray-700">Customer tidak terdaftar? tambah <a href="#"
                                onclick="openModal()" class="text-blue-700 hover:text-blue-900 underline">di
                                sini</a></span>
                        <!-- Modal Customer -->
                        <div id="customerModal" class="fixed inset-0 flex items-center justify-center hidden z-50">
                            <!-- Backdrop -->
                            <div class="absolute inset-0 bg-black bg-opacity-50 backdrop-blur-sm"></div>

                            <!-- Modal Content -->
                            <div
                                class="relative bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all">
                                <div class="p-6">
                                    <!-- Header -->
                                    <div class="flex items-center justify-between mb-6">
                                        <h2 class="text-2xl font-semibold text-gray-800">Tambah Customer</h2>
                                        <button onclick="closeModal()"
                                            class="text-gray-400 hover:text-gray-600 transition-colors">
                                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                    d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                        </button>
                                    </div>

                                    <!-- Form -->
                                    <form id="customerForm" class="space-y-4">
                                        <!-- Nama -->
                                        <div class="space-y-1">
                                            <label for="name"
                                                class="block text-sm font-medium text-gray-700">Nama</label>
                                            <input type="text" id="name" name="name"
                                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                                                placeholder="Masukkan nama customer">
                                            <p id="nameError" class="hidden text-sm text-red-500 mt-1">Nama harus diisi
                                            </p>
                                        </div>

                                        <!-- Nomor Telepon -->
                                        <div class="space-y-1">
                                            <label for="phone_number"
                                                class="block text-sm font-medium text-gray-700">Nomor Telepon</label>
                                            <input type="tel" id="phone_number" name="phone_number"
                                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                                                placeholder="Masukkan nomor telepon">
                                            <p id="phoneError" class="hidden text-sm text-red-500 mt-1">Nomor telepon
                                                harus diisi</p>
                                        </div>

                                        <!-- Email -->
                                        <div class="space-y-1">
                                            <label for="email"
                                                class="block text-sm font-medium text-gray-700">Email</label>
                                            <input type="email" id="email" name="email"
                                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                                                placeholder="Masukkan email">
                                        </div>

                                        <!-- Alamat -->
                                        <div class="space-y-1">
                                            <label for="address"
                                                class="block text-sm font-medium text-gray-700">Alamat</label>
                                            <textarea id="address" name="address" rows="3"
                                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                                                placeholder="Masukkan alamat"></textarea>
                                        </div>

                                        <!-- Buttons -->
                                        <div class="flex justify-end space-x-3 pt-4">
                                            <button type="button" onclick="closeModal()"
                                                class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 transition-all">
                                                Batal
                                            </button>
                                            <button type="submit"
                                                class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all">
                                                Simpan
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Script untuk menambahkan customer -->
                        <script>
                            function openModal() {
                                const modal = document.getElementById('customerModal');
                                modal.classList.remove('hidden');
                                document.body.style.overflow = 'hidden';
                            }

                            function closeModal() {
                                const modal = document.getElementById('customerModal');
                                modal.classList.add('hidden');
                                document.body.style.overflow = 'auto';

                                // Reset form and errors
                                document.getElementById('customerForm').reset();
                                document.querySelectorAll('.text-red-500').forEach(el => el.classList.add('hidden'));
                            }

                            document.getElementById("customerForm").addEventListener("submit", async function (e) {
                                e.preventDefault();

                                // Reset previous errors
                                document.querySelectorAll('.text-red-500').forEach(el => el.classList.add('hidden'));

                                // Validate required fields
                                let isValid = true;
                                const name = document.getElementById('name').value.trim();
                                const phoneNumber = document.getElementById('phone_number').value.trim();

                                if (name === '') {
                                    document.getElementById('nameError').classList.remove('hidden');
                                    isValid = false;
                                }

                                if (phoneNumber === '') {
                                    document.getElementById('phoneError').classList.remove('hidden');
                                    isValid = false;
                                }

                                if (!isValid) return;

                                try {
                                    const formData = new FormData(this);
                                    const response = await fetch("/kasir/add_customer/", {
                                        method: "POST",
                                        body: formData,
                                        headers: { 'X-CSRFToken': '{{ csrf_token }}' }
                                    });

                                    const result = await response.json();

                                    if (result.success) {
                                        // Show success message using a toast or inline notification instead of alert
                                        const notification = document.createElement('div');
                                        notification.className = 'fixed bottom-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg transform transition-all';
                                        notification.textContent = 'Customer berhasil ditambahkan!';
                                        document.body.appendChild(notification);

                                        // Remove notification after 3 seconds
                                        setTimeout(() => {
                                            notification.remove();
                                        }, 3000);

                                        this.reset();
                                        closeModal();
                                    } else {
                                        throw new Error(result.message);
                                    }
                                } catch (error) {
                                    console.error('Error:', error);
                                    // Show error message
                                    const notification = document.createElement('div');
                                    notification.className = 'fixed bottom-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg';
                                    notification.textContent = 'Terjadi kesalahan. Silakan coba lagi.';
                                    document.body.appendChild(notification);

                                    setTimeout(() => {
                                        notification.remove();
                                    }, 3000);
                                }
                            });
                        </script>
                    </div>
                </div>

                <!-- Payment Section -->
                <div class="bg-white shadow rounded-lg p-6">
                    <h2 class="text-xl font-semibold mb-4">Payment</h2>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Total</label>
                            <div id="total-amount" class="text-3xl font-bold">Rp 0</div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Payment Method</label>
                            <select id="payment-method" class="w-full p-2 border rounded">
                                <option value="CASH">Cash</option>
                                <option value="CARD">Card</option>
                                <option value="TRANSFER">Transfer</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Payment Status</label>
                            <select id="payment-status" class="w-full p-2 border rounded">
                                <option value="COMPLETED">Completed</option>
                                <option value="PENDING">Pending</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Paid Amount</label>
                            <input type="number" id="paid-amount" class="w-full p-2 border rounded" required
                                onchange="calculateChange()">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700">Change</label>
                            <div id="change-amount" class="text-2xl font-semibold">Rp 0</div>
                        </div>

                        <button onclick="saveTransaction()"
                            class="w-full bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
                            Complete Transaction
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!--Sweetalert-->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert2/11.10.5/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert2/11.10.5/sweetalert2.min.css">

<!-- autocomplete employee list -->
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const employeeInput = document.getElementById("employee-input");
        const employeeList = document.getElementById("employee-list");
        let selectedIndex = -1;
        let dropdownItems = [];

        employeeInput.addEventListener("input", function () {
            const query = employeeInput.value.trim();
            if (query.length > 0) {
                fetch(`/kasir/search-employees/?query=${query}`)
                    .then(response => response.json())
                    .then(data => {
                        employeeList.innerHTML = "";
                        dropdownItems = [];
                        selectedIndex = -1;

                        if (data.length > 0) {
                            data.forEach((employee, index) => {
                                const option = document.createElement("div");
                                option.textContent = employee.name;
                                option.className = "cursor-pointer px-4 py-2 hover:bg-gray-100";
                                option.dataset.id = employee.id;
                                option.dataset.index = index;

                                option.addEventListener("click", function () {
                                    selectEmployee(employee, option);
                                });

                                employeeList.appendChild(option);
                                dropdownItems.push(option);
                            });
                        } else {
                            const noResult = document.createElement("div");
                            noResult.textContent = "No results found...";
                            noResult.className = "px-4 py-2 text-gray-500";
                            employeeList.appendChild(noResult);
                        }
                        employeeList.classList.remove("hidden");
                    })
                    .catch(error => console.error("Error fetching employee data:", error));
            } else {
                employeeList.innerHTML = "";
                employeeList.classList.add("hidden");
                dropdownItems = [];
                selectedIndex = -1;
            }
        });

        // Keyboard navigation
        employeeInput.addEventListener("keydown", function (e) {
            if (!dropdownItems.length) return;

            switch (e.key) {
                case "ArrowDown":
                    e.preventDefault();
                    selectedIndex = Math.min(selectedIndex + 1, dropdownItems.length - 1);
                    updateHighlight();
                    break;

                case "ArrowUp":
                    e.preventDefault();
                    selectedIndex = Math.max(selectedIndex - 1, 0);
                    updateHighlight();
                    break;

                case "Enter":
                    e.preventDefault();
                    if (selectedIndex >= 0 && selectedIndex < dropdownItems.length) {
                        const selectedOption = dropdownItems[selectedIndex];
                        const employee = {
                            id: selectedOption.dataset.id,
                            name: selectedOption.textContent
                        };
                        selectEmployee(employee, selectedOption);
                    }
                    break;

                case "Escape":
                    e.preventDefault();
                    employeeList.classList.add("hidden");
                    selectedIndex = -1;
                    break;
            }
        });

        function updateHighlight() {
            dropdownItems.forEach((item, index) => {
                if (index === selectedIndex) {
                    item.classList.add("bg-gray-100");
                    // Ensure the selected item is visible in the dropdown
                    item.scrollIntoView({ block: "nearest" });
                } else {
                    item.classList.remove("bg-gray-100");
                }
            });
        }

        function selectEmployee(employee, option) {
            employeeInput.value = employee.name;
            employeeInput.dataset.id = employee.id;
            employeeList.classList.add("hidden");
            selectedIndex = parseInt(option.dataset.index);
        }

        // Close dropdown when clicking outside
        document.addEventListener("click", function (event) {
            if (!employeeInput.contains(event.target) && !employeeList.contains(event.target)) {
                employeeList.classList.add("hidden");
                selectedIndex = -1;
            }
        });
    });
</script>

<!-- autocomplete customer list -->
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const customerInput = document.getElementById("customer-input");
        const customerList = document.getElementById("customer-list");
        let selectedIndex = -1;
        let dropdownItems = [];

        // Event listener untuk input
        customerInput.addEventListener("input", function () {
            const query = customerInput.value.trim();
            // Jika input tidak kosong, lakukan pencarian
            if (query.length > 0) {
                // AJAX request untuk mendapatkan hasil pencarian
                fetch(`/kasir/search-customers/?query=${query}`)
                    .then(response => response.json())
                    .then(data => {
                        customerList.innerHTML = ""; // Kosongkan daftar sebelumnya
                        dropdownItems = [];
                        selectedIndex = -1;

                        if (data.length > 0) {
                            // Tambahkan hasil pencarian ke dropdown
                            data.forEach((customer, index) => {
                                const option = document.createElement("div");
                                option.textContent = customer.name;
                                option.className =
                                    "cursor-pointer px-4 py-2 hover:bg-gray-100";
                                option.dataset.id = customer.id;
                                option.dataset.index = index;

                                // Event listener untuk memilih item
                                option.addEventListener("click", function () {
                                    selectCustomer(customer, option);
                                });

                                customerList.appendChild(option);
                                dropdownItems.push(option);
                            });
                        } else {
                            // Jika tidak ada hasil
                            const noResult = document.createElement("div");
                            noResult.textContent = "No results found...";
                            noResult.className = "px-4 py-2 text-gray-500";
                            customerList.appendChild(noResult);
                        }
                        customerList.classList.remove("hidden"); // Tampilkan dropdown
                    })
                    .catch(error => console.error("Error fetching customer data:", error));
            } else {
                customerList.innerHTML = ""; // Kosongkan dropdown jika input kosong
                customerList.classList.add("hidden"); // Sembunyikan dropdown
                dropdownItems = [];
                selectedIndex = -1;
            }
        });

        // Keyboard navigation
        customerInput.addEventListener("keydown", function (e) {
            if (!dropdownItems.length) return;

            switch (e.key) {
                case "ArrowDown":
                    e.preventDefault();
                    selectedIndex = Math.min(selectedIndex + 1, dropdownItems.length - 1);
                    updateHighlight();
                    break;

                case "ArrowUp":
                    e.preventDefault();
                    selectedIndex = Math.max(selectedIndex - 1, 0);
                    updateHighlight();
                    break;

                case "Enter":
                    e.preventDefault();
                    if (selectedIndex >= 0 && selectedIndex < dropdownItems.length) {
                        const selectedOption = dropdownItems[selectedIndex];
                        const customer = {
                            id: selectedOption.dataset.id,
                            name: selectedOption.textContent
                        };
                        selectCustomer(customer, selectedOption);
                    }
                    break;

                case "Escape":
                    e.preventDefault();
                    employeeList.classList.add("hidden");
                    selectedIndex = -1;
                    break;
            }
        });

        function updateHighlight() {
            dropdownItems.forEach((item, index) => {
                if (index === selectedIndex) {
                    item.classList.add("bg-gray-100");
                    // Ensure the selected item is visible in the dropdown
                    item.scrollIntoView({ block: "nearest" });
                } else {
                    item.classList.remove("bg-gray-100");
                }
            });
        }

        function selectCustomer(customer, option) {
            customerInput.value = customer.name;
            customerInput.dataset.id = customer.id;
            customerList.classList.add("hidden");
            selectedIndex = parseInt(option.dataset.index);
        }


        // Event listener untuk menyembunyikan dropdown jika klik di luar
        document.addEventListener("click", function (event) {
            if (!customerInput.contains(event.target) && !customerList.contains(event.target)) {
                customerList.classList.add("hidden");
                selectedIndex = -1;
            }
        });
    });
</script>

<!-- Main script for transaction-->
<script>
    let cart = [];
    let selectedProduct = null; // Variabel untuk menyimpan data produk yang dipilih

    function formatCurrency(amount) {
        return new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR'
        }).format(amount);
    }

    document.addEventListener("DOMContentLoaded", function () {
        const productInput = document.getElementById("product-name");
        const productList = document.getElementById("product-list");
        let selectedIndex = -1;
        let dropdownItems = [];

        productInput.addEventListener("input", function () {
            const query = productInput.value.trim();
            if (query.length > 0) {
                fetch(`/kasir/search-products/?query=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        productList.innerHTML = "";
                        dropdownItems = [];
                        selectedIndex = -1;

                        if (data.length > 0) {
                            data.forEach((product, index) => {
                                const option = document.createElement("div");
                                option.textContent = `${product.name} (Stock: ${product.stock})`;
                                option.className = "cursor-pointer px-4 py-2 hover:bg-gray-100";
                                option.dataset.product = JSON.stringify(product);
                                option.dataset.index = index;

                                option.addEventListener("click", function () {
                                    selectProduct(product, option);
                                });

                                productList.appendChild(option);
                                dropdownItems.push(option);
                            });
                        } else {
                            const noResult = document.createElement("div");
                            noResult.textContent = "No results found...";
                            noResult.className = "px-4 py-2 text-gray-500";
                            productList.appendChild(noResult);
                        }
                        productList.classList.remove("hidden");
                    })
                    .catch(error => console.error("Error fetching product data:", error));
            } else {
                productList.innerHTML = "";
                productList.classList.add("hidden");
                dropdownItems = [];
                selectedIndex = -1;
            }
        });

        // Keyboard navigation
        productInput.addEventListener("keydown", function (e) {
            if (!dropdownItems.length) return;

            switch (e.key) {
                case "ArrowDown":
                    e.preventDefault();
                    selectedIndex = Math.min(selectedIndex + 1, dropdownItems.length - 1);
                    updateHighlight();
                    break;

                case "ArrowUp":
                    e.preventDefault();
                    selectedIndex = Math.max(selectedIndex - 1, 0);
                    updateHighlight();
                    break;

                case "Enter":
                    e.preventDefault();
                    if (selectedIndex >= 0 && selectedIndex < dropdownItems.length) {
                        const selectedOption = dropdownItems[selectedIndex];
                        const product = JSON.parse(selectedOption.dataset.product);
                        selectProduct(product, selectedOption);
                        addProductFromDropdown();
                    }
                    break;

                case "Escape":
                    e.preventDefault();
                    productList.classList.add("hidden");
                    selectedIndex = -1;
                    break;
            }
        });

        function updateHighlight() {
            dropdownItems.forEach((item, index) => {
                if (index === selectedIndex) {
                    item.classList.add("bg-gray-100");
                    // Ensure the selected item is visible in the dropdown
                    item.scrollIntoView({ block: "nearest" });
                } else {
                    item.classList.remove("bg-gray-100");
                }
            });
        }

        function selectProduct(product, option) {
            selectedProduct = product;
            productInput.value = product.name;
            productList.classList.add("hidden");
            selectedIndex = parseInt(option.dataset.index);
        }

        // Close dropdown when clicking outside
        document.addEventListener("click", function (event) {
            if (!productInput.contains(event.target) && !productList.contains(event.target)) {
                productList.classList.add("hidden");
                selectedIndex = -1;
            }
        });
    });

    // Fungsi untuk menambahkan produk ke keranjang
    function addProductFromDropdown() {
        // Konfigurasi SweetAlert mixin untuk notifikasi
        const Toast = Swal.mixin({
            toast: true,
            position: "top-end",
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.onmouseenter = Swal.stopTimer;
                toast.onmouseleave = Swal.resumeTimer;
            }
        });

        if (!selectedProduct) {
            Toast.fire({
                icon: 'warning',
                title: 'Please enter and select a product from the dropdown first.',
                customClass: {
                    popup: 'bg-red-500 text-white',
                    title: 'text-white font-semibold',
                    htmlContainer: 'text-white',
                    icon: 'text-white'
                },
                didOpen: (popup) => {
                    // Tambahkan gaya langsung untuk memastikan latar belakang merah
                    popup.style.backgroundColor = 'rgb(220 38 38 / var(--tw-text-opacity, 10))';
                    popup.style.color = 'white'; // Teks putih
                }
            });
            return;
            return;
        }

        // Tambahkan produk yang dipilih ke keranjang
        addToCart(selectedProduct);

        // Reset input dan variabel
        const productInput = document.getElementById("product-name");
        productInput.value = "";
        selectedProduct = null;
    }

    function addToCart(product) {
        // Konfigurasi SweetAlert mixin untuk notifikasi
        const Toast = Swal.mixin({
            toast: true,
            position: "top-end",
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.onmouseenter = Swal.stopTimer;
                toast.onmouseleave = Swal.resumeTimer;
            }
        });

        const existingItem = cart.find(item => item.product_number === product.product_number);

        if (existingItem) {
            if (existingItem.quantity + 1 <= product.stock) {
                existingItem.quantity += 1;
                existingItem.subtotal = existingItem.quantity * existingItem.price;
            } else {
                Toast.fire({
                    icon: 'warning',
                    title: `Cannot add more items. Available stock: ${product.stock}`,
                    customClass: {
                        popup: 'bg-red-500 text-white',
                        title: 'text-white font-semibold',
                        htmlContainer: 'text-white',
                        icon: 'text-white'
                    },
                    didOpen: (popup) => {
                        // Tambahkan gaya langsung untuk memastikan latar belakang merah
                        popup.style.backgroundColor = 'rgb(220 38 38 / var(--tw-text-opacity, 10))';
                        popup.style.color = 'white'; // Teks putih
                    }
                });
                return;
            }
        } else {
            cart.push({
                product_number: product.product_number,
                name: product.name,
                price: parseFloat(product.price),
                quantity: 1,
                subtotal: parseFloat(product.price),
                stock: product.stock
            });
        }

        updateCartDisplay();
    }

    function updateQuantity(index, change) {
        const item = cart[index];
        const newQuantity = item.quantity + change;

        if (change < 0) {
            if (newQuantity < 1) {
                cart.splice(index, 1);
            } else {
                item.quantity = newQuantity;
                item.subtotal = item.quantity * item.price;
            }
        } else if (change > 0) {
            if (newQuantity > item.stock) {
                alert(`Cannot add more items. Available stock: ${item.stock}`);
                return;
            }
            item.quantity = newQuantity;
            item.subtotal = item.quantity * item.price;
        }
        updateCartDisplay();
    }

    function updateCartDisplay() {
        const tbody = document.getElementById('cart-items');
        tbody.innerHTML = '';

        cart.forEach((item, index) => {
            const remainingStock = item.stock - item.quantity;
            const stockColor = remainingStock < 5 ? 'text-red-500' : 'text-green-500';

            tbody.innerHTML += `
                    <tr class="border-b odd:bg-white even:bg-gray-50">
                        <td class="p-2">
                            ${item.name}
                            <div class="text-sm ${stockColor}">
                                Stock: ${remainingStock}
                            </div>
                        </td>
                        <td class="text-right p-2">${formatCurrency(item.price)}</td>
                        <td class="text-right p-2">
                            <div class="flex justify-end items-center gap-2">
                                <button onclick="updateQuantity(${index}, -1)" 
                                    class="px-2 bg-gray-200 rounded">-</button>
                                ${item.quantity}
                                <button onclick="updateQuantity(${index}, 1)"
                                    class="px-2 bg-gray-200 rounded hover:bg-gray-300 ${remainingStock === 0 ? 'opacity-50 cursor-not-allowed' : ''}"
                                    ${remainingStock === 0 ? 'disabled' : ''}>+</button>
                            </div>
                        </td>
                        <td class="text-right p-2">${formatCurrency(item.subtotal)}</td>
                        <td class="text-center p-2">
                            <button onclick="updateQuantity(${index}, -${item.quantity})"
                                class="text-red-500 hover:text-red-700">Remove</button>
                        </td>
                    </tr>
                `;
        });

        const total = cart.reduce((sum, item) => sum + item.subtotal, 0);
        document.getElementById('total-amount').textContent = formatCurrency(total);
        calculateChange();
    }

    function calculateChange() {
        const total = cart.reduce((sum, item) => sum + item.subtotal, 0);
        const paid = parseFloat(document.getElementById('paid-amount').value) || 0;
        const change = paid - total;
        document.getElementById('change-amount').textContent = formatCurrency(change);
    }

    async function saveTransaction() {
        // Konfigurasi SweetAlert mixin untuk notifikasi
        const Toast = Swal.mixin({
            toast: true,
            position: "top-end",
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.onmouseenter = Swal.stopTimer;
                toast.onmouseleave = Swal.resumeTimer;
            }
        });

        if (cart.length === 0) {
            await Toast.fire({
                icon: 'warning',
                title: 'Cart is empty',
                customClass: {
                    popup: 'bg-red-500 text-white',
                    title: 'text-white font-semibold',
                    htmlContainer: 'text-white',
                    icon: 'text-white'
                },
                didOpen: (popup) => {
                    // Tambahkan gaya langsung untuk memastikan latar belakang merah
                    popup.style.backgroundColor = 'rgb(220 38 38 / var(--tw-text-opacity, 10))';
                    popup.style.color = 'white'; // Teks putih
                }
            });
            return;
        }

        const total = cart.reduce((sum, item) => sum + item.subtotal, 0);
        const paidInput = document.getElementById('paid-amount');
        const paid = parseFloat(paidInput.value) || 0;
        const employeeInput = document.getElementById('employee-input');
        const employeeId = employeeInput.dataset.id;
        const customerInput = document.getElementById('customer-input');
        const customerId = customerInput.dataset.id;
        const paymentStatus = document.getElementById('payment-status').value;

        // Debugging: Periksa nilai customerId dan employeeId
        //console.log("Customer ID:", customerId);
        //console.log("Employee ID:", employeeId);

        // Validasi Employee
        if (!employeeId) {
            employeeInput.setCustomValidity('Please select an employee');
            employeeInput.reportValidity(); // Tampilkan notifikasi error
            return;
        } else {
            employeeInput.setCustomValidity(''); // Hapus pesan error jika valid
        }

        // Validasi Customer
        if (!customerId) {
            customerInput.setCustomValidity('Please select a customer');
            customerInput.reportValidity(); // Tampilkan notifikasi error
            return;
        } else {
            customerInput.setCustomValidity(''); // Hapus pesan error jika valid
        }

        // Validasi Paid Amount
        if (paymentStatus === "COMPLETED" && paid < total) {
            paidInput.setCustomValidity('Insufficient payment amount for completed transactions');
            paidInput.reportValidity();
            return;
        } else {
            paidInput.setCustomValidity('');
        }
        const changeAmount = paid - total; // Bisa bernilai negatif jika payment status "Pending"

        const data = {
            items: cart.map(item => ({
                product_number: item.product_number,
                quantity: item.quantity,
                price: item.price,
                subtotal: item.subtotal,
            })),
            total_amount: total,
            payment_method: document.getElementById('payment-method').value,
            status: paymentStatus,
            paid_amount: paid,
            change_amount: paid - total,
            employee_id: parseInt(employeeId),
            customer_id: parseInt(customerId)
        };
        //console.log('Data yang akan dikirim:', JSON.stringify(data, null, 2));

        try {
            const response = await fetch('/kasir/save-transaction/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();
            //console.log('Response dari server:', result);

            if (!response.ok) {
                throw new Error(result.error || 'Failed to save transaction');
            }


            // Tampilkan notifikasi sukses dengan Swal.mixin
            await Toast.fire({
                title: 'Transaksi Berhasil!',
                html: `Total: <b>Rp ${total.toLocaleString()}</b><br>Kembalian: <b>Rp ${changeAmount.toLocaleString()}</b>`,
                icon: 'success',
            });

            cart = [];
            updateCartDisplay();
            document.getElementById('paid-amount').value = '';
            employeeInput.value = '';
            employeeInput.removeAttribute('data-id'); // Hapus ID setelah selesai
            customerInput.value = '';
            customerInput.removeAttribute('data-id'); // Hapus ID setelah selesai
        } catch (error) {
            //console.error('Error details:', error);
            //console.error('Response dari server:', error.response);
            // Tampilkan notifikasi error dengan Swal.mixin
            await Toast.fire({
                icon: 'error',
                title: 'Transaksi Gagal!',
                html: `Kesalahan: ${error.message}`,
                customClass: {
                    popup: 'bg-red-500 text-white',
                    title: 'text-white font-semibold',
                    htmlContainer: 'text-white',
                    icon: 'text-white'
                },
                didOpen: (popup) => {
                    // Tambahkan gaya langsung untuk memastikan latar belakang merah
                    popup.style.backgroundColor = 'rgb(220 38 38 / var(--tw-text-opacity, 10))';
                    popup.style.color = 'white'; // Teks putih
                }
            });
        }
    }

    // Tambahkan event listener untuk menghapus pesan error saat mengetik
    document.getElementById('customer-input').addEventListener('input', function () {
        this.setCustomValidity(''); // Hapus pesan error
    });

    document.getElementById('employee-input').addEventListener('input', function () {
        this.setCustomValidity(''); // Hapus pesan error
    });

    document.getElementById('paid-amount').addEventListener('input', function () {
        this.setCustomValidity(''); // Hapus pesan error
    });

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
</script>

{% endblock %}