<?php
include("../config/db.php");

/* ================= AUTH CHECK ================= */
if (!isset($_SESSION['admin'])) {
    header("Location: login.php");
    exit;
}

/* ================= VALIDATE ID ================= */
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: manage-menu.php");
    exit;
}

$id = (int) $_GET['id'];

/* ================= GET IMAGE NAME ================= */
$stmt = $conn->prepare("SELECT image FROM menu_items WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header("Location: manage-menu.php");
    exit;
}

$row = $result->fetch_assoc();
$image = $row['image'];

/* ================= DELETE DB RECORD ================= */
$del = $conn->prepare("DELETE FROM menu_items WHERE id = ?");
$del->bind_param("i", $id);
$del->execute();

/* ================= DELETE IMAGE FILE ================= */
$imagePath = "../uploads/menu/" . $image;
if (!empty($image) && file_exists($imagePath)) {
    unlink($imagePath);
}

/* ================= REDIRECT ================= */
header("Location: manage-menu.php?deleted=1");
exit;
