<?php
require "koneksi.php"; // Pastikan koneksi database sudah ada

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $id = $_POST["id"];
    $title = $_POST["title"];
    $slug = $_POST["slug"];
    $content = $_POST["content"];
    $status = $_POST["status"];
    $published_at = !empty($_POST["published_at"]) ? $_POST["published_at"] : NULL;
    $updated_at = date("Y-m-d H:i:s"); // Waktu sekarang untuk update

    // Cek apakah ada file gambar baru yang diunggah
    if (!empty($_FILES["gambar"]["name"])) {
        $gambar = basename($_FILES["gambar"]["name"]);
        $target_dir = "uploads/";
        $target_file = $target_dir . $gambar;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        // Cek format gambar yang diizinkan
        $allowed_types = ["jpg", "jpeg", "png", "gif"];
        if (!in_array($imageFileType, $allowed_types)) {
            die("Format gambar tidak valid! Gunakan JPG, JPEG, PNG, atau GIF.");
        }

        // Pindahkan file gambar ke folder uploads
        if (move_uploaded_file($_FILES["gambar"]["tmp_name"], $target_file)) {
            // Update query dengan gambar
            $query = "UPDATE posts SET title = ?, slug = ?, content = ?, status = ?, published_at = ?, updated_at = ?, gambar = ? WHERE id = ?";
            $stmt = mysqli_prepare($koneksi, $query);
            mysqli_stmt_bind_param($stmt, "sssssssi", $title, $slug, $content, $status, $published_at, $updated_at, $gambar, $id);
        } else {
            die("Gagal mengunggah gambar.");
        }
    } else {
        // Update query tanpa mengubah gambar
        $query = "UPDATE posts SET title = ?, slug = ?, content = ?, status = ?, published_at = ?, updated_at = ? WHERE id = ?";
        $stmt = mysqli_prepare($koneksi, $query);
        mysqli_stmt_bind_param($stmt, "ssssssi", $title, $slug, $content, $status, $published_at, $updated_at, $id);
    }

    // Eksekusi query
    if (mysqli_stmt_execute($stmt)) {
        mysqli_stmt_close($stmt);
        mysqli_close($koneksi);
        header("Location: index.php?page=voucher&notif=berhasil_ubah_data"); // Redirect setelah sukses
        exit();
    } else {
        die("Error: " . mysqli_error($koneksi));
    }
} else {
    die("Akses tidak valid.");
}
