<?php
include '../includes/auth.php';
include '../includes/functions.php';

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $id = (int)$data['id'];
    
    // Get file info before deleting
    $query = $conn->query("SELECT nama_file FROM dafdir_event_undangan WHERE id_undangan = $id");
    if ($query->num_rows > 0) {
        $file = $query->fetch_assoc();
        $filePath = '../uploads/event_undangan/' . $file['nama_file'];
        
        // Delete from database
        if ($conn->query("DELETE FROM dafdir_event_undangan WHERE id_undangan = $id")) {
            // Delete the file
            if (file_exists($filePath)) {
                unlink($filePath);
            }
            $response['success'] = true;
            $response['message'] = 'Undangan berhasil dihapus';
        } else {
            $response['message'] = 'Gagal menghapus dari database';
        }
    } else {
        $response['message'] = 'Undangan tidak ditemukan';
    }
}

header('Content-Type: application/json');
echo json_encode($response);
?>