<?php
require 'koneksi.php'; // Pastikan koneksi sudah benar

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $_POST["title"];
    $slug = $_POST["slug"];
    $content = $_POST["content"];
    $status = $_POST["status"];
    $published_at = $_POST["published_at"];
    $created_at = date("Y-m-d H:i:s");
    $updated_at = date("Y-m-d H:i:s");

    // Cek koneksi
    if (!$koneksi) {
        die("Koneksi database gagal: " . mysqli_connect_error());
    }

    // Upload Gambar
    $gambar = null;
    if (!empty($_FILES["gambar"]["name"])) {
        $targetDir = "uploads/";
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        $fileName = time() . "_" . basename($_FILES["gambar"]["name"]);
        $targetFilePath = $targetDir . $fileName;
        $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
        $allowedTypes = ["jpg", "jpeg", "png", "gif"];

        if (in_array(strtolower($fileType), $allowedTypes)) {
            if (move_uploaded_file($_FILES["gambar"]["tmp_name"], $targetFilePath)) {
                $gambar = $fileName;
            }
        }
    }

    // Query INSERT
    $sql = "INSERT INTO posts (title, slug, content, `status`, published_at, created_at, updated_at, gambar) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $koneksi->prepare($sql);

    if ($stmt === false) {
        die("Error saat mempersiapkan statement: " . $koneksi->error);
    }

    $stmt->bind_param("ssssssss", $title, $slug, $content, $status, $published_at, $created_at, $updated_at, $gambar);

    if ($stmt->execute()) {
        header("Location: index.php?page=posting&notif=berhasil_tambah_data");
        exit();
    } else {
        echo "Error saat menyimpan data: " . $stmt->error;
    }

    // Tutup statement
    $stmt->close();
    $koneksi->close();
}
?>
