<?php

session_start();

require_once "../../config/koneksi.php";


// ========================================
// CEK LOGIN ADMIN
// ========================================

if (!isset($_SESSION['user_id'])) {

    header("Location: ../login.php");
    exit;
}


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

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

    header("Location: index.php");
    exit;
}

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


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

$query = "
    SELECT *
    FROM berita
    WHERE id = ?
    LIMIT 1
";

$stmt = mysqli_prepare(
    $koneksi,
    $query
);

mysqli_stmt_bind_param(
    $stmt,
    "i",
    $id
);

mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);


if (mysqli_num_rows($result) !== 1) {

    header("Location: index.php");
    exit;
}


$berita = mysqli_fetch_assoc($result);


// ========================================
// PROSES UPDATE
// ========================================

if ($_SERVER["REQUEST_METHOD"] === "POST") {


    $judul = trim(
        $_POST['judul'] ?? ''
    );


    $isi = trim(
        $_POST['isi'] ?? ''
    );


    $tanggal = $_POST['tanggal'] ?? '';

    $link_instagram = trim(
        $_POST['link_instagram'] ?? ''
    );


    // Validasi

    if (
        $judul === '' ||
        $isi === '' ||
        $tanggal === ''
    ) {

        $error = "Semua data wajib diisi.";
    } else {


        // Foto lama

        $nama_gambar =
            $berita['gambar'];


        // ========================================
        // CEK FOTO BARU
        // ========================================

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


            $folder_upload =
                "../../uploads/berita/";


            // Buat folder jika belum ada

            if (!is_dir($folder_upload)) {

                mkdir(
                    $folder_upload,
                    0777,
                    true
                );
            }


            $nama_file_asli =
                $_FILES['gambar']['name'];


            $tmp_file =
                $_FILES['gambar']['tmp_name'];


            $ukuran_file =
                $_FILES['gambar']['size'];


            // Ambil ekstensi

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


            // Ekstensi yang diperbolehkan

            $ekstensi_diperbolehkan = [
                'jpg',
                'jpeg',
                'png',
                'webp'
            ];


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

                $error =
                    "Format foto harus JPG, JPEG, PNG, atau WEBP.";
            }


            // Maksimal 2 MB

            elseif (
                $ukuran_file > 2 * 1024 * 1024
            ) {

                $error =
                    "Ukuran foto maksimal 2 MB.";
            } else {


                // Buat nama file baru

                $nama_gambar =
                    time() .
                    "_" .
                    uniqid() .
                    "." .
                    $ekstensi;


                $lokasi_file =
                    $folder_upload .
                    $nama_gambar;


                // Upload foto

                if (
                    move_uploaded_file(
                        $tmp_file,
                        $lokasi_file
                    )
                ) {


                    // Hapus foto lama

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

                        $foto_lama =
                            $folder_upload .
                            $berita['gambar'];


                        if (
                            file_exists(
                                $foto_lama
                            )
                        ) {

                            unlink(
                                $foto_lama
                            );
                        }
                    }
                } else {

                    $error =
                        "Foto gagal diupload.";
                }
            }
        }


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

        if (!isset($error)) {


            $query_update = "UPDATE berita
            SET
        judul = ?,
        isi = ?,
        tanggal = ?,
        gambar = ?,
        link_instagram = ?
    WHERE id = ?
";


            $stmt_update =
                mysqli_prepare(
                    $koneksi,
                    $query_update
                );


            mysqli_stmt_bind_param(
                $stmt_update,
                "sssssi",
                $judul,
                $isi,
                $tanggal,
                $nama_gambar,
                $link_instagram,
                $id
            );

            if (
                mysqli_stmt_execute(
                    $stmt_update
                )
            ) {

                header(
                    "Location: index.php?success=edit"
                );

                exit;
            } else {

                $error =
                    "Data berita gagal diperbarui.";
            }
        }
    }
}

?>

<!DOCTYPE html>

<html lang="id">

<head>

    <meta charset="UTF-8">

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

    <title>
        Edit Berita - DISPUSIP Banyuwangi
    </title>


    <link
        href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
        rel="stylesheet">


    <style>
        body {
            background: #f5f7fb;
        }


        .form-card {

            max-width: 800px;

            margin: 40px auto;

            background: white;

            padding: 35px;

            border-radius: 15px;

            box-shadow:
                0 5px 20px rgba(0, 0, 0, 0.06);

        }


        .preview-image {

            width: 100%;

            max-width: 350px;

            height: 220px;

            object-fit: cover;

            border-radius: 10px;

            margin-bottom: 15px;

        }


        textarea {

            min-height: 250px;

        }
    </style>

</head>


<body>


    <div class="container">


        <div class="form-card">


            <!-- JUDUL -->

            <div class="mb-4">

                <h3>
                    Edit Berita
                </h3>

                <p class="text-muted mb-0">

                    Perbarui informasi berita
                    yang akan ditampilkan
                    pada website.

                </p>

            </div>


            <!-- ERROR -->

            <?php if (isset($error)): ?>

                <div class="alert alert-danger">

                    <?= htmlspecialchars($error); ?>

                </div>

            <?php endif; ?>


            <!-- FORM -->

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


                <!-- JUDUL -->

                <div class="mb-3">

                    <label class="form-label">

                        Judul Berita

                    </label>


                    <input
                        type="text"
                        name="judul"
                        class="form-control"
                        value="<?= htmlspecialchars(
                                    $berita['judul']
                                ); ?>"
                        required>

                </div>


                <!-- TANGGAL -->

                <div class="mb-3">

                    <label class="form-label">

                        Tanggal

                    </label>


                    <input
                        type="date"
                        name="tanggal"
                        class="form-control"
                        value="<?= htmlspecialchars(
                                    $berita['tanggal']
                                ); ?>"
                        required>

                </div>


                <!-- ISI -->

                <div class="mb-3">

                    <label class="form-label">

                        Isi Berita

                    </label>


                    <textarea
                        name="isi"
                        class="form-control"
                        required><?= htmlspecialchars(
                                        $berita['isi']
                                    ); ?></textarea>

                </div>


                <!-- FOTO LAMA -->

                <div class="mb-3">

                    <label class="form-label">

                        Foto Saat Ini

                    </label>


                    <?php if (
                        !empty($berita['gambar']) &&
                        file_exists(
                            "../../uploads/berita/" .
                                $berita['gambar']
                        )
                    ): ?>

                        <br>

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

                    <?php else: ?>

                        <p class="text-muted">

                            Belum ada foto.

                        </p>

                    <?php endif; ?>

                </div>


                <!-- FOTO BARU -->

                <div class="mb-4">

                    <label class="form-label">

                        Ganti Foto Berita

                    </label>


                    <input
                        type="file"
                        name="gambar"
                        class="form-control"
                        accept=".jpg,.jpeg,.png,.webp">


                    <small class="text-muted">

                        Kosongkan jika tidak ingin
                        mengganti foto.

                        Maksimal 2 MB.

                    </small>

                </div>

                <!-- LINK INSTAGRAM -->

                <div class="mb-4">

                    <label class="form-label">
                        Link Instagram
                    </label>

                    <input
                        type="url"
                        name="link_instagram"
                        class="form-control"
                        value="<?= htmlspecialchars(
                                    $berita['link_instagram'] ?? ''
                                ); ?>"
                        placeholder="https://www.instagram.com/...">

                    <small class="text-muted">
                        Masukkan link postingan Instagram untuk berita ini.
                    </small>

                </div>
                <!-- TOMBOL -->

                <div class="d-flex gap-2">

                    <a
                        href="index.php"
                        class="btn btn-secondary">

                        Batal

                    </a>


                    <button
                        type="submit"
                        class="btn btn-primary">

                        Simpan Perubahan

                    </button>

                </div>


            </form>


        </div>

    </div>


</body>

</html>