<?php
// Tambahkan di awal file untuk memastikan tidak ada output sebelum header
ob_start();
session_start();

include '../includes/auth.php';
include '../includes/db.php';

// Pastikan tidak ada output sebelum ini
header('Content-Type: application/json');

// Cek session dan method request
if (!isset($_SESSION['admin_logged_in'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Validasi input
if (!isset($_POST['id'])) {
    echo json_encode(['success' => false, 'message' => 'ID foto tidak valid']);
    exit;
}

$id_foto = (int)$_POST['id'];
$response = [];

try {
    // Mulai transaksi
    $conn->begin_transaction();

    // Dapatkan info foto sebelum dihapus
    $stmt = $conn->prepare("SELECT nama_file, id_event FROM dafdir_event_foto WHERE id_foto = ?");
    $stmt->bind_param("i", $id_foto);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception("Foto tidak ditemukan");
    }

    $foto = $result->fetch_assoc();
    $file_path = realpath(__DIR__ . '/../uploads/event_foto/' . $foto['nama_file']);

    // Verifikasi path file untuk keamanan
    $upload_dir = realpath(__DIR__ . '/../uploads/event_foto/');
    if (strpos($file_path, $upload_dir) !== 0) {
        throw new Exception("Path file tidak valid");
    }

    // Hapus dari database
    $stmt = $conn->prepare("DELETE FROM dafdir_event_foto WHERE id_foto = ?");
    $stmt->bind_param("i", $id_foto);
    $stmt->execute();

    // Hapus file fisik
    if (file_exists($file_path)) {
        if (!unlink($file_path)) {
            throw new Exception("Gagal menghapus file");
        }
    }

    $conn->commit();
    $response = ['success' => true, 'message' => 'Foto berhasil dihapus'];
} catch (Exception $e) {
    $conn->rollback();
    $response = ['success' => false, 'message' => 'Gagal menghapus foto: ' . $e->getMessage()];
}

// Pastikan hanya output JSON yang dikirim
ob_end_clean();
echo json_encode($response);
exit;