<?php

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

/* =====================================================
   CEK ID BERITA
===================================================== */

if (!isset($_GET['id'])) {

    echo "<script>
            alert('ID berita tidak ditemukan');
            window.location='berita_admin.php';
          </script>";

    exit;
}

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


/* =====================================================
   AMBIL DATA BERITA
===================================================== */

$query = mysqli_query($conn, "
    SELECT *
    FROM berita
    WHERE id_berita = '$id'
");

if (mysqli_num_rows($query) == 0) {

    echo "<script>
            alert('Data berita tidak ditemukan');
            window.location='berita_admin.php';
          </script>";

    exit;
}

$data = mysqli_fetch_assoc($query);


/* =====================================================
   UPDATE BERITA
===================================================== */

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

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

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

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

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


    /* ================================================
       GAMBAR LAMA
    ================================================ */

    $gambar_lama = $data['gambar'];

    $gambar_baru = $gambar_lama;


    /* ================================================
       CEK UPLOAD GAMBAR BARU
    ================================================ */

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

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

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


        /* ============================================
           FORMAT GAMBAR
        ============================================ */

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


        if (!in_array($extension, $format_valid)) {

            echo "<script>
                    alert('Format gambar harus JPG, JPEG, atau PNG');
                  </script>";

        } elseif ($ukuran > 2 * 1024 * 1024) {

            echo "<script>
                    alert('Ukuran gambar maksimal 2 MB');
                  </script>";

        } else {

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

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


            $folder = "../assets/img/berita/";


            /* ========================================
               PASTIKAN FOLDER ADA
            ======================================== */

            if (!is_dir($folder)) {

                mkdir(
                    $folder,
                    0777,
                    true
                );
            }


            /* ========================================
               UPLOAD GAMBAR
            ======================================== */

            if (
                move_uploaded_file(
                    $tmp_file,
                    $folder . $gambar_baru
                )
            ) {

                /* ====================================
                   HAPUS GAMBAR LAMA
                ==================================== */

                if (
                    !empty($gambar_lama) &&
                    file_exists(
                        $folder . $gambar_lama
                    )
                ) {

                    unlink(
                        $folder . $gambar_lama
                    );
                }

            } else {

                echo "<script>
                        alert('Gambar gagal diupload');
                      </script>";

                $gambar_baru = $gambar_lama;
            }
        }
    }


    /* =================================================
       UPDATE DATABASE
    ================================================= */

    $update = mysqli_query($conn, "

        UPDATE berita SET

            judul = '$judul',

            kategori = '$kategori',

            tanggal = '$tanggal',

            isi = '$isi',

            gambar = '$gambar_baru'

        WHERE id_berita = '$id'

    ");


    /* =================================================
       HASIL UPDATE
    ================================================= */

    if ($update) {

        echo "<script>

                alert('Berita berhasil diperbarui');

                window.location='berita_admin.php';

              </script>";

        exit;

    } else {

        echo "<script>

                alert('Berita gagal diperbarui');

              </script>";
    }
}

?>

<!DOCTYPE html>

<html lang="id">

<head>

    <meta charset="UTF-8">

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

    <title>
        Edit Berita Desa
    </title>


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


    <link
        href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

</head>


<body>


<div class="container">


    <div class="card">


        <!-- =================================================
             JUDUL
        ================================================== -->

        <h1>
            📰 Edit Berita Desa
        </h1>


        <!-- =================================================
             FORM
        ================================================== -->

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


            <!-- =============================================
                 JUDUL BERITA
            ============================================== -->

            <div class="form-group">

                <label>
                    Judul Berita
                </label>

                <input
                    type="text"
                    name="judul"
                    value="<?= htmlspecialchars($data['judul']); ?>"
                    placeholder="Masukkan judul berita"
                    required
                >

            </div>


            <!-- =============================================
                 KATEGORI
            ============================================== -->

            <div class="form-group">

                <label>
                    Kategori Berita
                </label>

                <select
                    name="kategori"
                    required
                >

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

                    <option
                        value="Kegiatan Desa"
                        <?= ($data['kategori'] == 'Kegiatan Desa') ? 'selected' : ''; ?>
                    >
                        Kegiatan Desa
                    </option>

                    <option
                        value="Pembangunan"
                        <?= ($data['kategori'] == 'Pembangunan') ? 'selected' : ''; ?>
                    >
                        Pembangunan
                    </option>

                    <option
                        value="Pengumuman"
                        <?= ($data['kategori'] == 'Pengumuman') ? 'selected' : ''; ?>
                    >
                        Pengumuman
                    </option>

                    <option
                        value="Edukasi"
                        <?= ($data['kategori'] == 'Edukasi') ? 'selected' : ''; ?>
                    >
                        Edukasi
                    </option>

                    <option
                        value="UMKM"
                        <?= ($data['kategori'] == 'UMKM') ? 'selected' : ''; ?>
                    >
                        UMKM
                    </option>

                </select>

            </div>


            <!-- =============================================
                 TANGGAL
            ============================================== -->

            <div class="form-group">

                <label>
                    Tanggal Berita
                </label>

                <input
                    type="date"
                    name="tanggal"
                    value="<?= htmlspecialchars($data['tanggal']); ?>"
                    required
                >

            </div>


            <!-- =============================================
                 ISI BERITA
            ============================================== -->

            <div class="form-group">

                <label>
                    Isi Berita
                </label>

                <textarea
                    name="isi"
                    rows="10"
                    placeholder="Masukkan isi berita"
                    required
                ><?= htmlspecialchars($data['isi']); ?></textarea>

            </div>


            <!-- =============================================
                 GAMBAR LAMA
            ============================================== -->

            <div class="form-group">

                <label>
                    Gambar Saat Ini
                </label>


                <?php if (!empty($data['gambar'])) { ?>

                    <div class="preview-gambar">

                        <img
                            src="../assets/img/berita/<?= htmlspecialchars($data['gambar']); ?>"
                            alt="Gambar Berita"
                        >

                    </div>

                <?php } else { ?>

                    <div class="no-image">

                        📰

                        <span>
                            Belum ada gambar
                        </span>

                    </div>

                <?php } ?>

            </div>


            <!-- =============================================
                 UPLOAD GAMBAR BARU
            ============================================== -->

            <div class="form-group">

                <label>
                    Ganti Gambar Berita
                </label>

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


                <div class="info-file">

                    ✔ Format : JPG, JPEG, PNG
                    <br>

                    ✔ Maksimal ukuran : 2 MB

                </div>


                <p id="nama-file">

                    Tidak ada gambar baru dipilih

                </p>


                <!-- PREVIEW GAMBAR BARU -->

                <div class="preview-gambar">

                    <img
                        id="preview"
                        src=""
                        alt="Preview Gambar"
                        style="display:none;"
                    >

                </div>

            </div>


            <!-- =============================================
                 TOMBOL
            ============================================== -->

            <div class="aksi">

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

                    ← Batal

                </a>


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

                    💾 Update Berita

                </button>

            </div>


        </form>

    </div>

</div>


<!-- =====================================================
     JAVASCRIPT PREVIEW GAMBAR
====================================================== -->

<script>

const gambar =
    document.getElementById('gambar');

const preview =
    document.getElementById('preview');

const namaFile =
    document.getElementById('nama-file');


gambar.addEventListener(
    'change',
    function () {

        const file = this.files[0];


        if (file) {

            namaFile.textContent =
                file.name;


            const reader =
                new FileReader();


            reader.onload =
                function (e) {

                    preview.src =
                        e.target.result;

                    preview.style.display =
                        'block';

                };


            reader.readAsDataURL(file);

        } else {

            namaFile.textContent =
                'Tidak ada gambar baru dipilih';

            preview.src = '';

            preview.style.display =
                'none';
        }

    }
);

</script>


</body>

</html>