<?php

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


/* =====================================================
   TAMBAH BERITA
===================================================== */

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

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

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

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

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


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

    $gambar = "";
    
    if (
        isset($_FILES['gambar']) &&
        $_FILES['gambar']['name'] != ""
    ) {

        $namaFile = $_FILES['gambar']['name'];
        $tmpFile = $_FILES['gambar']['tmp_name'];

        $ext = strtolower(
            pathinfo($namaFile, PATHINFO_EXTENSION)
        );

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

        if (!in_array($ext, $izin)) {

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

            exit;
        }


        /*
        Nama file dibuat unik
        agar tidak terjadi nama file sama
        */

        $gambar =
            time() . "_" .
            preg_replace(
                "/[^a-zA-Z0-9._-]/",
                "_",
                $namaFile
            );


        move_uploaded_file(
            $tmpFile,
            "../assets/img/berita/" . $gambar
        );
    }


    /* =========================
       INSERT DATA
    ========================= */

    mysqli_query($conn, "

        INSERT INTO berita (

            kategori,
            judul,
            tanggal,
            isi,
            gambar

        )

        VALUES (

            '$kategori',
            '$judul',
            '$tanggal',
            '$isi',
            '$gambar'

        )

    ");


    echo "<script>

        alert('Berita berhasil ditambahkan');

        window.location='berita_admin.php';

    </script>";

}


/* =====================================================
   HAPUS BERITA
===================================================== */

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

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


    /* Ambil data gambar */

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


    $d = mysqli_fetch_assoc($q);


    /* Hapus gambar */

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

        unlink(
            "../assets/img/berita/" . $d['gambar']
        );
    }


    /* Hapus data */

    mysqli_query(
        $conn,
        "
        DELETE FROM berita
        WHERE id_berita='$id'
        "
    );


    echo "<script>

        alert('Berita berhasil dihapus');

        window.location='berita_admin.php';

    </script>";
}

?>


<!DOCTYPE html>

<html lang="id">

<head>

    <meta charset="UTF-8">

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

    <title>
        Kelola Berita Desa
    </title>


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

</head>


<body>


<div class="container">


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

    <div class="header">
        <a
            href="dashboard.php"
            class="btn-kembali"
        >
            ← Dashboard
        </a>

        <h1>

            📰 Kelola Berita Desa

        </h1>

    </div>



    <!-- =================================================
         CARD FORM TAMBAH BERITA
    ================================================== -->

    <div class="card">


        <h2>
            Tambah Berita Baru
        </h2>


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


            <!-- KATEGORI -->

            <div class="form-group">

                <label>
                    Kategori Berita
                </label>


                <select
                    name="kategori"
                    required
                >

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

                    <option value="Berita Desa">
                        Berita Desa
                    </option>

                    <option value="Kegiatan Desa">
                        Kegiatan Desa
                    </option>

                    <option value="Pengumuman">
                        Pengumuman
                    </option>

                    <option value="Edukasi">
                        Edukasi
                    </option>

                </select>

            </div>



            <!-- JUDUL -->

            <div class="form-group">

                <label>
                    Judul Berita
                </label>


                <input
                    type="text"
                    name="judul"
                    placeholder="Masukkan judul berita"
                    required
                >

            </div>



            <!-- TANGGAL -->

            <div class="form-group">

                <label>
                    Tanggal Berita
                </label>


                <input
                    type="date"
                    name="tanggal"
                    value="<?= date('Y-m-d'); ?>"
                    required
                >

            </div>



            <!-- ISI BERITA -->

            <div class="form-group">

                <label>
                    Isi Berita
                </label>


                <textarea
                    name="isi"
                    rows="8"
                    placeholder="Masukkan isi berita..."
                    required
                ></textarea>

            </div>



            <!-- GAMBAR -->

            <div class="form-group">

                <label>
                    Foto Berita
                </label>


                <input
                    type="file"
                    id="gambar"
                    name="gambar"
                    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 -->

                <div class="preview-gambar">

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

                </div>

            </div>



            <!-- TOMBOL -->

            <div class="aksi">

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

                    💾 Simpan Berita

                </button>

            </div>


        </form>

    </div>



    <!-- =================================================
         DAFTAR BERITA
    ================================================== -->

    <div class="card table-card">


        <div class="table-header">

            <h2>
                Daftar Berita Desa
            </h2>


            <input
                type="text"
                id="cariBerita"
                placeholder="🔍 Cari judul berita..."
            >

        </div>



        <table id="tabelBerita">


            <thead>

                <tr>

                    <th>
                        No
                    </th>

                    <th>
                        Foto
                    </th>

                    <th>
                        Judul Berita
                    </th>

                    <th>
                        Kategori
                    </th>

                    <th>
                        Tanggal
                    </th>

                    <th>
                        Aksi
                    </th>

                </tr>

            </thead>



            <tbody>


            <?php

            $no = 1;


            $data = mysqli_query(
                $conn,
                "
                SELECT *
                FROM berita
                ORDER BY tanggal DESC
                "
            );


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

            ?>


                <tr>


                    <!-- NOMOR -->

                    <td>

                        <?= $no++; ?>

                    </td>



                    <!-- FOTO -->

                    <td>

                        <?php

                        if (!empty($d['gambar'])) {

                        ?>

                            <img
                                src="../assets/img/berita/<?= htmlspecialchars($d['gambar']); ?>"
                                class="foto-berita"
                                alt="Foto Berita"
                            >

                        <?php

                        } else {

                        ?>

                            <div class="tanpa-foto">

                                📰

                            </div>

                        <?php

                        }

                        ?>

                    </td>



                    <!-- JUDUL -->

                    <td>

                        <strong>

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

                        </strong>

                    </td>



                    <!-- KATEGORI -->

                    <td>

                        <span class="kategori">

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

                        </span>

                    </td>



                    <!-- TANGGAL -->

                    <td>

                        <?= date(
                            'd-m-Y',
                            strtotime($d['tanggal'])
                        ); ?>

                    </td>



                    <!-- AKSI -->

                    <td class="aksi-table">


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

                            ✏ Edit

                        </a>



                        <a
                            href="?hapus=<?= $d['id_berita']; ?>"
                            class="btn-hapus"

                            onclick="
                                return confirm(
                                    'Yakin ingin menghapus berita ini?'
                                )
                            "
                        >

                            🗑 Hapus

                        </a>


                    </td>


                </tr>


            <?php

            }

            ?>


            </tbody>


        </table>


    </div>


</div>



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

<script>

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

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

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


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

inputGambar.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 =
                'Belum ada file dipilih';

            preview.src = '';

            preview.style.display =
                'none';
        }

    }
);


/* =========================
   PENCARIAN BERITA
========================= */

document
    .getElementById('cariBerita')
    .addEventListener(
        'keyup',
        function () {


            const keyword =
                this.value.toLowerCase();


            const rows =
                document.querySelectorAll(
                    '#tabelBerita tbody tr'
                );


            rows.forEach(
                function (row) {


                    const judul =
                        row
                        .querySelector(
                            'td:nth-child(3)'
                        )
                        .textContent
                        .toLowerCase();


                    if (
                        judul.includes(keyword)
                    ) {

                        row.style.display =
                            '';

                    } else {

                        row.style.display =
                            'none';

                    }

                }
            );

        }
    );

</script>


</body>

</html>