<?php
session_start();
require 'koneksi.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: index");
    exit();
}

if (!isset($_GET['id'])) {
    $_SESSION['error'] = "ID kategori tidak valid";
    header("Location: kategori");
    exit();
}

$id = (int)$_GET['id'];
// Path relatif ke folder upload
$upload_dir = '../upload/galeri/';
$base_url = 'http://' . $_SERVER['HTTP_HOST'] . '/upload/galeri/'; // Sesuaikan path domain

// Get galeri ID dari URL
$galeri_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Ambil data galeri
$stmt = $pdo->prepare("SELECT * FROM galeri WHERE id = ?");
$stmt->execute([$galeri_id]);
$galeri = $stmt->fetch();

if ($galeri) {
    try {
        $pdo->beginTransaction();

        // Hapus gambar fisik
        if (!empty($galeri['gambar'])) {
            $old_image_path = str_replace($base_url, $upload_dir, $galeri['gambar']);
            if (file_exists($old_image_path)) {
                unlink($old_image_path);
            }
        }

        // Hapus dari database
        $stmt = $pdo->prepare("DELETE FROM galeri WHERE id = ?");
        $stmt->execute([$galeri_id]);

        $pdo->commit();

        $_SESSION['success'] = "Galeri berhasil dihapus!";
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = "Gagal menghapus galeri: " . $e->getMessage();
    }
}

header("Location: galeri");
exit();
