<?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="container mt-5">
    <?php if ($restaurant): ?>
        <div class="row mb-4 align-items-center">
            <div class="col-md-8">
                <div class="d-flex align-items-center">
                    <h1 class="display-4 mb-0"><?php echo htmlspecialchars($restaurant['name']); ?></h1>
                    <?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-danger'; ?>">
                                <?php echo $is_favorite ? '♥ Remove from Favorites' : '♡ Add to Favorites'; ?>
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
                <p class="lead text-muted"><?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-muted">(<?php echo count($ratings); ?> reviews)</span>
                </div>
            </div>
            <div class="col-md-4">
                <?php if (!empty($restaurant['image_url'])): ?>
                    <img src="<?php echo htmlspecialchars($restaurant['image_url']); ?>" class="img-fluid rounded shadow-sm" alt="Image of <?php echo htmlspecialchars($restaurant['name']); ?>">
                <?php endif; ?>
            </div>
        </div>

        <hr>

        <h2 class="mt-5 mb-4">Menu</h2>
        <div class="row">
            <?php if ($menu_items): ?>
                <?php foreach ($menu_items as $item): ?>
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card h-100 shadow-sm border-light">
                            <?php if (!empty($item['image_url'])): ?>
                                <img src="<?php echo htmlspecialchars($item['image_url']); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($item['name']); ?>" style="height: 200px; object-fit: cover;">
                            <?php endif; ?>
                            <div class="card-body d-flex flex-column">
                                <h5 class="card-title"><?php echo htmlspecialchars($item['name']); ?></h5>
                                <p class="card-text text-muted flex-grow-1"><?php echo htmlspecialchars($item['description']); ?></p>
                                <p class="card-text h4 text-success">$<?php echo htmlspecialchars(number_format($item['price'], 2)); ?></p>
                                <form action="cart_actions.php" method="post" class="mt-auto">
                                    <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" value="1" min="1">
                                        <button type="submit" class="btn btn-primary">Add to Cart</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col">
                    <p class="alert alert-info">This restaurant has no menu items yet.</p>
                </div>
            <?php endif; ?>
        </div>

        <hr class="my-5">

        <div class="row">
            <div class="col-lg-8 mx-auto">
                <h2 class="mb-4">Reviews & Ratings</h2>

                <?php if (isset($_SESSION['user_id']) && $rating_count > 0): ?>
                    <div class="alert alert-light">
                        You have already reviewed this restaurant.
                    </div>
                <?php elseif (isset($_SESSION['user_id'])): ?>
                    <div class="alert alert-info">
                        <a href="leave_review.php?order_id=ORDER_ID_PLACEHOLDER">Leave a review</a> for a completed order.
                    </div>
                <?php else: ?>
                    <div class="alert alert-info">
                        <a href="login.php?redirect_url=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">Log in</a> to see reviews or leave your own.
                    </div>
                <?php endif; ?>

                <?php if ($ratings): ?>
                    <?php foreach ($ratings as $rating): ?>
                        <div class="card mb-3">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <h5 class="card-title"><?php echo htmlspecialchars($rating['user_name']); ?></h5>
                                    <span class="text-warning"><?php echo str_repeat('★', $rating['rating']) . str_repeat('☆', 5 - $rating['rating']); ?></span>
                                </div>
                                <p class="card-text"><?php echo nl2br(htmlspecialchars($rating['review'])); ?></p>
                                <p class="card-text"><small class="text-muted"><?php echo date('F j, Y, g:i a', strtotime($rating['created_at'])); ?></small></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p>This restaurant has no reviews yet. Be the first!</p>
                <?php endif; ?>
            </div>
        </div>

    <?php else: ?>
        <p class="alert alert-warning">Restaurant not found.</p>
    <?php endif; ?>
</div>

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