<?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'];

// Get restaurant details
$stmt = $pdo->prepare("SELECT name FROM restaurants WHERE id = ?");
$stmt->execute([$restaurant_id]);
$restaurant_details = $stmt->fetch();


// Get menu items for the restaurant
$stmt = $pdo->prepare("SELECT * FROM menu_items WHERE restaurant_id = ? ORDER BY name");
$stmt->execute([$restaurant_id]);
$menu_items = $stmt->fetchAll();
?>

<div class="container mt-4">
    <h2>Manage Menu for <?php echo htmlspecialchars($restaurant_details['name']); ?></h2>
    <p><a href="add_menu_item.php" class="btn btn-success">Add New Menu Item</a></p>

    <table class="table table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Description</th>
                <th>Price</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($menu_items)): ?>
                <tr>
                    <td colspan="4">No menu items found.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($menu_items as $item): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($item['name']); ?></td>
                        <td><?php echo htmlspecialchars($item['description']); ?></td>
                        <td>$<?php echo htmlspecialchars(number_format($item['price'], 2)); ?></td>
                        <td>
                            <a href="edit_menu_item.php?id=<?php echo $item['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                            <a href="delete_menu_item.php?id=<?php echo $item['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
    <a href="index.php" class="btn btn-secondary">Back to Dashboard</a>
</div>

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