<?php

session_start();

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

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$id = $_POST['id'];
$judul = $_POST['judul'];
$link = $_POST['link'];
$deskripsi = $_POST['deskripsi'];

$gambar = $_POST['gambar_lama'];

// Jika ada gambar baru diupload
if (!empty($_FILES['gambar']['name'])) {

    $gambar = time() . "_" . $_FILES['gambar']['name'];
    $tmp = $_FILES['gambar']['tmp_name'];

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

    move_uploaded_file($tmp, $folder . $gambar);

    // Hapus gambar lama
    if (!empty($_POST['gambar_lama']) && file_exists($folder . $_POST['gambar_lama'])) {
        unlink($folder . $_POST['gambar_lama']);
    }
}

$query = mysqli_query(
    $koneksi,
    "UPDATE galeri SET
        judul='$judul',
        gambar='$gambar',
        link='$link',
        deskripsi='$deskripsi'
    WHERE id='$id'"
);

if ($query) {
    header("Location: index.php");
    exit;
} else {
    echo mysqli_error($koneksi);
}
