<?php
include 'auth.php';  // Memanggil auth.php untuk mengecek login
?>

<!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>
  <title>Form Report</title>
  <link rel="stylesheet" href="css/report.css">
  <link rel="stylesheet" href="css/navbar.css">
</head>

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

    <!-- Tombol untuk show/hide -->
    <button id="toggleTotalBtn" onclick="toggleTotalBox()"
      style="border: 1px solid #fed054; background: rgba(255,255,255,0.20); color:#fed054; padding:8px 15px; border-radius:5px;">
      Tampilkan Rincian
    </button>

    <!-- TOTAL BOX (disembunyikan) -->
    <div id="totalBox" class="total-box" style="display:none; pointer-events: none;">
      <div class="icon-wrapper">
        <label for="totalOngkir">Total Ongkir</label>
        <div class="input-container">
          <i class="fas fa-clipboard-list input-icon"></i>
          <input type="text" id="totalOngkir" readonly placeholder="Ongkir" />
        </div>
      </div>

      <div class="icon-wrapper">
        <label for="orderan">Total Orderan</label>
        <div class="input-container">
          <i class="fas fa-cart-arrow-down input-icon"></i>
          <input type="text" id="orderan" readonly placeholder="T.Order" />
        </div>
      </div>

      <div class="icon-wrapper">
        <label for="totalPendapatan">Total Pendapatan</label>
        <div class="input-container">
          <i class="fas fa-wallet input-icon"></i>
          <input type="text" id="totalPendapatan" readonly placeholder="Pendapatan" />
        </div>
      </div>

      <div class="icon-wrapper">
        <label for="totalDiskon">Total Diskon</label>
        <div class="input-container">
          <i class="fas fa-tag input-icon"></i>
          <input type="text" id="totalDiskon" readonly placeholder="Diskon" />
        </div>
      </div>

      <div class="icon-wrapper">
        <label for="totalSetoran">Total Setoran</label>
        <div class="input-container">
          <i class="fas fa-money-bill input-icon"></i>
          <input type="text" id="totalSetoran" readonly placeholder="Setoran" />
        </div>
      </div>

    </div>


    <div class="row-inline">
      <div hidden class="form-group">
        <button type="button" id="showTabunganBtn" class="btn-tabungan">+ Tabungan<span
            id="tabunganValue"></span></button>
        <input type="tel" id="tabungan" placeholder="Tabungan" readonly style="display:none;" />
        <input type="text" class="form-control" id="namaUser" name="nama"
          value="<?php echo $_SESSION['user']['nama_asli']; ?>" readonly hidden>
        <input type="text" class="form-control" id="noHandphone" name="nama"
          value="<?php echo $_SESSION['user']['no_handphone']; ?>" readonly hidden>
      </div>
      <div class="form-group">
        <select id="potongan" onchange="hitungTotal()">
          <option value="0">0% Potongan Global</option>
          <option value="5">5% Potongan Global</option>
        </select>
      </div>
    </div>

    <div style="margin-top:10px">
      <button onclick="tambahList()">+ Tambah List</button>
    </div>

    <div class="table-container">
      <table>
        <thead>
          <tr>
            <th>No</th>
            <th>Konsumen</th>
            <th>Ongkir</th>
            <th>X</th>
            <th>Del</th>
          </tr>
        </thead>
        <tbody id="tabelBody"></tbody>
        <tr>
          <td colspan="5" style="text-align:center;color:gray;">Klik ( + Tambah List ) untuk menambah kolom</td>
        </tr>
      </table>
    </div>

    <div class="flex-btns">
      <button type="button" class="btn-submit" onclick="kirimWA()" title="Kirim WA">
        <i class="fas fa-paper-plane"></i>
      </button>

      <button hidden type="button" onclick="salinTeksWA()" title="Salin">
        <i class="fas fa-copy"></i>
      </button>

      <button onclick="bersihkan()" title="Bersihkan">
        <i class="fas fa-trash"></i>
      </button>
    </div>

    <?php include 'navbar3.php'; ?>

    <script>
      function toggleTotalBox() {
        const box = document.getElementById("totalBox");
        const btn = document.getElementById("toggleTotalBtn");

        if (box.style.display === "none") {
          box.style.display = "block";
          btn.innerText = "Sembunyikan Rincian";
        } else {
          box.style.display = "none";
          btn.innerText = "Tampilkan Rincian";
        }
      }

      // POPUP INPUT ONGKIR + POTONGAN + DISKON
      function inputOngkirPopup(btn) {
        Swal.fire({
          title: "Input Ongkir",
          html: `
      <input type="tel" id="ongkirInput" class="swal2-input" placeholder="Masukkan Ongkir (Rp)" autocomplete="off" />
      <select id="potonganSelect" class="swal2-input">
        <option value="25">Potongan 25%</option>
        <option value="20">Potongan 20%</option>
      </select>
      <input type="tel" id="diskonInput" class="swal2-input" placeholder="Diskon (Rp)" autocomplete="off" />
    `,
          confirmButtonText: "OK",
          showCancelButton: true,

          didOpen: () => {
            // isi nilai awal jika sudah ada di btn.dataset
            const existingOngkir = parseFloat(btn.dataset.ongkir_asli || 0);
            const existingPot = parseFloat(btn.dataset.pot || 25);
            const existingDiskon = parseFloat(btn.dataset.diskon || 0);

            if (existingOngkir > 0) {
              // tampilkan dalam ribuan (mis. 12000)
              const el = Swal.getPopup().querySelector('#ongkirInput');
              if (el) el.value = Math.round(existingOngkir);
            }
            const potEl = Swal.getPopup().querySelector('#potonganSelect');
            if (potEl) potEl.value = existingPot;
            const diskEl = Swal.getPopup().querySelector('#diskonInput');
            if (diskEl) diskEl.value = existingDiskon ? Math.round(existingDiskon) : "";
          },

          preConfirm: () => {
            let ongkirRaw = document.getElementById("ongkirInput").value.replace(/,/g, ".");
            let ongkir = parseFloat(ongkirRaw);
            const pot = parseFloat(document.getElementById("potonganSelect").value);

            // Ambil diskon
            let diskonRaw = document.getElementById("diskonInput").value.replace(/,/g, ".");
            let diskon = parseFloat(diskonRaw) || 0;

            if (isNaN(ongkir) || ongkir <= 0) {
              Swal.showValidationMessage("Masukkan ongkir dengan benar!");
              return false;
            }

            // ×1000 untuk ongkir kecil
            if (ongkir < 1000) ongkir = ongkir * 1000;

            // ×1000 untuk diskon kecil
            if (diskon < 1000 && diskon > 0) diskon = diskon * 1000;

            const potongan = Math.round(ongkir * pot / 100);
            const setelahPotong = ongkir - potongan;
            const setelahDiskon = setelahPotong - diskon;

            if (setelahDiskon < 0) {
              Swal.showValidationMessage("Diskon melebihi pendapatan!");
              return false;
            }

            return {
              ongkir,
              pot,
              potongan,
              setelahPotong,
              diskon,
              setelahDiskon
            };
          }

        }).then(res => {
          if (res.isConfirmed && res.value) {
            const {
              ongkir,
              pot,
              potongan,
              setelahPotong,
              diskon,
              setelahDiskon
            } = res.value;

            // Simpan ongkir ASLI di input (dataset)
            btn.dataset.ongkir_asli = ongkir;
            btn.dataset.pot = pot;
            btn.dataset.potongan = potongan;
            btn.dataset.setelahPotong = setelahPotong;
            btn.dataset.diskon = diskon;
            btn.dataset.setelahDiskon = setelahDiskon;

            // tampilkan ongkir asli di input (format rupiah)
            try {
              btn.value = ongkir.toLocaleString("id-ID");
            } catch (e) {
              btn.value = ongkir;
            }

            simpanKeLocalStorage();
            hitungTotal();
          }
        });
      }

      document.getElementById("showTabunganBtn").addEventListener("click", function() {
        Swal.fire({
          title: 'Masukkan Tabungan',
          html: `
      <input type="tel" id="tabunganWajib" class="swal2-input" placeholder="Tabungan Wajib" autocomplete="off">
      <input type="tel" id="tabunganSukarela" class="swal2-input" placeholder="Tabungan Sukarela" autocomplete="off">
    `,
          confirmButtonColor: '#1f1f1f',
          cancelButtonColor: '#3b3b3b',
          showCancelButton: true,
          confirmButtonText: 'Lanjut',
          preConfirm: () => {
            const wajib = parseInt(document.getElementById("tabunganWajib").value);
            const sukarela = parseInt(document.getElementById("tabunganSukarela").value || "0");

            if (isNaN(wajib) || wajib < 5000) {
              Swal.showValidationMessage("Tabungan wajib minimal Rp. 5000 Brooo!");
              return false;
            }
            const today = new Date();
            const periode = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
            return {
              wajib,
              sukarela,
              total: wajib + sukarela,
              periode
            };
          }
        }).then((result) => {
          if (result.isConfirmed && result.value) {
            const {
              wajib,
              sukarela,
              total,
              periode
            } = result.value;
            const namaUser = document.getElementById("namaUser").value.trim();
            const noHandphone = document.getElementById("noHandphone").value.trim();
            if (!namaUser || !noHandphone) {
              Swal.fire("Lengkapi nama dan nomor HP terlebih dahulu", "", "warning");
              return;
            }
            Swal.fire({
              title: 'Anda Akan Menabung ?',
              html: `
          <p><strong>Tabungan Wajib:</strong> Rp ${wajib.toLocaleString('id-ID')}</p>
          <p><strong>Tabungan Sukarela:</strong> Rp ${sukarela.toLocaleString('id-ID')}</p>
          <p><strong>Total:</strong> Rp ${total.toLocaleString('id-ID')}</p>
        `,
              showCancelButton: true,
              confirmButtonText: 'Ya',
              cancelButtonText: 'Batal',
              confirmButtonColor: '#1f1f1f',
              cancelButtonColor: '#777'
            }).then((confirmResult) => {
              if (confirmResult.isConfirmed) {
                localStorage.setItem('tabungan_wajib', wajib);
                localStorage.setItem('tabungan_sukarela', sukarela);
                localStorage.setItem('tabungan_total', total);
                document.getElementById("tabungan").value = total;
                document.getElementById("showTabunganBtn").innerHTML = `+ Tabungan: ${total.toLocaleString('id-ID')}`;
                fetch('save_tabungan.php', {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `nama=${encodeURIComponent(namaUser)}&no_handphone=${encodeURIComponent(noHandphone)}&tabungan_wajib=${wajib}&tabungan_sukarela=${sukarela}&periode=${encodeURIComponent(periode)}`
                  })
                  .then(response => response.json())
                  .then(data => {
                    if (data.success) {
                      Swal.fire("Tabungan berhasil disimpan", "", "success");
                      localStorage.setItem('id_tabungan', data.id_tabungan);
                    } else {
                      Swal.fire("Gagal menyimpan", data.message || "", "error");
                    }
                  })
                  .catch(error => {
                    console.error("Error:", error);
                    Swal.fire("Terjadi kesalahan jaringan", "", "error");
                  });

                if (typeof hitungTotal === 'function') {
                  hitungTotal(); // Panggil jika fungsi ini memang ada
                }
              }
            });
          }
        });
      });

      function generateText() {
        const tanggal = document.getElementById("tanggal").value;
        const potGlobal = parseFloat(document.getElementById("potongan").value) || 0;

        let teksList = "";
        let totalOngkir = 0;
        let totalPotonganItem = 0;
        let totalDiskon = 0;
        let nomor = 1;

        document.querySelectorAll("#tabelBody tr").forEach(row => {
          const coret = row.querySelector(".coret")?.checked;
          const namaKons = row.querySelector(".nama")?.value || "";
          const btn = row.querySelector(".ongkir");

          const ongkirAsli = parseFloat(btn.dataset.ongkir_asli || 0);
          const potItem = parseFloat(btn.dataset.pot || 0);
          const potRupiah = Math.round(ongkirAsli * potItem / 100);
          const diskon = parseFloat(btn.dataset.diskon || 0);
          const ongkirRibuan = ongkirAsli / 1000;

          if (coret) {
            // tampilkan juga diskon jika ada, dalam format coret
            if (ongkirAsli > 0) {
              if (diskon && diskon > 0) {
                teksList += `~${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}% - Diskon ${diskon.toLocaleString('id-ID')}~\n`;
              } else {
                teksList += `~${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}%~\n`;
              }
              nomor++;
            }
            return;
          }

          if (ongkirAsli > 0) {
            totalOngkir += ongkirAsli;
            totalPotonganItem += potRupiah;
            totalDiskon += diskon;

            if (diskon && diskon > 0) {
              teksList += `${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}% - Diskon ${diskon.toLocaleString('id-ID')}\n`;
            } else {
              teksList += `${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}%\n`;
            }
            nomor++;
          }
        });

        const totalSetoran = (totalPotonganItem - totalDiskon) - ((totalPotonganItem - totalDiskon) * potGlobal / 100);

        let teks = `Tanggal ${tanggal}\n\n`;
        teks += teksList + "\n";
        teks += `Total Ongkir : ${totalOngkir.toLocaleString("id-ID")}\n`;
        teks += `Total Potongan : ${totalPotonganItem.toLocaleString("id-ID")}\n`;
        teks += `Total Diskon : ${totalDiskon.toLocaleString("id-ID")}\n`;
        teks += `Pot Global : ${potGlobal}%\n\n`;
        teks += `Total Setoran : ${Math.round(totalSetoran).toLocaleString("id-ID")}`;

        return teks;
      }


      function kirimWA() {
        const tanggal = document.getElementById("tanggal").value;
        const nama = document.getElementById("namaUser").value;

        const potGlobal = parseFloat(document.getElementById("potongan").value) || 0;

        if (!isDataValid()) {
          Swal.fire("Gagal", "Data belum lengkap!", "error");
          return;
        }

        let teksList = "";
        let totalOngkir = 0;
        let totalPotonganItem = 0;
        let totalDiskon = 0;
        let nomor = 1;

        document.querySelectorAll("#tabelBody tr").forEach(row => {
          const coret = row.querySelector(".coret")?.checked;

          const namaKons = row.querySelector(".nama")?.value || "";
          const btn = row.querySelector(".ongkir");

          const ongkirAsli = parseFloat(btn.dataset.ongkir_asli || 0);
          const potItem = parseFloat(btn.dataset.pot || 0);
          const potRupiah = Math.round(ongkirAsli * potItem / 100);
          const diskon = parseFloat(btn.dataset.diskon || 0);
          const ongkirRibuan = ongkirAsli / 1000;

          // === Jika CORETDATA ===
          if (coret) {
            if (ongkirAsli > 0) {
              if (diskon && diskon > 0) {
                teksList += `~${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}% - Diskon ${diskon.toLocaleString('id-ID')}~\n`;
              } else {
                teksList += `~${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}%~\n`;
              }
              nomor++;
            }
            return; // tidak dihitung total
          }

          // === Jika NORMAL (tidak dicoret) ===
          if (ongkirAsli > 0) {
            totalOngkir += ongkirAsli;
            totalPotonganItem += potRupiah;
            totalDiskon += diskon;

            if (diskon && diskon > 0) {
              teksList += `${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}% - Diskon ${diskon.toLocaleString('id-ID')}\n`;
            } else {
              teksList += `${nomor}. ${namaKons} - ${ongkirRibuan} x ${potItem}%\n`;
            }
            nomor++;
          }
        });


        const totalSetoran = (totalPotonganItem - totalDiskon) - ((totalPotonganItem - totalDiskon) * potGlobal / 100);

        // ---- FORMAT AKHIR UNTUK WA ----
        const teks = generateText();

        // CEK SEMUA DICORET
        let semuaDicoret = true;
        document.querySelectorAll("#tabelBody tr").forEach((row) => {
          if (!row.querySelector(".coret")?.checked) semuaDicoret = false;
        });
        if (semuaDicoret) {
          Swal.fire("Gagal", "Semua orderan dicoret. Tidak bisa kirim WA.", "error");
          return;
        }

        // FUNGSI FALLBACK COPY
        function fallbackSalin(teks) {
          const textarea = document.createElement("textarea");
          textarea.value = teks;
          textarea.style.position = "fixed";
          textarea.style.top = "-9999px";
          document.body.appendChild(textarea);
          textarea.focus();
          textarea.select();

          let berhasil = false;
          try {
            berhasil = document.execCommand("copy");
          } catch (err) {
            console.error("Fallback clipboard failed", err);
          }
          document.body.removeChild(textarea);
          return berhasil;
        }

        // KONFIRMASI
        Swal.fire({
          title: 'Pastikan Data Sudah Benar',
          text: "Data akan dikirim ke server dan WhatsApp.",
          icon: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Ya, kirim!',
          cancelButtonText: 'Batal',
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33'
        }).then((result) => {
          if (result.isConfirmed) {
            Swal.fire({
              title: 'Mengirim data ke server...',
              allowOutsideClick: false,
              didOpen: () => Swal.showLoading()
            });

            const data = new FormData();
            data.append("tanggal", tanggal);
            data.append("nama", nama);
            data.append("total_ongkir", totalOngkir);
            data.append("total_setoran", totalSetoran);
            data.append("total_pendapatan", totalPotonganItem);
            data.append("orderan", nomor - 1);
            data.append("potongan", potGlobal);
            data.append("tabungan", parseFloat(document.getElementById("tabungan").value || 0));

            // 🔥 Tambahan baru: kumpulkan list Konsumen + detail
            let konsumenList = [];
            document.querySelectorAll("#tabelBody tr").forEach(row => {
              const namaKons = row.querySelector(".nama")?.value.trim();
              const btn = row.querySelector(".ongkir");
              const ongkirAsli = parseFloat(btn.dataset.ongkir_asli || 0);
              const potItem = parseFloat(btn.dataset.pot || 0);
              const potRupiah = Math.round(ongkirAsli * potItem / 100);
              const diskon = parseFloat(btn.dataset.diskon || 0);
              const coret = row.querySelector(".coret")?.checked;
              if (namaKons) {
                konsumenList.push({
                  nama: namaKons,
                  ongkir: ongkirAsli,
                  pot_percent: potItem,
                  pot_rp: potRupiah,
                  diskon: diskon,
                  coret: coret
                });
              }
            });

            // 🔥 Kirim ke server dalam bentuk JSON
            data.append("konsumen_list", JSON.stringify(konsumenList));

            fetch("simpan_data.php", {
                method: "POST",
                body: data
              })
              .then(res => res.text())
              .then(response => {
                console.log("DB response:", response);

                const nomorWA = '+6281181210955';
                const url = `whatsapp://send?phone=${nomorWA}&text=${encodeURIComponent(teks)}`;
                window.open(url, '_blank');

                navigator.clipboard.writeText(teks)
                  .then(() => {
                    Swal.fire("Berhasil!", `Data tersimpan (${response}), WA terkirim & teks disalin.`, "success");
                  })
                  .catch(err => {
                    console.error("Clipboard error:", err);
                    const suksesFallback = fallbackSalin(teks);
                    Swal.fire("Berhasil!", suksesFallback ?
                      "Teks disalin via fallback & WA terkirim." :
                      "WA terkirim namun teks gagal disalin.", "success");
                  });
              })
              .catch(error => {
                console.error(error);
                Swal.fire("Gagal", "Gagal simpan ke database. Pesan tidak dikirim.", "error");
              });
          }
        });
      }

      function salinTeksWA() {
        const teks = generateText();

        navigator.clipboard.writeText(teks)
          .then(() => {
            Swal.fire({
              icon: "success",
              title: "Berhasil Disalin!",
              text: "Teks laporan berhasil disalin.",
              timer: 1500,
              showConfirmButton: false
            });
          })
          .catch(() => {
            Swal.fire("Gagal", "Tidak bisa menyalin teks!", "error");
          });
      }


      function isDataValid() {
        let hasData = false;
        document.querySelectorAll("#tabelBody tr").forEach((row) => {
          const btn = row.querySelector(".ongkir");
          const ongkir = parseFloat(btn.dataset.ongkir_asli || 0);
          if (ongkir > 0) {
            hasData = true;
          }
        });
        return hasData;
      }

      function parseNominal(nominal) {
        return parseFloat(nominal.replace(/[^\d]/g, "")) || 0;
      }

      document.addEventListener("DOMContentLoaded", function() {
        const savedTabungan = localStorage.getItem('tabungan_total');
        if (savedTabungan) {
          const value = parseInt(savedTabungan);
          document.getElementById("tabungan").value = value;
          document.getElementById("showTabunganBtn").innerHTML = `+ Tabungan: ${value.toLocaleString('id-ID')}`;
        }

        const savedData = JSON.parse(localStorage.getItem('ongkirData'));
        if (savedData) {
          document.getElementById("tanggal").value = savedData.tanggal;
          document.getElementById("tabungan").value = savedData.tabungan;
          document.getElementById("potongan").value = savedData.potongan;
          savedData.list.forEach(item => {
            // item mungkin berbentuk string atau angka -> pastikan number
            const ongkirNum = Number(item.ongkir) || 0;
            const potNum = Number(item.pot) || 25;
            const diskonNum = Number(item.diskon) || 0;
            tambahList(item.nama || "", ongkirNum, item.coret || false, potNum, diskonNum);
          });
          hitungTotal();

        } else {
          document.getElementById("tanggal").valueAsDate = new Date();
        }
      });

      function autoScrollOnFocus(id) {
        const el = document.getElementById(id);
        if (el) {
          el.addEventListener("focus", () => {
            setTimeout(() => {
              el.scrollIntoView({
                behavior: "smooth",
                block: "center"
              });
            }, 300);
          });
        }
      }

      function simpanKeLocalStorage() {
        const data = {
          tanggal: document.getElementById("tanggal").value,
          tabungan: document.getElementById("tabungan").value,
          potongan: document.getElementById("potongan").value,
          list: []
        };

        document.querySelectorAll("#tabelBody tr").forEach(row => {
          const nama = row.querySelector(".nama").value;
          const btn = row.querySelector(".ongkir");
          const coret = !!row.querySelector(".coret").checked;

          const ongkir_asli = Number(btn.dataset.ongkir_asli || 0);
          const pot = Number(btn.dataset.pot || 25);
          const diskon = Number(btn.dataset.diskon || 0);

          data.list.push({
            nama,
            ongkir: ongkir_asli,
            pot,
            diskon,
            coret
          });
        });

        localStorage.setItem('ongkirData', JSON.stringify(data));
      }

      // sekarang tambahList menerima (nama, ongkirAsli, coret, pot, diskon)
      function tambahList(nama = "", ongkir = 0, coret = false, pot = 25, diskon = 0) {
        const tbody = document.getElementById("tabelBody");
        const row = document.createElement("tr");

        row.innerHTML = `
    <td>${tbody.children.length + 1}</td>
    <td><input type="text" class="nama" value="${nama}" placeholder="" oninput="simpanKeLocalStorage()"/></td>
<td>
  <input type="tel" class="ongkir"
    value=""
    placeholder="Input"
    onclick="inputOngkirPopup(this)"
    readonly
    style="cursor: pointer; background-color:#f1f1f1;"
  />
</td>
    <td><input type="checkbox" class="coret" ${coret ? 'checked' : ''} onchange="simpanKeLocalStorage(); hitungTotal()"/></td>
    <td><button onclick="hapusRow(this)"></button></td>
  `;
        tbody.appendChild(row);

        // set dataset values pada input ongkir (jika ada)
        const btn = row.querySelector(".ongkir");
        const potNum = Number(pot || 25);
        const ongkirNum = Number(ongkir || 0);
        const diskonNum = Number(diskon || 0);
        const potRupiah = Math.round(ongkirNum * potNum / 100);
        const setelahPotong = ongkirNum - potRupiah;
        const setelahDiskon = setelahPotong - diskonNum;

        if (ongkirNum > 0) {
          btn.dataset.ongkir_asli = ongkirNum;
          btn.dataset.pot = potNum;
          btn.dataset.potongan = potRupiah;
          btn.dataset.setelahPotong = setelahPotong;
          btn.dataset.diskon = diskonNum;
          btn.dataset.setelahDiskon = setelahDiskon;
          try {
            btn.value = ongkirNum.toLocaleString("id-ID");
          } catch (e) {
            btn.value = ongkirNum;
          }
        } else {
          // kosongkan dataset
          btn.dataset.ongkir_asli = 0;
          btn.dataset.pot = potNum;
          btn.dataset.potongan = 0;
          btn.dataset.setelahPotong = 0;
          btn.dataset.diskon = 0;
          btn.dataset.setelahDiskon = 0;
          btn.value = "";
        }

        const namaInput = row.querySelector(".nama");
        if (namaInput && !ongkir) {
          namaInput.focus();
        }
        const container = document.querySelector(".table-container");
        setTimeout(() => {
          container.scrollTop = container.scrollHeight;
        }, 200);
      }


      function hapusRow(btn) {
        const row = btn.closest("tr");
        row.remove();
        simpanKeLocalStorage();
        hitungTotal();
      }

      function hitungTotal() {
        let totalOngkirAsli = 0;
        let totalPotongan = 0; // total potongan item (rp)
        let totalSetelahPotong = 0; // sum setelah potong (sebelum diskon)
        let totalDiskon = 0;
        let totalSetelahDiskon = 0;
        let jumlahOrderan = 0;

        const potonganGlobal = parseFloat(document.getElementById("potongan").value || 0);

        document.querySelectorAll("#tabelBody tr").forEach(row => {
          const btn = row.querySelector(".ongkir");

          const ongkirAsli = parseFloat(btn.dataset.ongkir_asli || 0);
          const potonganItem = parseFloat(btn.dataset.potongan || 0);
          const setelahPotong = parseFloat(btn.dataset.setelahPotong || 0);
          const diskon = parseFloat(btn.dataset.diskon || 0);
          const setelahDiskon = parseFloat(btn.dataset.setelahDiskon || 0);

          const coret = row.querySelector(".coret")?.checked;

          if (!coret) {
            totalOngkirAsli += ongkirAsli;
            totalPotongan += potonganItem;
            totalSetelahPotong += setelahPotong;
            totalDiskon += diskon;
            totalSetelahDiskon += setelahDiskon;
          }

          jumlahOrderan++;
        });

        // Global potongan diterapkan ke (totalPotongan - totalDiskon)
        const base = (totalPotongan - totalDiskon);
        const totalSetoran = base - (base * potonganGlobal / 100);

        // SET OUTPUT
        document.getElementById("totalOngkir").value =
          "Rp " + totalOngkirAsli.toLocaleString("id-ID");
        document.getElementById("totalOngkir").dataset.value = totalOngkirAsli;

        document.getElementById("totalPendapatan").value =
          "Rp " + totalSetelahPotong.toLocaleString("id-ID");
        document.getElementById("totalPendapatan").dataset.value = totalSetelahPotong;

        document.getElementById("totalDiskon").value =
          "Rp " + totalDiskon.toLocaleString("id-ID");
        document.getElementById("totalDiskon").dataset.value = totalDiskon;

        document.getElementById("totalSetoran").value =
          "Rp " + Math.round(totalSetoran).toLocaleString("id-ID");
        document.getElementById("totalSetoran").dataset.value = totalSetoran;

        document.getElementById("orderan").value = jumlahOrderan;
        document.getElementById("orderan").dataset.value = jumlahOrderan;

        simpanKeLocalStorage();
      }

      function bersihkan() {
        Swal.fire({
          title: 'Lanjut hapus?',
          icon: 'warning',
          background: '#ffe13d',
          iconColor: '#f25b00',
          allowOutsideClick: false,
          allowEscapeKey: false,
          customClass: {
            popup: 'animated tada',
            title: 'bold-text',
            text: 'text-primary',
          },
          showCancelButton: true,
          confirmButtonText: 'Ya, hapus!',
          cancelButtonText: 'Tidak',
          confirmButtonColor: '#1f1f1f',
          cancelButtonColor: '#3b3b3b',
        }).then((result) => {
          if (result.isConfirmed) {
            document.getElementById("tabelBody").innerHTML = "";
            document.getElementById("tabungan").value = "";
            document.getElementById("potongan").value = "0";
            document.getElementById("showTabunganBtn").innerHTML = "+ Tabungan"; // pakai innerHTML

            // Hapus semua data tabungan dari localStorage
            ["tabungan_wajib", "tabungan_sukarela", "tabungan_total", "id_tabungan"].forEach(key => localStorage.removeItem(key));
            localStorage.removeItem('ongkirData');

            hitungTotal();
            simpanKeLocalStorage();

            Swal.fire({
              icon: 'success',
              title: 'Berhasil Di hapus!',
              showConfirmButton: false,
              timer: 1500,
            });
          } else {
            console.log("Batal menghapus.");
          }
        });
      }


      autoScrollOnFocus("tabungan");
      autoScrollOnFocus("potongan");
      document.querySelectorAll("#tabelBody td").forEach(input => {
        input.addEventListener("focus", () => {
          setTimeout(() => {
            input.scrollIntoView({
              behavior: "smooth",
              block: "center"
            });
          }, 300); // Delay untuk memberi waktu keyboard muncul
        });
      });

      function formatOngkir(input) {
        let val = parseFloat(input.value);
        if (!isNaN(val) && val < 1000) {
          input.value = Math.round(val * 1000);
          hitungTotal();
          simpanKeLocalStorage();
        }
      }

      function cekEnter(event, input) {
        if (event.key === "Enter") {
          event.preventDefault();
          formatOngkir(input); // pastikan nilainya dikalikan 1000 kalau perlu
          const row = input.closest("tr");
          const nama = row.querySelector(".nama").value;
          const ongkir = row.querySelector(".ongkir").value;
          if (ongkir) {
            tambahList(); // tambahkan baris baru hanya jika nama dan ongkir diisi
          }
        }
      }

      function toggleDropdown() {
        const menu = document.getElementById("dropdownMenu");
        menu.style.display = menu.style.display === "block" ? "none" : "block";
      }

      function setPotongan(value) {
        document.getElementById("potongan").value = value;
        document.getElementById("selectedPotongan").innerText = value + "%";
        hitungTotal();
        document.getElementById("dropdownMenu").style.display = "none";
      }

      window.addEventListener("click", function(e) {
        const dropdown = document.getElementById("dropdownMenu");
        const button = document.getElementById("dropdownBtn");
        if (!dropdown.contains(e.target) && !button.contains(e.target)) {
          dropdown.style.display = "none";
        }
      });

      window.onload = function() {
        const tanggalInput = document.getElementById("tanggal");
        const today = new Date();
        const dd = String(today.getDate()).padStart(2, '0');
        const mm = String(today.getMonth() + 1).padStart(2, '0'); // Bulan dimulai dari 0
        const yyyy = today.getFullYear();
        const formattedDate = yyyy + '-' + mm + '-' + dd;
        tanggalInput.value = formattedDate;
      };

      Swal.fire({
        title: 'Memuat Halaman',
        html: 'Silakan tunggu...',
        allowOutsideClick: false,
        showConfirmButton: false,
        timer: 200,
        timerProgressBar: false,
        didOpen: () => {
          Swal.showLoading(); // ← ini OK di versi terbaru
        }
      });
    </script>
</body>

</html>