<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kasir Kendi</title>
<link rel=stylesheet href=style.css>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Google Font -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap" rel="stylesheet">

</head>
<body>
<h2>KASIR - KENDI</h2>
    <div class="menu-container">
        <label for="paidAmount">Uang:</label>
        <input type="number" id="paidAmount" min="0" placeholder="Masukkan jumlah uangnya..." oninput="calculateChange()">

        <label for="menu">Pilih Menu:</label>
        <select id="menu">
            <option value="1" data-price="15000">Nasi Rendang Ayam - Rp 15.000</option>
            <option value="2" data-price="10000">Bakso - Rp 10.000</option>
            <option value="3" data-price="10000">Pisang Nugget - Rp 10.000</option>
            <option value="4" data-price="5000">Maklor - Rp 5.000</option>
            <option value="5" data-price="5000">Es Milo - Rp 5.000</option>
            <option value="6" data-price="5000">Es Lemon Tea - Rp 5.000</option>
        </select>

        <label for="quantity">Jumlah:</label>
        <input type="number" id="quantity" min="1" value="1">

        <button class="tambah-btn" onclick="addToOrder()">Tambah ke Pesanan</button>

        <div class="order-list" id="orderList">
            <strong>List Pesanan:</strong>
            <ul id="orderItems"></ul>
            <p>Total: <span id="totalPrice">Rp 0</span></p>
            <p>Kembalian: <span id="changeAmount">----</span></p>
        </div>

       <label for="paymentStatus">Status Pembayaran:</label>
        <select id="paymentStatus">
            <option value="Lunas">Lunas 🥰</option>
            <option value="Tidak Lunas">Tidak Lunas 🤬</option>
        </select>

        <button class="simpan-btn" onclick="saveTransaction()">Simpan Transaksi</button>
        <button class="reset-btn" onclick="resetInputs()">Reset</button>
    </div>

  <div class="order-history">
    <strong>Riwayat Transaksi:</strong>
    <table id="historyTable">
        <thead>
            <tr>
                <th>No</th>
                <th>Tanggal</th>
                <th>Total</th>
                <th>Status</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody id="historyItems"></tbody>
    </table>
    <p>Total Semua Transaksi: <span id="totalAllTransactions">Rp 0</span></p>
    <button id="reset-riwayat-btn" class="reset-riwayat-btn" onclick="resetTransactionHistory()">Reset Riwayat</button>
</div>


<div class="footer">
    <p>Made with ♥️ By<br> 
    <a href="https://instagram.com/12tekaje_2025" target="_blank" style="color: white; text-decoration: none; font-weight: bold;">
        12 Teknik Komputer & Jaringan 1
    </a></p>
</div>



    <script>
        let orders = [];
        let totalHarga = 0;

        function addToOrder() {
            const menuSelect = document.getElementById("menu");
            const selectedOption = menuSelect.options[menuSelect.selectedIndex];
            const itemName = selectedOption.text.split(" - ")[0];
            const itemPrice = parseInt(selectedOption.getAttribute("data-price"));
            const quantity = parseInt(document.getElementById("quantity").value);

            if (quantity <= 0) {
                alert("Jumlah harus lebih dari 0!");
                return;
            }

            let existingOrder = orders.find(order => order.name === itemName);
            if (existingOrder) {
                existingOrder.quantity += quantity;
            } else {
                orders.push({ name: itemName, price: itemPrice, quantity: quantity });
            }

            updateOrderList();
        }

        function updateOrderList() {
            const orderListElement = document.getElementById("orderItems");
            const totalPriceElement = document.getElementById("totalPrice");

            orderListElement.innerHTML = "";
            totalHarga = 0;

            orders.forEach(order => {
                const totalItemPrice = order.price * order.quantity;
                totalHarga += totalItemPrice;

                let listItem = document.createElement("li");
                listItem.textContent = `${order.name} (x${order.quantity}) - Rp ${formatNumber(totalItemPrice)}`;
                orderListElement.appendChild(listItem);
            });

            totalPriceElement.textContent = `Rp ${formatNumber(totalHarga)}`;
            calculateChange();
        }

function calculateChange() {
    const paidAmountInput = document.getElementById("paidAmount").value;
    const changeAmountElement = document.getElementById("changeAmount");

    // Konversi format uang dari "1 = 1000", "10.4 = 10400"
    const paidAmount = parseFloat(paidAmountInput.replace('.', '')) * 1000;

    if (isNaN(paidAmount) || paidAmount <= 0) {
        changeAmountElement.textContent = "Masukkan uang yang valid!";
        changeAmountElement.style.color = "red";
        return;
    }

    if (paidAmount < totalHarga) {
        const kurang = totalHarga - paidAmount;
        changeAmountElement.textContent = `Uang kamu kurang Rp ${formatNumber(kurang)} Nih..`;
        changeAmountElement.style.color = "red"; // Warna merah untuk peringatan
    } else {
        const change = paidAmount - totalHarga;
        changeAmountElement.textContent = `Rp ${formatNumber(change)}`;
        changeAmountElement.style.color = "#27ae60"; // Warna hijau jika cukup
    }
}



        function formatNumber(number) {
            return number.toLocaleString('id-ID');
        }
function resetTransactionHistory() {
    Swal.fire({
        title: "Apakah Anda yakin?",
        text: "Riwayat transaksi akan dihapus permanen!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#e74c3c",
        cancelButtonColor: "#6c757d",
        confirmButtonText: "Ya, hapus!",
        cancelButtonText: "Batal"
    }).then((result) => {
        if (result.isConfirmed) {
            localStorage.removeItem("transactionHistory");
            displayTransactionHistory();

            Swal.fire({
                icon: "success",
                title: "Riwayat direset!",
                text: "Semua transaksi telah dihapus.",
                timer: 3000,
                showConfirmButton: false,
                toast: true,
                position: "top-end"
            });
        }
    });
}
document.getElementById("reset-riwayat-btn").addEventListener("click", function() {
    // Cek apakah tabel riwayat transaksi berisi data atau hanya tulisan "📂 Tidak ada data"
    const tabelRiwayat = document.querySelector(".order-history table tbody");
    const riwayatKosong = tabelRiwayat.children.length === 0 || tabelRiwayat.textContent.includes("📂 Tidak ada data");

    if (riwayatKosong) {
        // Jika tabel kosong atau hanya ada tulisan "📂 Tidak ada data", tampilkan pesan SweetAlert2
        Swal.fire({
            title: "Riwayat transaksi tidak ada",
            icon: "info",
            confirmButtonText: "OK",
            confirmButtonColor: "#4a68d0"
        });
    } else {
        // Jika ada data, tampilkan konfirmasi penghapusan
        Swal.fire({
            title: "Apakah Anda yakin?",
            text: "Data transaksi ini akan dihapus dan tidak bisa dikembalikan!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#e74c3c",
            cancelButtonColor: "#6c757d",
            confirmButtonText: "Ya, hapus!",
            cancelButtonText: "Batal"
        }).then((result) => {
            if (result.isConfirmed) {
                localStorage.removeItem("transactionHistory");
                displayTransactionHistory();
                Swal.fire({
                icon: "success",
                title: "Riwayat direset!",
                text: "Semua transaksi telah dihapus.",
                timer: 3000,
                showConfirmButton: false,
                toast: true,
                position: "top-end"
                });
            }
        });
    }
});
        
function saveTransaction() {
    const paidAmount = document.getElementById("paidAmount").value;

    if (paidAmount === "" || parseInt(paidAmount) <= 0) {
        Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: 'Masukkan jumlah uang dengan benar!',
        });
        return;
    }
    if (orders.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'Pesanan kosong!',
            text: 'Tambahkan pesanan terlebih dahulu.',
        });
        return;
    }

    const paymentStatus = document.getElementById("paymentStatus").value;
    let history = JSON.parse(localStorage.getItem("transactionHistory")) || [];
    let transactionNumber = history.length + 1;

    let newTransaction = {
        number: transactionNumber,
        orders,
        total: totalHarga,
        date: new Date().toLocaleString(),
        status: paymentStatus
    };

    history.push(newTransaction);
    localStorage.setItem("transactionHistory", JSON.stringify(history));

    const Toast = Swal.mixin({
    toast: true,
    position: "top-end",
    showConfirmButton: false,
    timer: 3000,
    timerProgressBar: true,
    customClass: {
        popup: 'swal2-toast' // Tambahkan custom class
    },
    didOpen: (toast) => {
        toast.onmouseenter = Swal.stopTimer;
        toast.onmouseleave = Swal.resumeTimer;
    }
});

// Contoh pemanggilan

Toast.fire({
    icon: "success",
    title: "Data has been saved!"
});

    orders = [];
    updateOrderList();
    displayTransactionHistory();
}


        function displayTransactionHistory() {
    const history = JSON.parse(localStorage.getItem("transactionHistory")) || [];
    const historyItems = document.getElementById("historyItems");
    historyItems.innerHTML = ""; // Kosongkan tabel sebelum diisi ulang
if (history.length === 0) {
        const emptyRow = document.createElement("tr");
        emptyRow.innerHTML = `
            <td colspan="5" class="no-data">📂 Tidak ada data</td>
        `;
        historyItems.appendChild(emptyRow);
        document.getElementById("totalAllTransactions").textContent = "Rp 0";
        return;
    }
    history.forEach((t, index) => {
        const row = document.createElement("tr");
        row.innerHTML = `
            <td>${index + 1}</td>
            <td>${t.date}</td>
            <td>Rp ${formatNumber(t.total)}</td>
            <td>${t.status === "Lunas" ? "✅ Lunas" : "❌ Tidak Lunas"}</td>
            <td>
                <button class="delete-btn" onclick="removeTransaction(${index})">❌</button>
            </td>
        `;
        historyItems.appendChild(row);
    });

    calculateTotalHistory(history);
}



function removeTransaction(index) {
    Swal.fire({
        title: "Apakah Anda yakin?",
        text: "Data transaksi ini akan dihapus dan tidak bisa dikembalikan!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#e74c3c",
        cancelButtonColor: "#6c757d",
        confirmButtonText: "Ya, hapus!",
        cancelButtonText: "Batal"
    }).then((result) => {
        if (result.isConfirmed) {
            let history = JSON.parse(localStorage.getItem("transactionHistory")) || [];
            history.splice(index, 1);  // Hapus transaksi berdasarkan index
            localStorage.setItem("transactionHistory", JSON.stringify(history));
            displayTransactionHistory();  // Update tampilan riwayat

            const Toast = Swal.mixin({
    toast: true,
    position: "top-end",
    showConfirmButton: false,
    timer: 3000,
    timerProgressBar: true,
    customClass: {
        popup: 'swal2-toast' // Tambahkan custom class
    },
    didOpen: (toast) => {
        toast.onmouseenter = Swal.stopTimer;
        toast.onmouseleave = Swal.resumeTimer;
    }
});

// Contoh pemanggilan

Toast.fire({
    icon: "success",
    title: "Data berhasil dihapus!"
});
        }
    });
}



        function calculateTotalHistory(history) {
    const totalAll = history.reduce((acc, curr) => acc + curr.total, 0);
    const totalElement = document.getElementById("totalAllTransactions");

    totalElement.textContent = `Rp ${formatNumber(totalAll)}`;
    
    if (totalAll > 0) {
        totalElement.style.color = "red";
    } else {
        totalElement.style.color = "black"; // Default jika 0
    }
}


    function resetInputs() {
    document.getElementById("paidAmount").value = "";
    document.getElementById("menu").selectedIndex = 0;
    document.getElementById("quantity").value = 1;
    document.getElementById("paymentStatus").selectedIndex = 0;
    orders = [];
    totalHarga = 0;
    updateOrderList();

    // Menghapus teks kembalian agar tidak muncul pesan error
    const changeAmountElement = document.getElementById("changeAmount");
    changeAmountElement.textContent = "----";
    changeAmountElement.classList.remove("error");
    changeAmount.classList.add("green-text");
}


        window.onload = displayTransactionHistory;
    </script>

</body>
</html>