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

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

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

// Handle review submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_review'])) {
    if (!isset($_SESSION['user_id'])) {
        // Redirect to login if not logged in
        header('Location: login.php');
        exit;
    }

    $rating = isset($_POST['rating']) ? (int)$_POST['rating'] : 0;
    $review = isset($_POST['review']) ? trim($_POST['review']) : '';
    $user_id = $_SESSION['user_id'];

    if ($rating >= 1 && $rating <= 5) {
        try {
            $insert_stmt = db()->prepare("INSERT INTO ratings (restaurant_id, user_id, rating, review) VALUES (:restaurant_id, :user_id, :rating, :review)");
            $insert_stmt->bindParam(':restaurant_id', $restaurant_id, PDO::PARAM_INT);
            $insert_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $insert_stmt->bindParam(':rating', $rating, PDO::PARAM_INT);
            $insert_stmt->bindParam(':review', $review, PDO::PARAM_STR);
            $insert_stmt->execute();
            // Redirect to the same page to prevent form resubmission
            header("Location: menu.php?id=$restaurant_id&rated=true");
            exit;
        } catch (PDOException $e) {
            $submit_error = "Error submitting your review. Please try again.";
            // In a real app, you'd log this error.
        }
    } else {
        $submit_error = "Please select a rating between 1 and 5.";
    }
}

require_once 'header.php';

try {
    // Fetch restaurant details
    $stmt = db()->prepare("SELECT name, image_url, cuisine FROM restaurants WHERE id = :id");
    $stmt->bindParam(':id', $restaurant_id, PDO::PARAM_INT);
    $stmt->execute();
    $restaurant = $stmt->fetch(PDO::FETCH_ASSOC);

    // 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;
    if (count($ratings) > 0) {
        $total_rating = 0;
        foreach ($ratings as $r) {
            $total_rating += $r['rating'];
        }
        $average_rating = round($total_rating / count($ratings), 1);
    }

} catch (PDOException $e) {
    echo "<div class='container'><p class='alert alert-danger'>Error fetching restaurant data.</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">
                <h1 class="display-4"><?php echo htmlspecialchars($restaurant['name']); ?></h1>
                <p class="lead text-muted"><?php echo htmlspecialchars($restaurant['cuisine']); ?></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'])): ?>
                    <div class="card mb-4">
                        <div class="card-header">Leave a Review</div>
                        <div class="card-body">
                            <?php if (isset($submit_error)): ?>
                                <div class="alert alert-danger"><?php echo $submit_error; ?></div>
                            <?php endif; ?>
                            <?php if (isset($_GET['rated']) && $_GET['rated'] == 'true'): ?>
                                <div class="alert alert-success">Thank you for your review!</div>
                            <?php endif; ?>
                            <form action="menu.php?id=<?php echo $restaurant_id; ?>" method="post">
                                <div class="mb-3">
                                    <label for="rating" class="form-label">Your Rating</label>
                                    <select class="form-select" id="rating" name="rating" required>
                                        <option value="" disabled selected>Choose a rating...</option>
                                        <option value="5">5 - Excellent</option>
                                        <option value="4">4 - Very Good</option>
                                        <option value="3">3 - Good</option>
                                        <option value="2">2 - Fair</option>
                                        <option value="1">1 - Poor</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="review" class="form-label">Your Review</label>
                                    <textarea class="form-control" id="review" name="review" rows="3" placeholder="What did you think?"></textarea>
                                </div>
                                <button type="submit" name="submit_review" class="btn btn-success">Submit Review</button>
                            </form>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="alert alert-info">
                        <a href="login.php?redirect_url=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">Log in</a> to leave a review.
                    </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'; ?>