<?php

include 'session.php';
include '../config/koneksi.php';

/* =========================================================
   TAMBAH PRODUK
========================================================= */

if (isset($_POST['tambah'])) {

    $id_kategori = mysqli_real_escape_string(
        $conn,
        $_POST['id_kategori']
    );

    $nama_produk = mysqli_real_escape_string(
        $conn,
        $_POST['nama_produk']
    );

    $harga = (float) $_POST['harga'];

    $deskripsi = mysqli_real_escape_string(
        $conn,
        $_POST['deskripsi']
    );

    $nama_penjual = mysqli_real_escape_string(
        $conn,
        $_POST['nama_penjual']
    );

    $no_hp = mysqli_real_escape_string(
        $conn,
        $_POST['no_hp']
    );


    /* =====================================================
       UPLOAD FOTO
    ===================================================== */

    $foto = "";

    if (
        isset($_FILES['foto']) &&
        $_FILES['foto']['error'] == 0
    ) {

        $nama_file = $_FILES['foto']['name'];
        $tmp_file  = $_FILES['foto']['tmp_name'];
        $ukuran    = $_FILES['foto']['size'];

        $ekstensi = strtolower(
            pathinfo($nama_file, PATHINFO_EXTENSION)
        );

        $ekstensi_diizinkan = [
            'jpg',
            'jpeg',
            'png'
        ];


        /* Cek format */

        if (!in_array($ekstensi, $ekstensi_diizinkan)) {

            echo "<script>
                    alert('Format foto harus JPG, JPEG, atau PNG.');
                    window.location='produk_admin.php';
                  </script>";

            exit;
        }


        /* Cek ukuran maksimal 2 MB */

        if ($ukuran > 2 * 1024 * 1024) {

            echo "<script>
                    alert('Ukuran foto maksimal 2 MB.');
                    window.location='produk_admin.php';
                  </script>";

            exit;
        }


        /* Buat nama file unik */

        $foto = time() . '_' . preg_replace(
            '/[^A-Za-z0-9._-]/',
            '_',
            $nama_file
        );


        /* Upload */

        move_uploaded_file(
            $tmp_file,
            "../assets/img/" . $foto
        );
    }


    /* =====================================================
       INSERT PRODUK
    ===================================================== */

    $insert = mysqli_query(
        $conn,
        "
        INSERT INTO produk (
            id_kategori,
            nama_produk,
            harga,
            deskripsi,
            nama_penjual,
            no_hp,
            foto
        )
        VALUES (
            '$id_kategori',
            '$nama_produk',
            '$harga',
            '$deskripsi',
            '$nama_penjual',
            '$no_hp',
            '$foto'
        )
        "
    );


    if ($insert) {

        echo "<script>
                alert('Produk berhasil ditambahkan.');
                window.location='produk_admin.php';
              </script>";

        exit;

    } else {

        echo "<script>
                alert('Produk gagal ditambahkan.');
                window.location='produk_admin.php';
              </script>";

        exit;
    }
}


/* =========================================================
   HAPUS PRODUK
========================================================= */

if (isset($_GET['hapus'])) {

    $id = (int) $_GET['hapus'];


    /* Ambil data foto */

    $queryFoto = mysqli_query(
        $conn,
        "
        SELECT foto
        FROM produk
        WHERE id_produk = '$id'
        "
    );

    $dataFoto = mysqli_fetch_assoc($queryFoto);


    /* Hapus file foto */

    if (
        $dataFoto &&
        !empty($dataFoto['foto'])
    ) {

        $fileFoto =
            "../assets/img/" . $dataFoto['foto'];

        if (file_exists($fileFoto)) {

            unlink($fileFoto);
        }
    }


    /* Hapus data produk */

    mysqli_query(
        $conn,
        "
        DELETE FROM produk
        WHERE id_produk = '$id'
        "
    );


    echo "<script>
            alert('Produk berhasil dihapus.');
            window.location='produk_admin.php';
          </script>";

    exit;
}

?>

<!DOCTYPE html>

<html lang="id">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Kelola Produk Desa
    </title>


    <link
        rel="stylesheet"
        href="../assets/css/produk_admin.css"
    >

</head>


<body>


<div class="container">


    <!-- =====================================================
         HEADER
    ====================================================== -->

    <div class="header">

        <a
            href="dashboard.php"
            class="btn-kembali"
        >

            ← Dashboard

        </a>


        <h1>

            🛍 Kelola Produk Desa

        </h1>

    </div>



    <!-- =====================================================
         FORM TAMBAH PRODUK
    ====================================================== -->

    <div class="card">

        <h2>
            Tambah Produk Baru
        </h2>


        <form
            action=""
            method="POST"
            enctype="multipart/form-data"
        >


            <!-- KATEGORI -->

            <div class="form-group">

                <label>
                    Kategori Produk
                </label>


                <select
                    name="id_kategori"
                    required
                >

                    <option value="">
                        -- Pilih Kategori --
                    </option>


                    <?php

                    $kategori = mysqli_query(
                        $conn,
                        "
                        SELECT *
                        FROM kategori_produk
                        ORDER BY nama_kategori ASC
                        "
                    );


                    while (
                        $k = mysqli_fetch_assoc($kategori)
                    ) {

                    ?>

                        <option
                            value="<?= $k['id_kategori']; ?>"
                        >

                            <?= htmlspecialchars(
                                $k['nama_kategori']
                            ); ?>

                        </option>

                    <?php

                    }

                    ?>

                </select>

            </div>



            <!-- NAMA PRODUK -->

            <div class="form-group">

                <label>
                    Nama Produk
                </label>


                <input
                    type="text"
                    name="nama_produk"
                    placeholder="Masukkan nama produk"
                    required
                >

            </div>



            <!-- HARGA -->

            <div class="form-group">

                <label>
                    Harga Produk
                </label>


                <input
                    type="number"
                    name="harga"
                    placeholder="Contoh: 25000"
                    min="0"
                    required
                >

            </div>



            <!-- DESKRIPSI -->

            <div class="form-group">

                <label>
                    Deskripsi Produk
                </label>


                <textarea
                    name="deskripsi"
                    rows="5"
                    placeholder="Masukkan deskripsi produk"
                ></textarea>

            </div>



            <!-- NAMA PENJUAL -->

            <div class="form-group">

                <label>
                    Nama Penjual
                </label>


                <input
                    type="text"
                    name="nama_penjual"
                    placeholder="Masukkan nama penjual"
                >

            </div>



            <!-- NOMOR WHATSAPP -->

            <div class="form-group">

                <label>
                    Nomor WhatsApp
                </label>


                <input
                    type="text"
                    name="no_hp"
                    placeholder="Contoh: 081234567890"
                >

            </div>



            <!-- FOTO -->

            <div class="form-group">

                <label>
                    Foto Produk
                </label>


                <input
                    type="file"
                    id="foto"
                    name="foto"
                    accept=".jpg,.jpeg,.png"
                >


                <div class="info-file">

                    ✔ Format: JPG, JPEG, PNG
                    <br>

                    ✔ Maksimal ukuran: 2 MB

                </div>


                <p id="nama-file">

                    Belum ada file dipilih

                </p>


                <!-- PREVIEW FOTO -->

                <div class="preview-gambar">

                    <img
                        id="preview"
                        src=""
                        alt="Preview Produk"
                    >

                </div>

            </div>



            <!-- TOMBOL SIMPAN -->

            <div class="aksi">

                <button
                    type="submit"
                    name="tambah"
                    class="btn-simpan"
                >

                    💾 Simpan Produk

                </button>

            </div>


        </form>

    </div>



    <!-- =====================================================
         DAFTAR PRODUK
    ====================================================== -->

    <div class="card table-card">


        <div class="table-header">

            <h2>
                Daftar Produk Desa
            </h2>


            <input
                type="text"
                id="cariProduk"
                placeholder="🔍 Cari produk..."
            >

        </div>



        <table id="tabelProduk">


            <thead>

                <tr>

                    <th>
                        No
                    </th>

                    <th>
                        Foto
                    </th>

                    <th>
                        Produk
                    </th>

                    <th>
                        Kategori
                    </th>

                    <th>
                        Penjual
                    </th>

                    <th>
                        WhatsApp
                    </th>

                    <th>
                        Aksi
                    </th>

                </tr>

            </thead>



            <tbody>


            <?php

            $no = 1;


            $data = mysqli_query(
                $conn,
                "
                SELECT
                    produk.*,
                    kategori_produk.nama_kategori
                FROM produk

                LEFT JOIN kategori_produk
                    ON produk.id_kategori =
                       kategori_produk.id_kategori

                ORDER BY produk.id_produk DESC
                "
            );


            if (
                mysqli_num_rows($data) > 0
            ) {


                while (
                    $d = mysqli_fetch_assoc($data)
                ) {

            ?>


                <tr>


                    <!-- NO -->

                    <td>

                        <?= $no++; ?>

                    </td>



                    <!-- FOTO -->

                    <td>

                        <?php

                        if (
                            !empty($d['foto']) &&
                            file_exists(
                                "../assets/img/" .
                                $d['foto']
                            )
                        ) {

                        ?>

                            <img
                                src="../assets/img/<?= htmlspecialchars($d['foto']); ?>"
                                class="foto-produk"
                                alt="<?= htmlspecialchars($d['nama_produk']); ?>"
                            >

                        <?php

                        } else {

                        ?>

                            <div class="foto-kosong">
                                🛍
                            </div>

                        <?php

                        }

                        ?>

                    </td>



                    <!-- PRODUK -->

                    <td>

                        <strong>

                            <?= htmlspecialchars(
                                $d['nama_produk']
                            ); ?>

                        </strong>

                        <br>

                        <span class="harga">

                            Rp <?= number_format(
                                $d['harga'],
                                0,
                                ',',
                                '.'
                            ); ?>

                        </span>

                    </td>



                    <!-- KATEGORI -->

                    <td>

                        <span class="kategori">

                            <?= htmlspecialchars(
                                $d['nama_kategori']
                            ); ?>

                        </span>

                    </td>



                    <!-- PENJUAL -->

                    <td>

                        <?= htmlspecialchars(
                            $d['nama_penjual']
                        ); ?>

                    </td>



                    <!-- WHATSAPP -->

                    <td>

                        <?php

                        $nomor =
                            preg_replace(
                                '/[^0-9]/',
                                '',
                                $d['no_hp']
                            );


                        if (
                            !empty($nomor)
                        ) {

                            if (
                                substr(
                                    $nomor,
                                    0,
                                    1
                                ) == '0'
                            ) {

                                $nomor =
                                    '62' .
                                    substr(
                                        $nomor,
                                        1
                                    );
                            }

                        ?>

                            <a
                                href="https://wa.me/<?= $nomor; ?>"
                                target="_blank"
                                class="wa-link"
                            >

                                <?= htmlspecialchars(
                                    $d['no_hp']
                                ); ?>

                            </a>

                        <?php

                        } else {

                            echo '-';

                        }

                        ?>

                    </td>



                    <!-- AKSI -->

                    <td class="aksi-table">


                        <a
                            href="edit_produk_admin.php?id=<?= $d['id_produk']; ?>"
                            class="btn-edit"
                        >

                            ✏ Edit

                        </a>

                        <a
                            href="produk_admin.php?hapus=<?= $d['id_produk']; ?>"
                            class="btn-hapus"
                            onclick="return confirm('Yakin ingin menghapus produk ini?')"
                        >

                            🗑 Hapus

                        </a>


                    </td>


                </tr>


            <?php

                }

            } else {

            ?>


                <tr>

                    <td
                        colspan="7"
                        class="data-kosong"
                    >

                        🛍 Belum ada produk yang
                        ditambahkan.

                    </td>

                </tr>


            <?php

            }

            ?>


            </tbody>

        </table>

    </div>


</div>



<!-- =====================================================
     JAVASCRIPT
====================================================== -->

<script
    src="../assets/js/produk_admin.js"
></script>


</body>

</html>