<?php
session_start();
require_once 'db/config.php';

$restaurant_id = isset($_GET['restaurant_id']) ? (int)$_GET['restaurant_id'] : 0;

if ($restaurant_id === 0) {
    header('Location: index.php');
    exit;
}

require_once 'header.php';

try {
    // Fetch restaurant details
    $stmt = db()->prepare("SELECT r.id, r.name, r.image_url, c.name as cuisine_name 
                           FROM restaurants r 
                           LEFT JOIN restaurant_cuisines rc ON r.id = rc.restaurant_id 
                           LEFT JOIN cuisines c ON rc.cuisine_id = c.id 
                           WHERE r.id = :id");
    $stmt->bindParam(':id', $restaurant_id, PDO::PARAM_INT);
    $stmt->execute();
    $restaurant_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$restaurant_data) {
        throw new Exception("Restaurant not found.");
    }

    $restaurant = [
        'id' => $restaurant_data[0]['id'],
        'name' => $restaurant_data[0]['name'],
        'image_url' => $restaurant_data[0]['image_url'],
        'cuisines' => array_column($restaurant_data, 'cuisine_name')
    ];

    // Fetch menu items
    $menu_stmt = db()->prepare("SELECT id, name, description, price, image_url FROM menu_items WHERE restaurant_id = :restaurant_id");
    $menu_stmt->bindParam(':restaurant_id', $restaurant_id, PDO::PARAM_INT);
    $menu_stmt->execute();
    $menu_items = $menu_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch ratings and calculate average
    $ratings_stmt = db()->prepare("SELECT r.rating, r.review, r.created_at, u.name as user_name FROM ratings r JOIN users u ON r.user_id = u.id WHERE r.restaurant_id = :restaurant_id ORDER BY r.created_at DESC");
    $ratings_stmt->bindParam(':restaurant_id', $restaurant_id, PDO::PARAM_INT);
    $ratings_stmt->execute();
    $ratings = $ratings_stmt->fetchAll(PDO::FETCH_ASSOC);

    $average_rating = 0;
    $rating_count = count($ratings);
    if ($rating_count > 0) {
        $total_rating = array_sum(array_column($ratings, 'rating'));
        $average_rating = round($total_rating / $rating_count, 1);
    }

    // Check if this restaurant is a favorite for the current user
    $is_favorite = false;
    if (isset($_SESSION['user_id'])) {
        $fav_stmt = db()->prepare("SELECT COUNT(*) FROM favorite_restaurants WHERE user_id = :user_id AND restaurant_id = :restaurant_id");
        $fav_stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
        $fav_stmt->bindParam(':restaurant_id', $restaurant_id, PDO::PARAM_INT);
        $fav_stmt->execute();
        $is_favorite = $fav_stmt->fetchColumn() > 0;
    }

} catch (Exception $e) {
    echo "<div class='container'><p class='alert alert-danger'>" . $e->getMessage() . "</p></div>";
    require_once 'footer.php';
    exit;
}
?>

<div class="restaurant-hero-menu" style="background-image: url('<?php echo htmlspecialchars($restaurant['image_url']); ?>');">
    <div class="restaurant-hero-menu-content">
        <h1><?php echo htmlspecialchars($restaurant['name']); ?></h1>
        <p><?php echo htmlspecialchars(implode(', ', $restaurant['cuisines'])); ?></p>
        <div class="d-flex align-items-center">
            <span class="h4 text-warning me-2"><?php echo $average_rating; ?> ★</span>
            <span class="text-white">(<?php echo count($ratings); ?> reviews)</span>
            <?php if (isset($_SESSION['user_id'])) : ?>
                <form action="toggle_favorite.php" method="post" class="ms-4">
                    <input type="hidden" name="restaurant_id" value="<?php echo $restaurant_id; ?>">
                    <button type="submit" class="btn <?php echo $is_favorite ? 'btn-danger' : 'btn-outline-light'; ?>">
                        <?php echo $is_favorite ? '♥ Favorited' : '♡ Add to Favorites'; ?>
                    </button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="container mt-5">
    <div class="row">
        <div class="col-lg-8">
            <h2 class="mb-4">Menu</h2>
            <div class="menu-grid">
                <?php if ($menu_items): ?>
                    <?php foreach ($menu_items as $item): ?>
                        <div class="menu-item-card">
                            <div class="menu-item-card-content">
                                <h3><?php echo htmlspecialchars($item['name']); ?></h3>
                                <p class="description"><?php echo htmlspecialchars($item['description']); ?></p>
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="price">$<?php echo htmlspecialchars(number_format($item['price'], 2)); ?></span>
                                    <form action="cart_actions.php" method="post" class="add-to-cart-form">
                                        <input type="hidden" name="action" value="add">
                                        <input type="hidden" name="restaurant_id" value="<?php echo $restaurant_id; ?>">
                                        <input type="hidden" name="menu_item_id" value="<?php echo $item['id']; ?>">
                                        <div class="input-group">
                                            <input type="number" name="quantity" class="form-control quantity-input" value="1" min="1">
                                            <button type="submit" class="btn btn-primary add-to-cart-btn">Add</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <?php if (!empty($item['image_url'])): ?>
                                <img src="<?php echo htmlspecialchars($item['image_url']); ?>" class="menu-item-image" alt="<?php echo htmlspecialchars($item['name']); ?>">
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="alert alert-info">This restaurant has no menu items yet.</p>
                <?php endif; ?>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="reviews-section">
                <h2 class="mb-4">Reviews</h2>
                <?php if ($ratings): ?>
                    <?php foreach (array_slice($ratings, 0, 3) as $rating): ?>
                        <div class="review-card">
                            <div class="review-header">
                                <strong><?php echo htmlspecialchars($rating['user_name']); ?></strong>
                                <span class="text-warning"><?php echo str_repeat('★', $rating['rating']) . str_repeat('☆', 5 - $rating['rating']); ?></span>
                            </div>
                            <p class="review-text">"<?php echo nl2br(htmlspecialchars($rating['review'])); ?>"</p>
                            <small class="text-muted"><?php echo date('F Y', strtotime($rating['created_at'])); ?></small>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p>This restaurant has no reviews yet.</p>
                <?php endif; ?>

                <?php if (isset($_SESSION['user_id'])): ?>
                    <a href="leave_review.php?restaurant_id=<?php echo $restaurant_id; ?>" class="btn btn-outline-primary mt-3">Leave a Review</a>
                <?php else: ?>
                    <p class="mt-3"><a href="login.php?redirect_url=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">Log in</a> to leave a review.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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