<?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>
  <link rel="stylesheet" href="css/navbar.css">
  <link rel="stylesheet" href="css/order.css">
  <title>Form Order</title>
<body>

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

    <div class="total-box">
      <div class="icon-wrapper">
        <label for="orderan">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>
      <div class="icon-wrapper">
        <label for="orderan">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>
      <div class="icon-wrapper">
        <div class="input-container">
          <input type="tel" id="ongkos" placeholder="Ongkos Kirim" autocomplete="off" />
        </div>
      </div>
    </div>

    <div class="flex-btns">
      <button onclick="tambahList()" title="Tambah List">
        <i class="fab fa-plus"></i>
      </button>
      <button onclick="salinOrderan()" title="Salin">
        <i class="fas fa-copy"></i>
      </button>
      <button onclick="bersihkan()" title="Bersihkan">
        <i class="fas fa-trash"></i>
      </button>
    </div>

    <div class="table-container">
      <table>
        <thead>
          <tr>
            <th>No</th>
            <th>Item</th>
            <th>Harga</th>
            <th>Del</th>
          </tr>
        </thead>
        <tbody id="tabelBody"></tbody>
        <tr>
          <td colspan="4" style="text-align:center;color:gray;">Klik ( + ) untuk menambah kolom</td>
        </tr>
      </table>
    </div>

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

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

      $id_user = $_SESSION['user']['id'];

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

      $bank = $dataUser['bank'];
      $no_rek = $dataUser['no_rek'];
      $an = $dataUser['a_n'];
      ?>

      <script>
        const userBank = "<?php echo $bank; ?>";
        const userRekening = "<?php echo $no_rek; ?>";
        const userAN = "<?php echo $an; ?>";
      </script>

      <script>
        function salinOrderan() {
          // ✅ VALIDASI DATA WAJIB DIISI
          const valid = Array.from(document.querySelectorAll("#tabelBody tr")).every(row => {
            const nama = row.querySelector(".nama")?.value.trim();
            const harga = parseNominal(row.querySelector(".harga")?.value || "0");
            return nama && harga >= 0; // ubah dari > 0 ke >= 0
          });

          if (!valid || parseNominal(document.getElementById("ongkos").value) < 0) {
            Swal.fire({
              icon: 'warning',
              title: 'Data ada yang Kosong !',
              showConfirmButton: true,
              confirmButtonText: 'Oke',
              background: '#ffe13d',
              iconColor: '#f25b00',
              customClass: {
                popup: 'animated tada',
                title: 'bold-text',
                text: 'text-primary',
              },
            });
            return;
          }
          let hasilSalinan = "";

          // Format tanggal (contoh: 10 Mei 2025)
          const tanggalInput = document.getElementById("tanggal")?.value || new Date().toISOString().slice(0, 10);
          const [year, month, day] = tanggalInput.split("-");
          const bulanIndonesia = [
            "Januari", "Februari", "Maret", "April", "Mei", "Juni",
            "Juli", "Agustus", "September", "Oktober", "November", "Desember"
          ];
          const tanggalFormat = `${parseInt(day)} ${bulanIndonesia[parseInt(month) - 1]} ${year}`;

          // Judul dan header
          hasilSalinan += `𝐓𝐈𝐎𝐑 𝐃𝐄𝐋𝐈𝐕𝐄𝐑𝐘 | ${tanggalFormat}\n`;
          hasilSalinan += `Driver : *<?php echo $_SESSION['user']['nama_asli']; ?>*\n\n`;
          hasilSalinan += `📋𝙻𝚒𝚜𝚝 𝙿𝚎𝚖𝚋𝚊𝚢𝚊𝚛𝚊𝚗 :\n`;
          hasilSalinan += `──────────────────────\n`;

          // Daftar item
          document.querySelectorAll("#tabelBody tr").forEach(row => {
            const nama = row.querySelector(".nama")?.value.trim() || "";
            const harga = row.querySelector(".harga")?.value.trim() || "0";

            if (nama) {
              const hargaFormat = "Rp. " + parseNominal(harga).toLocaleString("id-ID");
              hasilSalinan += `•  ${nama} ( ${hargaFormat} )\n`;
            }
          });

          hasilSalinan += `──────────────────────\n`;
          const totalBelanja = "Rp. " + parseNominal(document.getElementById("totalBelanja").value).toLocaleString("id-ID");
          const ongkos = "Rp. " + parseNominal(document.getElementById("ongkos").value).toLocaleString("id-ID");
          const grandTotal = "Rp. " + parseNominal(document.getElementById("grandTotal").value).toLocaleString("id-ID");
          hasilSalinan += `Total Belanja : ${totalBelanja}\n`;
          hasilSalinan += `𝙾𝚗𝚐𝚔𝚒𝚛 :  ${ongkos}\n`;
          hasilSalinan += `──────────────────────\n`;
          hasilSalinan += `𝚃𝚘𝚝𝚊𝚕 : ${grandTotal}\n`;
          hasilSalinan += `──────────────────────\n\n`;
          hasilSalinan += `Pembayaran Bisa Cash/Transfer:\n`;
          hasilSalinan += `${userBank} ${userRekening} ${userAN}\n\n`;
          hasilSalinan += `Untuk Jaminan Antar-Kirim, Selalu Order Melalui Admin\n`;
          hasilSalinan += `Admin TIOR : +6281181210955\n\n`;
          hasilSalinan += `𝘛𝘦𝘳𝘪𝘮𝘢𝘬𝘢𝘴𝘪𝘩 𝘛𝘦𝘭𝘢𝘩 𝘔𝘦𝘯𝘨𝘨𝘶𝘯𝘢𝘬𝘢𝘯 𝘑𝘢𝘴𝘢 𝘛𝘐𝘖𝘙 𝘋𝘦𝘭𝘪𝘷𝘦𝘳𝘺`;
          // Salin ke clipboard
          navigator.clipboard.writeText(hasilSalinan).then(() => {
            Swal.fire({
              icon: 'success',
              title: 'Disalin!',
              text: 'Orderan telah disalin ke clipboard.',
              timer: 1500,
              showConfirmButton: false
            });
          }).catch(() => {
            alert("Gagal menyalin orderan.");
          });
        }

        function hitungTotal() {
          const rows = document.querySelectorAll("#tabelBody tr");
          let totalBelanja = 0;

          rows.forEach(row => {
            const hargaInput = row.querySelector(".harga");
            if (hargaInput) {
              const nilai = parseNominal(hargaInput.value);
              totalBelanja += nilai;
            }
          });

          // Tampilkan total belanja
          document.getElementById("totalBelanja").value = "Rp " + totalBelanja.toLocaleString();
          // Ambil ongkos tambahan dari input #ongkos (jika ada)
          const ongkosTambahan = parseNominal(document.getElementById("ongkos").value);

          // Hitung grand total
          const grandTotal = totalBelanja + ongkosTambahan;
          document.getElementById("grandTotal").value = "Rp " + grandTotal.toLocaleString();
        }

        function isDataValid() {
          let hasData = false;
          document.querySelectorAll("#tabelBody tr").forEach((row) => {
            const harga = row.querySelector(".harga")?.value || "0";
            if (parseNominal(harga) > 0) {
              hasData = true;
            }
          });
          return hasData;
        }

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

        document.addEventListener("DOMContentLoaded", function () {
          const savedData = JSON.parse(localStorage.getItem('hargaData'));
          if (savedData) {
            document.getElementById("tanggal").value = savedData.tanggal;
            document.getElementById("ongkos").value = savedData.ongkos || "";
            document.getElementById("ongkos").addEventListener("input", function () {
              hitungTotal();
              simpanKeLocalStorage();
            });
            document.getElementById("ongkos").addEventListener("blur", function () {
              formatharga(this);
            });

            savedData.list.forEach(item => {
              tambahList(item.nama, item.harga);
            });
            hitungTotal();
          } else {
            document.getElementById("tanggal").valueAsDate = new Date();
          }
        });


        function simpanKeLocalStorage() {
          const data = {
            tanggal: document.getElementById("tanggal").value,
            ongkos: document.getElementById("ongkos").value, // Tambahkan baris ini
            list: []
          };

          document.querySelectorAll("#tabelBody tr").forEach(row => {
            const nama = row.querySelector(".nama").value;
            const harga = row.querySelector(".harga").value;
            data.list.push({ nama, harga });
          });

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


        function tambahList(nama = "", harga = "", coret = false) {
          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="harga" value="${harga}" placeholder="" 
    onblur="formatharga(this)" 
    onkeydown="cekEnter(event, this)" 
    oninput="simpanKeLocalStorage(); hitungTotal()"/></td>
    <td><button onclick="hapusRow(this)"></button></td>
  `;
          tbody.appendChild(row);

          // Fokus ke input nama
          const namaInput = row.querySelector(".nama");
          if (namaInput && !harga) {
            namaInput.focus();
          }

          // Scroll kontainernya, bukan hanya elemennya
          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 bersihkan() {
          Swal.fire({
            title: 'Lanjut hapus?',
            icon: 'warning',
            background: '#ffe13d',
            iconColor: '#f25b00',
            allowOutsideClick: false, // Ini mencegah klik di luar popup
            allowEscapeKey: false,    // Ini mencegah popup ditutup dengan tombol Escape
            customClass: {
              popup: 'animated tada',  // Animasi popup
              title: 'bold-text',
              text: 'text-primary',
            },
            showCancelButton: true,
            confirmButtonText: 'Ya, hapus!',
            cancelButtonText: 'Tidak',
            confirmButtonColor: '#1f1f1f',
            cancelButtonColor: '#3b3b3b',
          }).then((result) => {
            if (result.isConfirmed) {
              // Jika pengguna memilih Ya
              document.getElementById("ongkos").value = "";
              document.getElementById("tabelBody").innerHTML = "";
              hitungTotal()
              simpanKeLocalStorage();

              // Menampilkan notifikasi setelah berhasil menghapus
              Swal.fire({
                icon: 'success',
                title: 'Berhasil Di hapus!',
                showConfirmButton: false,
                timer: 1500, // Menampilkan notifikasi selama 1,5 detik
              });
            } else {
              // Jika pengguna memilih Tidak
              console.log("Batal menghapus.");
            }
          });
        }

        // Untuk semua input dalam tabel, bisa gunakan querySelectorAll
        document.querySelectorAll("#tabelBody td").forEach(input => {
          input.addEventListener("focus", () => {
            setTimeout(() => {
              input.scrollIntoView({ behavior: "smooth", block: "center" });
            }, 300); // Delay untuk memberi waktu keyboard muncul
          });
        });

        function formatharga(input) {
          let raw = input.value.replace(/[^\d.,]/g, '').replace(',', '.'); // Ijinkan titik atau koma
          let num = parseFloat(raw);

          if (!isNaN(num)) {
            if (num < 1000) {
              num *= 1000;
            }
            input.value = Math.round(num).toString();
          } else {
            input.value = '';
          }

          hitungTotal();
          simpanKeLocalStorage();
        }

        function cekEnter(event, input) {
          if (event.key === "Enter") {
            event.preventDefault();
            formatharga(input); // pastikan nilainya dikalikan 1000 kalau perlu

            const row = input.closest("tr");
            const nama = row.querySelector(".nama").value;
            const harga = row.querySelector(".harga").value;

            if (harga) {
              tambahList(); // tambahkan baris baru hanya jika nama dan harga diisi
            }
          }
        }

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

        // Tutup dropdown jika klik di luar
        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");

          // Mengatur nilai input tanggal ke tanggal saat ini
          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();

          // Format tanggal dalam format yyyy-mm-dd
          const formattedDate = yyyy + '-' + mm + '-' + dd;

          // Set nilai input tanggal
          tanggalInput.value = formattedDate;
        };

        //memuat halaman
        Swal.fire({
          title: 'Memuat Halaman',
          html: 'Silakan tunggu...',
          allowOutsideClick: false,
          showConfirmButton: false,
          timer: 200, // bisa diatur lebih lama jika perlu
          timerProgressBar: false,
          didOpen: () => {
            Swal.showLoading();
          }
        });

        //menutup footer
        const footer = document.getElementById('footer');
        let initialHeight = window.innerHeight;

        window.addEventListener('resize', () => {
          const currentHeight = window.innerHeight;
          const heightDiff = initialHeight - currentHeight;

          if (heightDiff > 100) {
            // Anggap keyboard muncul
            footer.style.display = 'none';
          } else {
            // Keyboard disembunyikan
            footer.style.display = 'block';
          }
        });

        document.getElementById("ongkos").addEventListener("blur", function () {
          formatharga(this);

          const value = parseInt(this.value.replace(/\D/g, '') || "0");
          if (value < 12000) {
            Swal.fire({
              icon: 'warning',
              title: 'Ongkos terlalu rendah!',
              text: 'Nilai ongkos kirim minimal adalah 12.000',
              confirmButtonText: 'OK'
            }).then(() => {
              this.value = '12000';
              hitungTotal();
              simpanKeLocalStorage();
            });
          }
        });

      </script>

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

</body>
</html>