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

// Check if the user is logged in as a restaurant owner
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'restaurant_owner') {
    header('Location: ../restaurant_login.php');
    exit;
}

$pdo = db();

// Get the restaurant ID associated with the logged-in user
$stmt = $pdo->prepare("SELECT id FROM restaurants WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$restaurant = $stmt->fetch();

if (!$restaurant) {
    // If for some reason the user is a restaurant owner but has no restaurant, redirect them
    header('Location: ../index.php');
    exit;
}
$restaurant_id = $restaurant['id'];

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

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

$stmt = $pdo->prepare("SELECT * FROM special_promotions");
$stmt->execute();
$promotions = $stmt->fetchAll();

?>

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

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

    <form action="add_menu_item.php" method="POST">
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" name="name" required>
        </div>
        <div class="mb-3">
            <label for="description" class="form-label">Description</label>
            <textarea class="form-control" id="description" name="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" required>
        </div>
        <div class="mb-3">
            <label for="promotion_id" class="form-label">Promotion</label>
            <select class="form-control" id="promotion_id" name="promotion_id">
                <option value="">None</option>
                <?php foreach ($promotions as $promotion): ?>
                    <option value="<?= $promotion['id'] ?>"><?= htmlspecialchars($promotion['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" class="btn btn-primary">Add Item</button>
        <a href="menu.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

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