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

$user = $_SESSION['username'] ?? 'Unknown User'; // Who is deleting

if(!isset($_GET['id'])){
    echo "<script>alert('Menu ID not specified!'); window.location='restaurant_menu.php';</script>";
    exit;
}

$menu_id = intval($_GET['id']);

// Fetch the menu item before deletion
$menu = $conn->query("SELECT name, price, description FROM restaurant_menu WHERE id=$menu_id")->fetch_assoc();

if($menu){
    // Delete the menu item
    $stmt = $conn->prepare("DELETE FROM restaurant_menu WHERE id=?");
    $stmt->bind_param("i", $menu_id);
    $deleted = $stmt->execute();
    $stmt->close();

    if($deleted){
        // ================== SEND EMAIL ==================
        $to = "giantplusmw@gmail.com";
        $subject = "Restaurant Menu Item Deleted: {$menu['name']}";
        $message = "
Hello GiantPlus Team,

A menu item has been deleted from the restaurant system.

Details:
-------------------------
Menu Name: {$menu['name']}
Price: ".number_format($menu['price'],2)." MK
Description: {$menu['description']}
Deleted By: $user
Deleted On: ".date("Y-m-d H:i:s")."
-------------------------

This is an automated notification.

Regards,
Restaurant Management System
";

        $headers = "From: cloud@gianterp.space\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        mail($to, $subject, $message, $headers);

        echo "<script>alert('Menu item \"{$menu['name']}\" deleted and email notification sent!'); window.location='restaurant_menu.php';</script>";
        exit;
    } else {
        echo "<script>alert('Error deleting menu item: ".$conn->error."'); window.location='restaurant_menu.php';</script>";
        exit;
    }

} else {
    echo "<script>alert('Menu item not found!'); window.location='restaurant_menu.php';</script>";
    exit;
}
