<?php
session_start();
include "koneksi.php";

$id_user = isset($_SESSION['id']) ? $_SESSION['id'] : 0; // amankan kalau session kosong

$q = mysqli_query($koneksi, "SELECT nama, bank, no_rek, a_n FROM user WHERE id='$id_user'");
$user = mysqli_fetch_assoc($q);

$namaDriver = $user['nama'] ?? '';
$bank = $user['bank'] ?? '';
$no_rek = $user['no_rek'] ?? '';
$atas_nama = $user['a_n'] ?? '';
?>
<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="css/order.css">
    <title>Form Order</title>
</head>

<body>
    <h3>Nota Pembelian</h3>
    <div class="container">
        <input type="date" id="tanggal" hidden />

        <div class="total-box">

            <!-- TOTAL BELANJA -->
            <div class="icon-wrapper">
                <label>Total Belanja</label>
                <div class="input-container">
                    <i class="fas fa-clipboard-list input-icon"></i>
                    <input type="text" id="totalBelanja" readonly placeholder="Total Belanja" />
                </div>
            </div>

            <!-- GRAND TOTAL -->
            <div class="icon-wrapper">
                <label>Grand Total</label>
                <div class="input-container">
                    <i class="fas fa-money-bill input-icon"></i>
                    <input type="text" id="grandTotal" readonly placeholder="Grand Total" />
                </div>
            </div>

            <!-- ONKIR -->
            <div class="icon-wrapper">
                <div class="input-container">
                    <!-- onfocus: show editable decimal (raw/1000); onblur: format ×1000 -->
                    <input type="tel" id="ongkir" placeholder="Ongkir"
                        autocomplete="off"
                        onfocus="ongkirDiskon_onFocus(this)"
                        onblur="ongkirDiskon_onBlur(this)"
                        onkeydown="ongkirDiskon_onKeydown(event,this)" />
                </div>
            </div>

            <!-- DISKON -->
            <div class="icon-wrapper">
                <div class="input-container">
                    <input type="tel" id="diskon" placeholder="Diskon (Rp)"
                        autocomplete="off"
                        onfocus="ongkirDiskon_onFocus(this)"
                        onblur="ongkirDiskon_onBlur(this)"
                        onkeydown="ongkirDiskon_onKeydown(event,this)" />
                </div>
            </div>

        </div>
    </div>

    <div class="table-container">
        <table id="tabelList">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Item</th>
                    <th>Qty</th>
                    <th>Harga</th>
                    <th>Total</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <div class="flex-btns">
        <button onclick="tambahList()" title="Tambah List">
            <i class="fab fa-plus"></i>
        </button>
        <button onclick="salinText()" title="Salin">
            <i class="fas fa-copy"></i>
        </button>
        <button onclick="bersihkanSemua()" title="Bersihkan">
            <i class="fas fa-trash"></i>
        </button>
    </div>
    <script>
        /* ---------- Data & Inisialisasi ---------- */
        let dataList = [];
        let noUrut = 1;

        // ambil data php ke js (tersimpan aman pada saat rendering)
        const PHP_namaDriver = `<?php echo addslashes($namaDriver); ?>`;
        const PHP_bank = `<?php echo addslashes($bank); ?>`;
        const PHP_no_rek = `<?php echo addslashes($no_rek); ?>`;
        const PHP_atas_nama = `<?php echo addslashes($atas_nama); ?>`;

        /* ---------- Load / Save localStorage (AMAN) ---------- */
        function loadData() {
            const saved = localStorage.getItem("dataList");
            try {
                const parsed = saved ? JSON.parse(saved) : null;
                if (Array.isArray(parsed)) {
                    dataList = parsed.map(item => {
                        return {
                            id: (item.id !== undefined) ? Number(item.id) : undefined,
                            item: item.item ?? "",
                            qty: Number(item.qty) || 0,
                            harga: Number(item.harga) || 0
                        };
                    });
                } else {
                    dataList = [];
                }
            } catch (e) {
                console.warn("Gagal parse dataList dari localStorage, mereset ke array kosong.", e);
                dataList = [];
            }

            // pastikan noUrut valid
            if (dataList.length > 0) {
                const ids = dataList.map(x => Number(x.id)).filter(n => !isNaN(n) && isFinite(n));
                noUrut = ids.length > 0 ? Math.max(...ids) + 1 : 1;
            } else {
                noUrut = 1;
            }

            // restore ongkir_raw & diskon_raw (tersimpan sebagai angka string)
            const savedOngkirRaw = localStorage.getItem("ongkir_raw");
            const savedDiskonRaw = localStorage.getItem("diskon_raw");

            if (savedOngkirRaw !== null) {
                const raw = parseInt(savedOngkirRaw) || 0;
                const el = document.getElementById("ongkir");
                if (el) {
                    el.dataset.raw = raw;
                    if (raw > 0) el.value = Number(raw).toLocaleString("id-ID");
                    else el.value = "";
                }
            }

            if (savedDiskonRaw !== null) {
                const raw = parseInt(savedDiskonRaw) || 0;
                const el = document.getElementById("diskon");
                if (el) {
                    el.dataset.raw = raw;
                    if (raw > 0) el.value = Number(raw).toLocaleString("id-ID");
                    else el.value = "";
                }
            }

            renderTable();
            hitungGrandTotal();
        }
        loadData();

        function saveData() {
            try {
                localStorage.setItem("dataList", JSON.stringify(dataList));
                // simpan raw values (angka rupiah)
                const ong = document.getElementById("ongkir");
                const dis = document.getElementById("diskon");
                localStorage.setItem("ongkir_raw", (ong && ong.dataset && ong.dataset.raw) ? ong.dataset.raw : "0");
                localStorage.setItem("diskon_raw", (dis && dis.dataset && dis.dataset.raw) ? dis.dataset.raw : "0");
            } catch (e) {
                console.error("Gagal menyimpan ke localStorage:", e);
            }
        }

        /* ---------- Helper Harga (×1000) ---------- */
        function convertHarga(val) {
            if (val === null || val === undefined) return 0;
            val = val.toString().trim().replace(",", ".");
            const n = parseFloat(val);
            if (isNaN(n)) return 0;
            return Math.round(n * 1000);
        }

        /* ---------- Tambah List ---------- */
        function tambahList() {
            Swal.fire({
                title: "Tambah Item",
                html: `
            <input id="swal-item" class="swal2-input" placeholder="Nama Item" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
            <input id="swal-qty" type="number" class="swal2-input" placeholder="Qty" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
            <input id="swal-harga" class="swal2-input" placeholder="Harga Satuan" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
        `,
                showCancelButton: true,
                confirmButtonText: "Tambah",
                preConfirm: () => {
                    const item = document.getElementById("swal-item").value.trim();
                    const qtyRaw = document.getElementById("swal-qty").value;
                    const qty = qtyRaw === "" ? NaN : parseFloat(qtyRaw);
                    const hargaInput = document.getElementById("swal-harga").value.trim();

                    // item wajib, qty wajib
                    if (!item || !qty || isNaN(qty) || qty <= 0) {
                        Swal.showValidationMessage("Item & Qty wajib diisi (Qty > 0)");
                        return false;
                    }

                    // harga boleh kosong
                    let harga = 0;
                    if (hargaInput !== "") {
                        harga = convertHarga(hargaInput);

                        if (isNaN(harga) || harga < 0) {
                            Swal.showValidationMessage("Format harga tidak valid");
                            return false;
                        }
                    }

                    return {
                        item,
                        qty,
                        harga
                    };
                }
            }).then((result) => {
                if (!result.isConfirmed) return;

                dataList.push({
                    id: noUrut++,
                    item: result.value.item,
                    qty: Number(result.value.qty),
                    harga: Number(result.value.harga)
                });

                saveData();
                renderTable();
                hitungGrandTotal();
            });
        }

        /* ---------- Action Menu (Edit / Delete) ---------- */
        function actionMenu(id) {
            Swal.fire({
                title: "Pilih Aksi",
                showCancelButton: true,
                confirmButtonText: "Edit",
                cancelButtonText: "Delete",
                reverseButtons: true
            }).then((res) => {
                if (res.isConfirmed) editList(id);
                else if (res.dismiss === Swal.DismissReason.cancel) deleteList(id);
            });
        }

        /* ---------- Edit ---------- */
        function editList(id) {
            const data = dataList.find(x => x.id === id);
            if (!data) return;

            Swal.fire({
                title: "Edit Item",
                html: `
            <input id="swal-item" class="swal2-input" value="${escapeHtml(data.item)}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
            <input id="swal-qty" type="number" class="swal2-input" value="${data.qty}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
            <input id="swal-harga" class="swal2-input" value="${(data.harga / 1000) || 0}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
        `,
                showCancelButton: true,
                confirmButtonText: "Simpan",

                preConfirm: () => {
                    const item = document.getElementById("swal-item").value.trim();
                    const qtyRaw = document.getElementById("swal-qty").value;
                    const qty = qtyRaw === "" ? NaN : parseFloat(qtyRaw);
                    const hargaInput = document.getElementById("swal-harga").value.trim();

                    if (!item || !qty || isNaN(qty) || qty <= 0) {
                        Swal.showValidationMessage("Item & Qty wajib diisi!");
                        return false;
                    }

                    // harga boleh kosong
                    let harga = 0;
                    if (hargaInput !== "") {
                        harga = convertHarga(hargaInput);

                        if (isNaN(harga) || harga < 0) {
                            Swal.showValidationMessage("Format harga tidak valid");
                            return false;
                        }
                    }

                    return {
                        item,
                        qty,
                        harga
                    };
                }
            }).then((result) => {
                if (!result.isConfirmed) return;
                const index = dataList.findIndex(x => x.id === id);
                if (index === -1) return;
                dataList[index] = {
                    ...dataList[index],
                    ...{
                        item: result.value.item,
                        qty: Number(result.value.qty),
                        harga: Number(result.value.harga)
                    }
                };
                saveData();
                renderTable();
                hitungGrandTotal();
            });
        }

        /* ---------- Delete ---------- */
        function deleteList(id) {
            Swal.fire({
                icon: "warning",
                title: "Hapus item ini?",
                showCancelButton: true,
                confirmButtonText: "Hapus"
            }).then((res) => {
                if (!res.isConfirmed) return;
                dataList = dataList.filter(x => x.id !== id);
                saveData();
                renderTable();
                hitungGrandTotal();
            });
        }

        /* ---------- Hitung Total ---------- */
        function hitungGrandTotal() {
            // totalBelanjaRaw sudah dalam satuan rupiah (karena harga disimpan ×1000)
            const totalBelanjaRaw = dataList.reduce((a, b) => {
                const harga = Number(b.harga) || 0;
                const qty = Number(b.qty) || 0;
                return a + (harga * qty);
            }, 0);

            // ongkir & diskon diambil dari dataset.raw (yang sudah dalam rupiah)
            const ongEl = document.getElementById("ongkir");
            const disEl = document.getElementById("diskon");
            const ongkirRaw = parseInt((ongEl && ongEl.dataset && ongEl.dataset.raw) ? ongEl.dataset.raw : 0) || 0;
            const diskonRaw = parseInt((disEl && disEl.dataset && disEl.dataset.raw) ? disEl.dataset.raw : 0) || 0;
            const grand = totalBelanjaRaw + ongkirRaw - diskonRaw;

            const tbEl = document.getElementById("totalBelanja");
            const gtEl = document.getElementById("grandTotal");
            if (tbEl) tbEl.value = totalBelanjaRaw.toLocaleString("id-ID");
            if (gtEl) gtEl.value = grand.toLocaleString("id-ID");

            saveData();
        }

        /* ---------- Render Table (AMAN) ---------- */
        function renderTable() {
            const tbody = document.querySelector("#tabelList tbody");
            if (!tbody) return;
            tbody.innerHTML = "";

            if (!Array.isArray(dataList) || dataList.length === 0) {
                const tr = document.createElement("tr");
                tr.innerHTML = `<td colspan="6" style="text-align:center; color:#666">Belum ada item</td>`;
                tbody.appendChild(tr);
                return;
            }

            dataList.forEach((row, i) => {
                const qty = Number(row.qty) || 0;
                const harga = Number(row.harga) || 0; // sudah dalam rupiah
                const total = qty * harga;

                const hargaDisplay = harga.toLocaleString("id-ID");
                const totalDisplay = total.toLocaleString("id-ID");

                const tr = document.createElement("tr");
                tr.innerHTML = `
            <td>${i + 1}</td>
            <td>${escapeHtml(row.item)}</td>
            <td>${qty}</td>
            <td>${hargaDisplay}</td>
            <td>${totalDisplay}</td>
            <td>
                <button class="btn-action" onclick="actionMenu(${row.id})">
                </button>
            </td>
        `;
                tbody.appendChild(tr);
            });
        }

        /* ---------- Salin Text (Clipboard) ---------- */
        function salinText() {
            const tanggal = new Date().toLocaleDateString("id-ID", {
                day: "numeric",
                month: "long",
                year: "numeric"
            });

            // build list lines
            let listLines = "";
            dataList.forEach(x => {
                const hargaFmt = (Number(x.harga) || 0).toLocaleString("id-ID");
                const subtotal = ((Number(x.harga) || 0) * (Number(x.qty) || 0)).toLocaleString("id-ID");
                listLines += `•  ${x.item} : Rp. ${hargaFmt} x ${x.qty} = Rp. ${subtotal}\n`;
            });

            // raw numbers for totals (no thousand separator)
            const totalBelanjaRaw = dataList.reduce((a, b) => a + ((Number(b.harga) || 0) * (Number(b.qty) || 0)), 0);

            const ongEl = document.getElementById("ongkir");
            const disEl = document.getElementById("diskon");
            const ongkirRaw = parseInt((ongEl && ongEl.dataset && ongEl.dataset.raw) ? ongEl.dataset.raw : 0) || 0;
            const diskonRaw = parseInt((disEl && disEl.dataset && disEl.dataset.raw) ? disEl.dataset.raw : 0) || 0;

            const grandRaw = totalBelanjaRaw + ongkirRaw - diskonRaw;

            // format numbers for display
            const totalBelanjaFmt = totalBelanjaRaw.toLocaleString("id-ID");
            const ongkirFmt = ongkirRaw.toLocaleString("id-ID");
            const diskonFmt = diskonRaw.toLocaleString("id-ID");
            const grandFmt = grandRaw.toLocaleString("id-ID");

            const namaDriver = PHP_namaDriver || "";
            const bank = PHP_bank || "";
            const no_rek = PHP_no_rek || "";
            const a_n = PHP_atas_nama || "";

            const text =
                `𝐓𝐈𝐎𝐑 𝐃𝐄𝐋𝐈𝐕𝐄𝐑𝐘 | ${tanggal}
Driver : ${namaDriver}

📋𝙻𝚒𝚜𝚝 𝙿𝚎𝚖𝚋𝚊𝚢𝚊𝚛𝚊𝚗 :
──────────────────────
${listLines}
──────────────────────
Total Belanja : Rp. ${totalBelanjaFmt}
Diskon Ongkir : Rp. ${diskonFmt}
𝙾𝚗𝚐𝚔𝚒𝚛 : Rp. ${ongkirFmt}
──────────────────────
*𝚃𝚘𝚝𝚊𝚕 : Rp. ${grandFmt}*
──────────────────────

Pembayaran Bisa Cash/Transfer :
${bank} : ${no_rek} (${a_n})

Admin TIOR : +6281181210955

𝘛𝘦𝘳𝘪𝘮𝘢𝘬𝘢𝘴𝘪𝘩 𝘛𝘦𝘭𝘢𝘩 𝘔𝘦𝘯𝘨𝘨𝘶𝘯𝘢𝘬𝘢𝘯 𝘑𝘢𝘴𝘢 𝘛𝘐𝘖𝘙 𝘋𝘦𝘭𝘪𝘷𝘦𝘳𝘺`;

            // try clipboard API
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(() => {
                    Swal.fire({
                        icon: "success",
                        title: "Teks Berhasil Disalin!",
                        showConfirmButton: false,
                        timer: 1200
                    });
                }).catch((err) => {
                    console.error("Clipboard error:", err);
                    fallbackCopyTextToClipboard(text);
                });
            } else {
                fallbackCopyTextToClipboard(text);
            }
        }

        /* fallback for older browsers */
        function fallbackCopyTextToClipboard(text) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            // Avoid scrolling to bottom
            textArea.style.position = "fixed";
            textArea.style.top = "-9999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    Swal.fire({
                        icon: "success",
                        title: "Teks Berhasil Disalin!",
                        showConfirmButton: false,
                        timer: 1200
                    });
                } else {
                    Swal.fire({
                        icon: "error",
                        title: "Gagal menyalin. Silakan salin manual.",
                        text: "Pilih teks lalu Ctrl+C"
                    });
                }
            } catch (err) {
                console.error('Fallback copy failed', err);
                Swal.fire({
                    icon: "error",
                    title: "Gagal menyalin. Silakan salin manual.",
                    text: "Pilih teks lalu Ctrl+C"
                });
            }

            document.body.removeChild(textArea);
        }

        /* ---------- utility ---------- */
        function escapeHtml(text) {
            if (text === null || text === undefined) return "";
            return String(text)
                .replace(/&/g, "&amp;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;");
        }

        /* ---------- Ongkir & Diskon helpers (Gaya A) ----------
           - Saat focus: tampilkan nilai editable (raw/1000) dengan koma sebagai decimal separator.
           - Saat blur: konversi input ke angka, kalikan ×1000, simpan di dataset.raw, lalu tampilkan formatted (ribuan).
           - Tekan Enter = blur.
        */
        function ongkirDiskon_onFocus(el) {
            // saat fokus, tunjukkan nilai desimal yang bisa diedit (raw/1000)
            const raw = parseInt(el.dataset.raw) || 0;
            if (raw > 0) {
                // convert raw (rupiah) -> decimal string (raw/1000), use comma
                let decimal = (raw / 1000).toString().replace(".", ",");
                el.value = decimal;
            } else {
                // kosong biarkan kosong
                el.value = "";
            }
            // simpan state edit agar onblur tahu ini berasal dari fokus
            el.dataset.editing = "1";
            // tidak trigger hitung saat mengetik; onblur akan menghitung
        }

        function ongkirDiskon_onKeydown(e, el) {
            // tekan Enter -> blur (selesai input)
            if (e.key === "Enter") {
                e.preventDefault();
                el.blur();
            }
        }

        function ongkirDiskon_onBlur(el) {
            // saat blur, ambil nilai yang diketik user
            let v = (el.value || "").toString().trim();
            if (v === "") {
                el.dataset.raw = 0;
                el.value = "";
                hitungGrandTotal();
                return;
            }

            // ubah koma -> titik agar parseFloat benar
            v = v.replace(",", ".");

            // kalau user memasukkan nilai penuh (misal 12000) — kita tangani juga:
            // if v looks like large integer (>=1000), assume user entered rupiah langsung.
            // namun preferahan: treat as decimal (x * 1000)
            // Kita tentukan: jika v contains '.' or ',' or v < 1000 => treat as decimal; else if v >= 1000 treat as rupiah
            let num = parseFloat(v);
            if (isNaN(num)) {
                el.dataset.raw = 0;
                el.value = "";
                hitungGrandTotal();
                return;
            }

            let result;
            if (num >= 1000 && !v.includes(".") && !v.includes(",")) {
                // user mungkin memasukkan 12000 langsung -> gunakan langsung
                result = Math.round(num);
            } else {
                // normal case: treat as decimal and multiply
                result = Math.round(num * 1000);
            }

            // simpan raw (rupiah) ke dataset
            el.dataset.raw = result;

            // tampilkan formatted rupiah di input
            if (result > 0) el.value = result.toLocaleString("id-ID");
            else el.value = "";

            // hapus flag editing
            delete el.dataset.editing;

            // hitung ulang total
            hitungGrandTotal();
        }

        // ================================
        // BERSIHKAN SEMUA DATA
        // ================================
        function bersihkanSemua() {
            Swal.fire({
                icon: "warning",
                title: "Bersihkan semua data?",
                text: "Semua list, ongkir, diskon, dan total akan dihapus!",
                showCancelButton: true,
                confirmButtonColor: "#d33",
                cancelButtonColor: "#3085d6",
                cancelButtonText: "Batal",
                confirmButtonText: "Ya, hapus!"
            }).then((result) => {
                if (!result.isConfirmed) return;

                // reset data
                dataList = [];
                noUrut = 1;

                // hapus localStorage
                localStorage.removeItem("dataList");
                localStorage.removeItem("ongkir_raw");
                localStorage.removeItem("diskon_raw");

                // reset input
                if (document.getElementById("ongkir")) {
                    document.getElementById("ongkir").dataset.raw = 0;
                    document.getElementById("ongkir").value = "";
                }
                if (document.getElementById("diskon")) {
                    document.getElementById("diskon").dataset.raw = 0;
                    document.getElementById("diskon").value = "";
                }
                if (document.getElementById("totalBelanja")) document.getElementById("totalBelanja").value = "0";
                if (document.getElementById("grandTotal")) document.getElementById("grandTotal").value = "0";

                // render ulang tabel
                renderTable();
                hitungGrandTotal();

                Swal.fire({
                    icon: "success",
                    title: "Data berhasil dibersihkan!",
                    timer: 1200,
                    showConfirmButton: false
                });
            });
        }
    </script>
    <?php include 'navbar3.php'; ?>

</body>

</html>