<?php
// --- VERY IMPORTANT: FOR DEBUGGING ONLY ---
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// --- ROBUST URL HANDLING LOGIC (ID & SLUG) ---
$library_id = null;
$slug = null;
$library = false;

if (isset($_GET['id']) && !empty($_GET['id'])) {
    $library_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    if ($library_id) {
        $stmt_slug = $conn->prepare("SELECT slug FROM libraries WHERE id = ?");
        $stmt_slug->execute([$library_id]);
        $result = $stmt_slug->fetch(PDO::FETCH_ASSOC);
        if ($result && !empty($result['slug'])) {
            $new_url = '/library_details/' . $result['slug'];
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: " . $new_url);
            exit();
        }
    }
}
elseif (isset($_GET['slug']) && !empty($_GET['slug'])) {
    $slug = filter_input(INPUT_GET, 'slug', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
}
else {
    header('Location: /index.php');
    exit();
}

// --- UNIFIED DATA FETCHING ---
if ($slug) {
    $stmt_library = $conn->prepare("SELECT * FROM libraries WHERE slug = ? AND status = 'approved'");
    $stmt_library->execute([$slug]);
    $library = $stmt_library->fetch(PDO::FETCH_ASSOC);
} elseif ($library_id) {
    // This part is mainly for old ID-based URLs before redirection
    $stmt_library = $conn->prepare("SELECT * FROM libraries WHERE id = ? AND status = 'approved'");
    $stmt_library->execute([$library_id]);
    $library = $stmt_library->fetch(PDO::FETCH_ASSOC);
}

if (!$library) {
    http_response_code(404);
    die("<h1>404 Not Found</h1><p>The library you are looking for does not exist.</p><a href='/index.php'>Go Home</a>");
}

$library_id = $library['id']; // Ensure library_id is set correctly from fetched data
$slug = $library['slug'];

// --- (The rest of your PHP logic for eligibility, reviews, etc. remains the same) ---
$can_submit_review = false;
$has_already_reviewed = false;
$is_student_logged_in = isset($_SESSION['student_id']);
if ($is_student_logged_in) {
    $student_id = $_SESSION['student_id'];
    $stmt_check_booking = $conn->prepare("SELECT 1 FROM bookings WHERE student_id = ? AND library_id = ? UNION SELECT 1 FROM previous_bookings WHERE student_id = ? AND library_id = ? LIMIT 1");
    $stmt_check_booking->execute([$student_id, $library_id, $student_id, $library_id]);
    if ($stmt_check_booking->fetch()) {
        $can_submit_review = true;
    }
    $stmt_check_reviewed = $conn->prepare("SELECT 1 FROM reviews WHERE student_id = ? AND library_id = ? LIMIT 1");
    $stmt_check_reviewed->execute([$student_id, $library_id]);
    if ($stmt_check_reviewed->fetch()) {
        $has_already_reviewed = true;
    }
}

// Check if user is fully eligible to write a review
$is_eligible_for_review = $is_student_logged_in && $can_submit_review && !$has_already_reviewed;

// ##################################################################
// ### UPDATED REVIEW SUBMISSION LOGIC ###
// ##################################################################
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_review'])) {
    
    // 1. Check eligibility again on the server side (IMPORTANT!)
    if (!$is_eligible_for_review) {
        $_SESSION['error_message'] = "You are not eligible to submit a review for this library.";
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit();
    }

    // 2. Get data from the form
    $rating = filter_input(INPUT_POST, 'rating', FILTER_VALIDATE_INT);
    $review_text = trim(filter_input(INPUT_POST, 'review_text', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
    $student_id = $_SESSION['student_id'];

    // 3. Validate rating
    if ($rating === false || $rating < 1 || $rating > 5) {
        $_SESSION['error_message'] = "Please select a valid star rating.";
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit();
    }
    
    // Get student's name from session or database
    $student_name = $_SESSION['student_name'] ?? 'Anonymous Student';

    // 4. Insert the review into the database using a transaction
    $conn->beginTransaction();
    try {
        $stmt_insert_review = $conn->prepare(
            "INSERT INTO reviews (library_id, student_id, user_name, rating, review_text, created_at) 
             VALUES (?, ?, ?, ?, ?, NOW())"
        );
        $stmt_insert_review->execute([$library_id, $student_id, $student_name, $rating, $review_text]);

        // 5. Update the library's average rating and count
        $stmt_update_lib = $conn->prepare(
            "UPDATE libraries SET 
             rating_count = (SELECT COUNT(*) FROM reviews WHERE library_id = ?),
             rating_average = (SELECT AVG(rating) FROM reviews WHERE library_id = ?)
             WHERE id = ?"
        );
        $stmt_update_lib->execute([$library_id, $library_id, $library_id]);

        $conn->commit();

        // 6. Set success message and redirect
        $_SESSION['success_message'] = "Thank you! Your review has been submitted successfully.";
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit();

    } catch (Exception $e) {
        $conn->rollBack();
        $_SESSION['error_message'] = "An error occurred while submitting your review. Please try again.";
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit();
    }
}
// ##################################################################


// --- DATA FETCHING FOR PAGE ---
$stmt_shifts = $conn->prepare("SELECT shift_name, start_time, end_time, price FROM shifts WHERE library_id = ? AND status = 'active' ORDER BY start_time ASC");
$stmt_shifts->execute([$library_id]);
$shifts = $stmt_shifts->fetchAll(PDO::FETCH_ASSOC);

$stmt_reviews = $conn->prepare("SELECT r.*, s.photo, s.gender FROM reviews r LEFT JOIN students s ON r.student_id = s.id WHERE r.library_id = ? ORDER BY r.created_at DESC");
$stmt_reviews->execute([$library_id]);
$reviews = $stmt_reviews->fetchAll(PDO::FETCH_ASSOC);

$related_libraries = [];
if (!empty($library['city'])) {
    $stmt_related = $conn->prepare("SELECT * FROM libraries WHERE city = ? AND id != ? AND status = 'approved' LIMIT 3");
    $stmt_related->execute([$library['city'], $library_id]);
    $related_libraries = $stmt_related->fetchAll(PDO::FETCH_ASSOC);
}

// --- HELPER DATA & FUNCTIONS ---
$starting_price = $library['fee_monthly'];
if (!empty($shifts)) {
    $shift_prices = array_column($shifts, 'price');
    if (!empty($shift_prices)) {
        $starting_price = min($shift_prices);
    }
}
$amenities_map = [
    'has_wifi' => ['icon' => 'fas fa-wifi', 'title' => 'Free Wi-Fi'], 'has_ac' => ['icon' => 'fas fa-snowflake', 'title' => 'Fully AC'],
    'has_power_outlets' => ['icon' => 'fas fa-plug', 'title' => 'Charging Plug'], 'has_parking' => ['icon' => 'fas fa-car', 'title' => 'Parking Available'],
    'has_restrooms' => ['icon' => 'fas fa-restroom', 'title' => 'Clean Toilets'], 'has_water' => ['icon' => 'fas fa-tint', 'title' => 'RO Purified Water'],
    'has_lockers' => ['icon' => 'fas fa-lock', 'title' => 'Personal Lockers'], 'has_discussion_room' => ['icon' => 'fas fa-users', 'title' => 'Discussion Room']
];
$shift_icons = ['Morning' => 'fas fa-sun', 'Good Noon' => 'fas fa-cloud-sun', 'Evening' => 'fas fa-cloud-sun', 'Day' => 'fas fa-sun', 'Night' => 'fas fa-moon'];
$gallery_photos = [];
if (!empty($library['main_image'])) { $gallery_photos[] = 'uploads/' . htmlspecialchars($library['main_image']); }
if (!empty($library['gallery_photos'])) {
    $decoded_gallery = json_decode($library['gallery_photos'], true);
    if (is_array($decoded_gallery)) { foreach ($decoded_gallery as $photo) { $gallery_photos[] = 'uploads/' . htmlspecialchars($photo); } }
}
if (empty($gallery_photos)) { $gallery_photos[] = 'https://placehold.co/1200x400/FF6B35/FFFFFF?text=Padzo'; }

// ##################################################################
// ### SEO VARIABLES GENERATION ###
// ##################################################################
$seo_title = htmlspecialchars($library['name']) . ' in ' . htmlspecialchars($library['city']) . ' | Padzo';
$seo_description = 'Explore ' . htmlspecialchars($library['name']) . ' in ' . htmlspecialchars($library['city']) . ', located at ' . htmlspecialchars($library['address']) . '. Check details and book your seat on Padzo.';
$seo_keywords = htmlspecialchars($library['name']) . ', ' . htmlspecialchars($library['name']) . ' in ' . htmlspecialchars($library['city']) . ', library in ' . htmlspecialchars($library['city']) . ', study space in ' . htmlspecialchars($library['city']) . ', reading room ' . htmlspecialchars($library['city']) . ', padzo';
$canonical_url = 'https://padzo.in/library_details/' . $slug;
$og_image = 'https://padzo.in/https://placehold.co/1200x630/FF6B35/FFFFFF?text=Padzo';
if (!empty($library['main_image'])) {
    $og_image = 'https://padzo.in/uploads/' . htmlspecialchars($library['main_image']);
}
// ##################################################################

function render_library_card($lib) {
    $image_url = 'https://placehold.co/500x280/FF6B35/FFFFFF?text=Padzo';
    if (!empty($lib['main_image'])) { $image_url = 'uploads/' . htmlspecialchars($lib['main_image']); }
    $opening_hours = ($lib['opening_time'] === null || $lib['closing_time'] === null) ? '24 Hours' : date('g A', strtotime($lib['opening_time'])) . ' - ' . date('g A', strtotime($lib['closing_time']));
    $link_url = !empty($lib['slug']) ? '/library_details/' . htmlspecialchars($lib['slug']) : '/library_details?id=' . $lib['id'];
?>
    <a href="<?php echo $link_url; ?>" class="library-card">
        <?php if ($lib['is_premium']): ?><div class="premium-border-tag">Popular</div><?php endif; ?>
        <div class="library-image"><img src="/<?php echo $image_url; ?>" alt="<?php echo htmlspecialchars($lib['name']); ?>"></div>
        <div class="library-info">
            <div class="library-title-row">
                <h3><?php echo htmlspecialchars($lib['name']); ?></h3>
                <?php if ($lib['rating_average'] >= 2.0 && $lib['rating_count'] >= 1): ?>
                <div class="library-rating"><i class="fas fa-star"></i> <?php echo htmlspecialchars($lib['rating_average']); ?></div>
                <?php endif; ?>
            </div>
            <p class="library-meta"><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($lib['address']); ?></p>
            <div class="library-info-footer">
                <div class="library-details-row">
                    <div class="opening-hours"><i class="fas fa-clock"></i> <?php echo $opening_hours; ?></div>
                    <div class="total-seats"><i class="fas fa-chair"></i> <?php echo htmlspecialchars($lib['total_seats']); ?> Seats</div>
                </div>
            </div>
        </div>
    </a>
<?php }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title><?php echo $seo_title; ?></title>
    <meta name="description" content="<?php echo $seo_description; ?>">
    <meta name="keywords" content="<?php echo $seo_keywords; ?>">
    <link rel="canonical" href="<?php echo $canonical_url; ?>" />
    
    <link rel="icon" type="image/png" href="/uploads/logos/icon.png">
    <link rel="apple-touch-icon" href="/uploads/logos/icon.png">
    
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?php echo $canonical_url; ?>">
    <meta property="og:title" content="<?php echo $seo_title; ?>">
    <meta property="og:description" content="<?php echo $seo_description; ?>">
    <meta property="og:image" content="<?php echo $og_image; ?>">
    
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:url" content="<?php echo $canonical_url; ?>">
    <meta name="twitter:title" content="<?php echo $seo_title; ?>">
    <meta name="twitter:description" content="<?php echo $seo_description; ?>">
    <meta name="twitter:image" content="<?php echo $og_image; ?>">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #FF6B35; --secondary-color: #FF9F1C; --dark-color: #292922;
            --premium-color: #FFD700; --star-color: #FFC107; --star-inactive-color: #ccc;
        }
        /* [Your existing CSS remains the same from here...] */
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: #FFF5F0; color: var(--dark-color); line-height: 1.6; padding-bottom: 150px; }
        .container { max-width: 100%; padding: 0 15px; margin: 0 auto; }
        
        /* MODIFIED: Header is now sticky by default */
        header { background: #FFFFFF; padding: 15px 0; position: sticky; top: 0; z-index: 100; box-shadow: 0 2px 10px rgba(0,0,0,0.08); }

        .header-mobile { display: flex; justify-content: space-between; align-items: center; }
        .header-mobile .back-link { font-size: 1.2rem; color: var(--dark-color); }
        .header-mobile .page-title { font-size: 1.1rem; font-weight: 600; position: absolute; left: 50%; transform: translateX(-50%); }
        .header-mobile .user-actions { display: flex; align-items: center; gap: 20px; }
        .header-mobile .user-actions a { color: var(--dark-color); font-size: 1.2rem; }
        .header-desktop { display: none; }
        .slider-container { width: 100%; height: 250px; overflow: hidden; position: relative; background-color: #E9ECEF; }
        .slides { display: flex; width: <?php echo count($gallery_photos) * 100; ?>%; height: 100%; transition: transform 0.8s ease-in-out; }
        .slide { width: <?php echo 100 / (count($gallery_photos) ?: 1); ?>%; height: 100%; }
        .slide img { width: 100%; height: 100%; object-fit: contain; }
        .details-main-container { margin-top: -50px; position: relative; z-index: 2; margin-bottom: 30px; }
        .details-content-card { padding: 20px; background: white; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); position: relative; overflow: hidden; }
        .details-header { text-align: center; margin-bottom: 20px; border-bottom: 1px solid #eee; padding-bottom: 15px; }
        .popular-ribbon-wrapper { width: 120px; height: 120px; overflow: hidden; position: absolute; top: -8px; left: -8px; z-index: 4; }
        .popular-ribbon { position: absolute; display: block; width: 170px; padding: 6px 0; background-color: var(--primary-color); box-shadow: 0 5px 10px rgba(0,0,0,0.1); color: #fff; font-size: 0.7rem; font-weight: bold; text-transform: uppercase; letter-spacing: 0.5px; text-align: center; transform: rotate(-45deg); left: -55px; top: 28px; }
        .details-header h1 { font-size: 1.5rem; line-height: 1.3; margin-bottom: 8px; padding: 0 10px; font-weight: 700; }
        .details-meta { font-size: 0.8rem; color: #777; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 5px 15px; }
        .library-code-tag { display: inline-block; font-size: 0.7rem; font-weight: 600; padding: 3px 8px; background-color: #f0f3f5; color: #5c677d; border-radius: 4px; }
        .details-rating { font-size: 0.9rem; color: #555; margin-bottom: 8px; }
        .details-rating .fa-star { color: var(--star-color); }
        .details-section { margin-bottom: 25px; }
        .details-section-title { font-size: 1.1rem; font-weight: 600; margin-bottom: 15px; border-left: 4px solid var(--primary-color); padding-left: 10px; }
        .info-list li { list-style: none; display: flex; align-items: center; margin-bottom: 10px; font-size: 0.9rem; }
        .info-list i { color: var(--primary-color); width: 25px; text-align: center; margin-right: 10px; }
        .shifts-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 12px; }
        .shift-card { background: #FFF9F5; border: 1px solid #FFDDC9; border-radius: 10px; padding: 12px 8px; text-align: center; }
        .shift-icon { font-size: 1.4rem; color: var(--secondary-color); margin-bottom: 5px; }
        .shift-name { font-weight: 600; font-size: 0.8rem; line-height: 1.2; }
        .shift-time { font-size: 0.7rem; color: #666; line-height: 1.1; margin-bottom: 4px; }
        .shift-price { font-size: 0.9rem; font-weight: 700; color: var(--primary-color); }
        .amenities-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
        .amenity-item { display: flex; align-items: center; font-size: 0.85rem; }
        .amenity-item i { color: var(--primary-color); width: 25px; text-align: center; margin-right: 10px; }
        .review-card { border-bottom: 1px solid #eee; padding: 12px 0; margin-bottom: 8px; }
        .review-header { display: flex; align-items: center; margin-bottom: 5px; gap: 12px; }
        .review-header .avatar { width: 40px; height: 40px; border-radius: 50%; background: var(--primary-color); color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0; }
        .review-header .avatar i { font-size: 1.5rem; }
        .review-header .avatar-photo { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; flex-shrink: 0; }
        .review-header .user-info { flex-grow: 1; display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; min-width: 0; }
        .review-header .user-info .name { font-size: 0.9rem; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .review-header .user-info .date { font-size: 0.75rem; color: #777; flex-shrink: 0; }
        .review-stars { flex-shrink: 0; }
        .review-stars i { color: var(--star-color); font-size: 0.8rem; }
        .write-review-stars { text-align: center; margin-bottom: 15px; }
        .write-review-stars i { font-size: 2rem; color: var(--star-inactive-color); cursor: pointer; transition: color 0.2s, transform 0.2s; margin: 0 5px; }
        .write-review-stars i:hover, .write-review-stars i.selected { color: var(--star-color); transform: scale(1.1); }
        .review-form-container { display: none; margin-top: 15px; }
        #review-text { width: 100%; padding: 10px; border-radius: 8px; border: 1px solid #ddd; min-height: 100px; margin-bottom: 10px; }
        #submit-review-btn { width: 100%; background: var(--primary-color); color: white; border: none; padding: 12px; border-radius: 8px; font-weight: bold; cursor: pointer; }
        .desktop-sidebar { display: none; }
        .library-list { display: grid; gap: 20px; }
        .library-card { background: white; border-radius: 15px; text-decoration: none; color: inherit; box-shadow: 0 3px 10px rgba(255,107,53,0.1); position: relative; display: flex; flex-direction: column; }
        .premium-border-tag { position: absolute; top: 15px; left: -8px; background-color: var(--primary-color); color: white; padding: 5px 12px; font-size: 0.7rem; font-weight: 700; border-radius: 0 5px 5px 0; z-index: 2; }
        .library-image { height: 140px; border-radius: 15px 15px 0 0; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center; overflow: hidden; }
        .library-image img { width: 100%; height: 100%; object-fit: contain; }
        .library-info { padding: 12px; display: flex; flex-direction: column; flex-grow: 1; }
        .library-title-row { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 5px; }
        .library-meta { font-size: 0.75rem; color: #666; margin-bottom: 10px; }
        .library-info-footer { margin-top: auto; border-top: 1px solid #eee; padding-top: 10px; }
        .library-details-row { display: flex; justify-content: space-between; font-size: 0.7rem; color: #555; }
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; display: flex; justify-content: space-around; align-items: center; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); z-index: 100; height: 65px; }
        .nav-item { display: flex; flex-direction: column; align-items: center; color: #666; text-decoration: none; font-size: 0.75rem; }
        .nav-item i { font-size: 1.2rem; margin-bottom: 3px; }
        .nav-item.active { color: var(--primary-color); }
        .bottom-book-bar { position: fixed; bottom: 65px; left: 0; right: 0; background: white; padding: 8px 15px; box-shadow: 0 -2px 10px rgba(0,0,0,0.08); z-index: 99; display: flex; justify-content: space-between; align-items: center; }
        .price-info { line-height: 1.2; }
        .price-info .label { font-size: 0.75rem; color: #666; }
        .price-info .amount { font-size: 1.4rem; font-weight: 700; color: var(--primary-color); }
        .price-info .amount small { font-size: 0.8rem; font-weight: 500; }
        .book-now-btn { background: var(--primary-color); color: white; border: none; padding: 12px 25px; border-radius: 8px; font-weight: bold; cursor: pointer; text-decoration: none; text-align: center; display: inline-block; }
        .info-box { text-align: center; color: #666; background-color: #f9f9f9; padding: 15px; border-radius: 8px; }

        /* NEW: Popup Styles */
        .review-popup-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.6); z-index: 1001;
            display: none; /* Hidden by default */
            align-items: center; justify-content: center; padding: 15px;
        }
        .review-popup-content {
            background: white; padding: 25px; border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2); text-align: center;
            position: relative; max-width: 400px; width: 100%;
        }
        .review-popup-close {
            position: absolute; top: 10px; right: 15px; font-size: 1.8rem;
            color: #aaa; cursor: pointer; line-height: 1;
        }
        .review-popup-close:hover { color: #333; }
        .review-popup-content p { font-size: 1rem; color: #555; margin: 0; }
        .review-popup-content p a { color: var(--primary-color); font-weight: 600; }

        /* NEW: Icon Loading Animation */
        body.loading [class*="fa-"] {
            animation: pulse-placeholder 1.5s infinite ease-in-out;
            background-color: #e0e0e0;
            color: transparent !important; /* Hide original icon color */
            border-radius: 4px; /* Make it look like a placeholder box */
            display: inline-block;
            line-height: 1;
            min-width: 1em;
            min-height: 1em;
        }
        @keyframes pulse-placeholder {
            0% { opacity: 0.6; }
            50% { opacity: 1; }
            100% { opacity: 0.6; }
        }

        /* NEW: Mobile Header Fix & Body Padding */
        @media (max-width: 1023px) {
            body {
                padding-top: 60px; /* Height of the fixed mobile header */
            }
            header {
                position: fixed;
                width: 100%;
                top: 0;
            }
        }

        @media (min-width: 768px) { .container { max-width: 720px; } .amenities-grid { grid-template-columns: repeat(3, 1fr); } .library-list { grid-template-columns: repeat(3, 1fr); } }
        @media (min-width: 1024px) {
            body { padding-bottom: 0; } .container { max-width: 1140px; } .header-mobile, .bottom-book-bar, .bottom-nav { display: none; }
            .header-desktop { display: grid; align-items: center; grid-template-columns: auto 1fr auto; gap: 20px; }
            .header-desktop .logo { font-size: 1.6rem; font-weight: bold; display: flex; align-items: center; color: var(--dark-color); text-decoration: none; }
            .header-desktop .logo i { margin-right: 10px; color: var(--primary-color); }
            .header-desktop .desktop-nav { display: flex; justify-content: center; gap: 30px; }
            .header-desktop .desktop-nav a { text-decoration: none; color: #555; font-weight: 500; }
            .header-desktop .user-actions { display: flex; justify-self: flex-end; align-items: center; gap: 25px; }
            .header-desktop .user-actions a { color: var(--dark-color); font-size: 1.2rem; }
            .slider-container { height: 400px; border-radius: 15px; }
            .details-main-container { margin-top: -50px; }
            .details-layout-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 30px; align-items: flex-start; }
            .desktop-sidebar { display: block; position: sticky; top: 90px; }
            .booking-widget { background: white; padding: 20px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.08); margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; gap: 15px; }
            .booking-widget .book-now-btn { width: auto; flex-shrink: 0; font-size: 1rem; padding: 12px 20px; }
            .contact-widget { background: white; padding: 20px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.08); }
        }
    </style>
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "Library",
      "name": "<?php echo htmlspecialchars($library['name']); ?>",
      "image": "<?php echo $og_image; ?>",
      "url": "<?php echo $canonical_url; ?>",
      "telephone": "<?php echo htmlspecialchars($library['contact_number']); ?>",
      "email": "<?php echo htmlspecialchars($library['email']); ?>",
      "address": {
        "@type": "PostalAddress",
        "streetAddress": "<?php echo htmlspecialchars($library['address']); ?>",
        "addressLocality": "<?php echo htmlspecialchars($library['city']); ?>",
        "addressCountry": "IN"
      },
      "description": "<?php echo $seo_description; ?>",
      "brand": {
        "@type": "Brand",
        "name": "Padzo",
        "logo": "https://padzo.in/uploads/logo2.png"
      },
      <?php if ($library['opening_time'] !== null): ?>
      "openingHours": "Mo-Su <?php echo date('H:i', strtotime($library['opening_time'])); ?>-<?php echo date('H:i', strtotime($library['closing_time'])); ?>",
      <?php else: ?>
      "openingHours": "Mo-Su 00:00-23:59",
      <?php endif; ?>
      <?php if ($library['rating_average'] > 0 && $library['rating_count'] > 0): ?>
      "aggregateRating": {
        "@type": "AggregateRating",
        "ratingValue": "<?php echo $library['rating_average']; ?>",
        "reviewCount": "<?php echo $library['rating_count']; ?>"
      },
      <?php endif; ?>
      "priceRange": "₹<?php echo round($starting_price); ?>"
    }
    </script>
</head>
<body class="loading">
    <header>
        <div class="container header-mobile">
            <a href="/libraries.php" class="back-link"><i class="fas fa-arrow-left"></i></a>
            <a href="/" class="logo"><img src="/uploads/logo2.png" alt="Padzo Logo" style="height: 30px;"></a>
            <div class="user-actions">
                <a href="#" id="share-button-mobile"><i class="fas fa-share-alt"></i></a>
            </div>
        </div>
        <div class="container header-desktop">
            <a href="/" class="logo"><img src="/uploads/logo2.png" alt="Padzo Logo" style="height: 40px;"></a>
            <nav class="desktop-nav"><a href="/index.php">Home</a><a href="/libraries.php">Find Libraries</a><a href="/student/login_student.php">My Bookings</a><a href="/profile.php">Profile</a></nav>
            <div class="user-actions">
                <a href="#" id="share-button-desktop"><i class="fas fa-share-alt"></i></a>
                <a href="#"><i class="fas fa-bell"></i></a>
            </div>
        </div>
    </header>

    <div class="container">
        <?php if (isset($_SESSION['success_message'])): ?>
            <div style="padding: 15px; background-color: #D4EDDA; color: #155724; border: 1px solid #C3E6CB; border-radius: 8px; margin-top: 15px; margin-bottom: 15px;"><?php echo $_SESSION['success_message']; ?></div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>
        <?php if (isset($_SESSION['error_message'])): ?>
            <div style="padding: 15px; background-color: #F8D7DA; color: #721C24; border: 1px solid #F5C6CB; border-radius: 8px; margin-top: 15px; margin-bottom: 15px;"><?php echo $_SESSION['error_message']; ?></div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>
    </div>
    <main>
        <div class="slider-container">
            <div class="slides">
                <?php foreach ($gallery_photos as $photo_url): ?>
                <div class="slide"><img src="/<?php echo $photo_url; ?>" alt="Library Gallery Image"></div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="container details-main-container">
            <div class="details-layout-grid">
                <div class="main-column">
                    <div class="details-content-card">
                        
                        <?php if ($library['is_premium']): ?>
                        <div class="popular-ribbon-wrapper"><div class="popular-ribbon">Popular</div></div>
                        <?php endif; ?>

                        <div class="details-header">
                            <h1><?php echo htmlspecialchars($library['name']); ?></h1>
                            <?php if ($library['rating_average'] >= 2.0 && $library['rating_count'] >= 1): ?>
                            <div class="details-rating"><i class="fas fa-star"></i> <?php echo htmlspecialchars(number_format($library['rating_average'], 1)); ?> (based on <?php echo htmlspecialchars($library['rating_count']); ?> Reviews)</div>
                            <?php endif; ?>
                            <div class="details-meta">
                                <span><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($library['address']); ?> - <?php echo htmlspecialchars($library['city']); ?></span>
                                <?php if (!empty($library['library_code'])): ?>
                                <span class="library-code-tag">ID: <?php echo htmlspecialchars($library['library_code']); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <section class="details-section">
                            <ul class="info-list">
                                <li><i class="fas fa-chair"></i><strong><?php echo htmlspecialchars($library['total_seats']); ?> Total Seats</strong></li>
                                <li>
                                    <i class="fas fa-clock"></i>
                                    <strong>
                                        <?php echo ($library['opening_time'] === null || $library['closing_time'] === null) ? 'Open 24 Hours' : date('g:i A', strtotime($library['opening_time'])) . ' - ' . date('g:i A', strtotime($library['closing_time'])); ?>
                                    </strong>
                                </li>
                            </ul>
                        </section>
                        
                        <?php if (!empty($shifts)): ?>
                        <section class="details-section"><h2 class="details-section-title">Available Shifts</h2><div class="shifts-grid"><?php foreach ($shifts as $shift): ?><div class="shift-card"><i class="<?php echo $shift_icons[$shift['shift_name']] ?? 'fas fa-clock'; ?> shift-icon"></i><div class="shift-name"><?php echo htmlspecialchars($shift['shift_name']); ?></div><div class="shift-time"><?php echo date('g:i A', strtotime($shift['start_time'])) . ' - ' . date('g:i A', strtotime($shift['end_time'])); ?></div><div class="shift-price">₹<?php echo round($shift['price']); ?></div></div><?php endforeach; ?></div></section>
                        <?php endif; ?>
                        <section class="details-section"><h2 class="details-section-title">Amenities</h2><div class="amenities-grid"><?php foreach ($amenities_map as $key => $amenity): if ($library[$key]): ?><div class="amenity-item"><i class="<?php echo $amenity['icon']; ?>"></i> <?php echo $amenity['title']; ?></div><?php endif; endforeach; ?></div></section>
                        <section class="details-section desktop-contact-hidden"><h2 class="details-section-title">Contact Information</h2><ul class="info-list"><?php if(!empty($library['contact_number'])): ?><li><i class="fas fa-mobile-alt"></i> <?php echo htmlspecialchars($library['contact_number']); ?></li><?php endif; ?><?php if(!empty($library['email'])): ?><li><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($library['email']); ?></li><?php endif; ?><li><i class="fas fa-map-marked-alt"></i> <?php echo htmlspecialchars($library['address']) . ', ' . htmlspecialchars($library['city']); ?></li></ul></section>
                        <section class="details-section">
                            <h2 class="details-section-title">Reviews & Ratings</h2>
                            <div class="review-list">
                                <?php if (empty($reviews)): ?>
                                    <p>No reviews yet. Be the first to write one!</p>
                                <?php else: foreach ($reviews as $review): ?>
                                <div class="review-card">
                                    <div class="review-header">
                                        <?php
                                            if (!empty($review['photo']) && file_exists('uploads/' . $review['photo'])):
                                        ?>
                                            <img src="/uploads/<?php echo htmlspecialchars($review['photo']); ?>" alt="User photo" class="avatar-photo">
                                        <?php else: 
                                            $avatar_content = (isset($review['gender']) && strtolower($review['gender']) === 'female') ? '<i class="fas fa-female"></i>' : '<i class="fas fa-user-graduate"></i>';
                                        ?>
                                            <div class="avatar"><?php echo $avatar_content; ?></div>
                                        <?php endif; ?>
                                        <div class="user-info" title="<?php echo htmlspecialchars($review['user_name']); ?>">
                                            <div class="name"><?php echo htmlspecialchars($review['user_name']); ?></div>
                                            <div class="date"><?php echo date('F j, Y', strtotime($review['created_at'])); ?></div>
                                        </div>
                                        <div class="review-stars"><?php for($i=0; $i<5; $i++): ?><i class="<?php echo $i < $review['rating'] ? 'fas' : 'far'; ?> fa-star"></i><?php endfor; ?></div>
                                    </div>
                                    <p class="review-text"><?php echo htmlspecialchars($review['review_text']); ?></p>
                                </div>
                                <?php endforeach; endif; ?>
                            </div>
                        </section>
                        <section class="details-section">
                            <?php if ($is_student_logged_in && $has_already_reviewed): ?>
                                <h2 class="details-section-title">Your Feedback</h2>
                                <div class="info-box"><i class="fas fa-check-circle"></i> Thanks for your feedback on this library!</div>
                            <?php else: ?>
                                <h2 class="details-section-title">Write Your Review</h2>
                                <form method="POST" action="<?php echo $slug ? '/library_details/' . $slug : '/library_details?id=' . $library_id; ?>">
                                    <input type="hidden" name="rating" id="rating-input" value="0">
                                    <div class="write-review-stars" id="write-review-stars">
                                        <?php for($i=1; $i<=5; $i++): ?><i class="far fa-star" data-value="<?php echo $i; ?>"></i><?php endfor; ?>
                                    </div>
                                    <div class="review-form-container" id="review-form-container">
                                        <textarea name="review_text" id="review-text" placeholder="Share your experience... (optional)"></textarea>
                                        <button type="submit" name="submit_review" id="submit-review-btn">Submit Review</button>
                                    </div>
                                </form>
                            <?php endif; ?>
                        </section>
                        </div>
                </div>
                <div class="desktop-sidebar">
                    <div class="booking-widget">
                        <div class="price-info"><span class="label">Starts From</span><div class="amount">₹<?php echo round($starting_price); ?></div></div>
                        <a href="/student/view_library?lib_id=<?php echo htmlspecialchars($library['id']); ?>" class="book-now-btn">Book Seat</a>
                    </div>
                    <div class="contact-widget"><h2 class="details-section-title">Contact Info</h2><ul class="info-list"><?php if(!empty($library['contact_number'])): ?><li><i class="fas fa-phone-alt"></i> <?php echo htmlspecialchars($library['contact_number']); ?></li><?php endif; ?><?php if(!empty($library['email'])): ?><li><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($library['email']); ?></li><?php endif; ?><li><i class="fas fa-map-marked-alt"></i> <?php echo htmlspecialchars($library['address']) . ', ' . htmlspecialchars($library['city']); ?></li></ul></div>
                </div>
            </div>
            <?php if (!empty($related_libraries)): ?>
            <section class="details-section" style="margin-top: 30px;"><h2 class="details-section-title">Related Libraries in <?php echo htmlspecialchars($library['city']); ?></h2><div class="library-list"><?php foreach ($related_libraries as $related_lib): ?><?php render_library_card($related_lib); ?><?php endforeach; ?></div></section>
            <?php endif; ?>
        </div>
    </main>
    <div class="bottom-book-bar"><div class="price-info"><span class="label">Starts From</span><div class="amount">₹<?php echo round($starting_price); ?></div></div><a href="/student/view_library?lib_id=<?php echo htmlspecialchars($library['id']); ?>" class="book-now-btn">Book Seat</a></div>
    <nav class="bottom-nav"><a href="/index.php" class="nav-item"><i class="fas fa-home"></i><span>Home</span></a><a href="/libraries.php" class="nav-item"><i class="fas fa-book-open"></i><span>Find Libraries</span></a><a href="/student/student_dashboard.php" class="nav-item"><i class="fas fa-id-card"></i><span>My Bookings</span></a><a href="/profile.php" class="nav-item"><i class="fas fa-user"></i><span>Profile</span></a></nav>
    
    <div id="review-popup" class="review-popup-overlay">
        <div class="review-popup-content">
            <span id="review-popup-close" class="review-popup-close">&times;</span>
            <p id="review-popup-message"></p>
        </div>
    </div>
    
    <?php
        $share_description_parts = [
            'Check out ' . htmlspecialchars($library['name']) . ' on Padzo!',
            'Starting Fee: ₹' . round($starting_price),
            'Address: ' . htmlspecialchars($library['address'])
        ];
        $full_share_description = implode("\n", $share_description_parts);
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // NEW: Remove loading class to reveal icons
        document.body.classList.remove('loading');

        // [Your existing share logic script remains the same]
        const shareTitle = '<?php echo addslashes(htmlspecialchars($library['name'])); ?>';
        const shareText = `<?php echo addslashes($full_share_description); ?>`;
        const shareUrl = window.location.href;
        async function handleShare() { if (navigator.share) { try { await navigator.share({ title: shareTitle, text: shareText, url: shareUrl }); } catch (error) { console.error('Error sharing:', error); } } else { try { await navigator.clipboard.writeText(`${shareText}\n\nFind it here: ${shareUrl}`); alert('Library details copied to clipboard!'); } catch (err) { alert('Could not copy link.'); } } }
        function setupShareButton(id) { const btn = document.getElementById(id); if(btn) btn.addEventListener('click', (e) => { e.preventDefault(); handleShare(); }); }
        setupShareButton('share-button-mobile');
        setupShareButton('share-button-desktop');

        const slides = document.querySelector('.slides');
        if (slides) {
            const totalSlides = <?php echo count($gallery_photos) ?: 1; ?>;
            if (totalSlides > 1) { let currentSlide = 0; setInterval(() => { currentSlide = (currentSlide + 1) % totalSlides; slides.style.transform = `translateX(-${currentSlide * (100 / totalSlides)}%)`; }, 4000); }
        }

        // ############ NEW REVIEW & POPUP LOGIC ############
        const reviewEligibility = {
            isEligible: <?php echo json_encode($is_eligible_for_review); ?>,
            isLoggedIn: <?php echo json_encode($is_student_logged_in); ?>,
        };

        const reviewStars = document.querySelectorAll('#write-review-stars i');
        const reviewForm = document.getElementById('review-form-container');
        const ratingInput = document.getElementById('rating-input');
        const popup = document.getElementById('review-popup');
        const popupMessage = document.getElementById('review-popup-message');
        const popupClose = document.getElementById('review-popup-close');
        
        if (reviewStars.length > 0) {
            reviewStars.forEach(star => {
                star.addEventListener('click', function() {
                    if (reviewEligibility.isEligible) {
                        // User is eligible, proceed with form
                        let selectedRating = this.dataset.value;
                        ratingInput.value = selectedRating;
                        reviewStars.forEach((s, i) => { s.className = (i < selectedRating) ? 'fas fa-star selected' : 'far fa-star'; });
                        if (reviewForm) { reviewForm.style.display = 'block'; }
                    } else {
                        // User is NOT eligible, show popup
                        let message = '';
                        if (!reviewEligibility.isLoggedIn) {
                            message = 'Please <a href="/student/login_student.php">log in</a> and book a seat to write a review.';
                        } else {
                            message = 'You must book a seat at this library before you can leave a review.';
                        }
                        popupMessage.innerHTML = message;
                        popup.style.display = 'flex';
                    }
                });
            });
        }

        // Popup close functionality
        if (popup) {
            popupClose.addEventListener('click', () => { popup.style.display = 'none'; });
            popup.addEventListener('click', (event) => {
                if (event.target === popup) { popup.style.display = 'none'; }
            });
        }
        
        function handleContactVisibility() { const contactSection = document.querySelector('.desktop-contact-hidden'); if (contactSection) { contactSection.style.display = window.innerWidth >= 1024 ? 'none' : 'block'; } }
        handleContactVisibility();
        window.addEventListener('resize', handleContactVisibility);
    });
    </script>
</body>
</html>