/* =========================================
   PREVIEW GAMBAR
========================================= */

const foto = document.getElementById("foto");
const preview = document.getElementById("preview");
const namaFile = document.getElementById("nama-file");

if (foto) {

    foto.addEventListener("change", function () {

        const file = this.files[0];

        if (!file) {

            preview.style.display = "none";
            preview.src = "";
            namaFile.innerHTML = "Belum ada file dipilih";

            return;
        }

        /* ===========================
           VALIDASI FORMAT
        =========================== */

        const ekstensi = ["image/jpeg", "image/jpg", "image/png"];

        if (!ekstensi.includes(file.type)) {

            alert("Format gambar harus JPG, JPEG, atau PNG.");

            this.value = "";

            preview.style.display = "none";
            preview.src = "";
            namaFile.innerHTML = "Belum ada file dipilih";

            return;
        }

        /* ===========================
           VALIDASI UKURAN 2 MB
        =========================== */

        if (file.size > 2 * 1024 * 1024) {

            alert("Ukuran gambar maksimal 2 MB.");

            this.value = "";

            preview.style.display = "none";
            preview.src = "";
            namaFile.innerHTML = "Belum ada file dipilih";

            return;
        }

        /* ===========================
           NAMA FILE
        =========================== */

        namaFile.innerHTML = file.name;

        /* ===========================
           PREVIEW
        =========================== */

        const reader = new FileReader();

        reader.onload = function (e) {

            preview.src = e.target.result;
            preview.style.display = "block";

        }

        reader.readAsDataURL(file);

    });

}

/* =========================================
   PENCARIAN PRODUK
========================================= */

const cari = document.getElementById("cariProduk");

if (cari) {

    cari.addEventListener("keyup", function () {

        const keyword = this.value.toLowerCase();

        const baris = document.querySelectorAll("#tabelProduk tbody tr");

        baris.forEach(function (row) {

            const isi = row.textContent.toLowerCase();

            if (isi.indexOf(keyword) > -1) {

                row.style.display = "";

            } else {

                row.style.display = "none";

            }

        });

    });

}