<?php
include 'header.php';
require_once '../db/config.php';

// Check if the user is logged in as an admin
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$id = $_GET['id'] ?? null;
if (!$id) {
    header('Location: index.php');
    exit;
}

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $description = $_POST['description'] ?? '';
    $price = $_POST['price'] ?? '';
    $id = $_POST['id'] ?? null;
    $restaurant_id = $_POST['restaurant_id'] ?? null;

    if ($name && $price && $id && $restaurant_id) {
        $stmt = $pdo->prepare("UPDATE menu_items SET name = ?, description = ?, price = ? WHERE id = ?");
        $stmt->execute([$name, $description, $price, $id]);
        header('Location: menu.php?restaurant_id=' . $restaurant_id);
        exit;
    } else {
        $error = "Name and price are required.";
    }
}

$stmt = $pdo->prepare("SELECT * FROM menu_items WHERE id = ?");
$stmt->execute([$id]);
$item = $stmt->fetch();

if (!$item) {
    header('Location: index.php');
    exit;
}
?>

<div class="container mt-4">
    <h2>Edit Menu Item</h2>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>

    <form action="edit_menu_item.php?id=<?php echo $item['id']; ?>" method="POST">
        <input type="hidden" name="id" value="<?php echo $item['id']; ?>">
        <input type="hidden" name="restaurant_id" value="<?php echo $item['restaurant_id']; ?>">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($item['name']); ?>" required>
        </div>
        <div class="mb-3">
            <label for="description" class="form-label">Description</label>
            <textarea class="form-control" id="description" name="description"><?php echo htmlspecialchars($item['description']); ?></textarea>
        </div>
        <div class="mb-3">
            <label for="price" class="form-label">Price</label>
            <input type="number" step="0.01" class="form-control" id="price" name="price" value="<?php echo htmlspecialchars($item['price']); ?>" required>
        </div>
        <button type="submit" class="btn btn-primary">Update Item</button>
        <a href="menu.php?restaurant_id=<?php echo $item['restaurant_id']; ?>" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include 'footer.php'; ?>
