<?php

session_start();

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


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

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

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


// ===============================
// AMBIL DATA FORM
// ===============================

$judul   = $_POST['judul'];
$tanggal = $_POST['tanggal'];
$isi     = $_POST['isi'];
$link_instagram = $_POST['link_instagram'] ?? '';



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

if (!isset($_FILES['gambar']) || $_FILES['gambar']['error'] != 0) {

    header("Location: tambah.php?error=foto");
    exit;
}



$nama_file = $_FILES['gambar']['name'];
$tmp_file  = $_FILES['gambar']['tmp_name'];
$ukuran    = $_FILES['gambar']['size'];



// ===============================
// VALIDASI FORMAT FOTO
// ===============================

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


$format_boleh = [
    "jpg",
    "jpeg",
    "png",
    "webp"
];


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

    header("Location: tambah.php?error=format");
    exit;
}



// ===============================
// VALIDASI UKURAN
// maksimal 2 MB
// ===============================

if ($ukuran > 2 * 1024 * 1024) {

    header("Location: tambah.php?error=ukuran");
    exit;
}



// ===============================
// UPLOAD FOTO
// ===============================

$nama_baru = time() . "_" . $nama_file;


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


// buat folder jika belum ada

if (!is_dir($folder)) {

    mkdir($folder, 0777, true);
}


$upload = move_uploaded_file(
    $tmp_file,
    $folder . $nama_baru
);



if (!$upload) {

    header("Location: tambah.php?error=upload");
    exit;
}



// ===============================
// SIMPAN DATABASE
// ===============================


$query = mysqli_query(
    $koneksi,
    "INSERT INTO berita
    (
        judul,
        tanggal,
        isi,
        gambar,
        link_instagram
    )
    VALUES
    (
        '$judul',
        '$tanggal',
        '$isi',
        '$nama_baru',
        '$link_instagram'
    )"
);


if ($query) {


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

    exit;
} else {


    header("Location: tambah.php?error=database");

    exit;
}
