<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $judul = $_POST["judul"];
    $isi = $_POST["isi"];
    $link = $_POST["link"] ?? "";
    $gambarNama = "";

    // Simpan gambar jika ada
    if (!empty($_FILES["gambar"]["name"])) {
        $uploadDir = "uploads/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $gambarNama = time() . "_" . basename($_FILES["gambar"]["name"]);
        move_uploaded_file($_FILES["gambar"]["tmp_name"], $uploadDir . $gambarNama);
    }

    // Simpan ke JSON
    $dataFile = "data.json";
    $data = file_exists($dataFile) ? json_decode(file_get_contents($dataFile), true) : [];
    $data[] = ["judul" => $judul, "isi" => $isi, "link" => $link, "gambar" => $gambarNama];

    file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT));

    // Redirect kembali dengan notifikasi
    header("Location: index.php?success=1");
    exit();
}
?>
