<?php
// Include configuration and models using existing init.php
require_once __DIR__ . '/app/Core/init.php';
require_once __DIR__ . '/app/Core/DojahKYC.php';

// ── KYC status for the logged-in customer ──────────────────────────
$customer_is_kyc_verified = false;
$kyc_widget_id            = '';

if (Auth::check() && Auth::userType() === 'customer') {
    $kycCheck = new DojahKYC();
    $customer_is_kyc_verified = $kycCheck->isCustomerVerified(Auth::id());
    if (!$customer_is_kyc_verified) {
        $kyc_widget_id = $kycCheck->getWidgetId(DojahKYC::TYPE_CUSTOMER_IDENTITY);
    }
}

// Initialize models
$itemModel = new Item();
$categoryModel = new Category();
$reviewModel = new Review();


// Get item by slug OR id (backward compatible)
$item_slug = $_GET['slug'] ?? '';
$item_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$itemModel = new Item();

if ($item_slug) {
    $item = $itemModel->findBySlug($item_slug);
} elseif ($item_id) {
    $item = $itemModel->findById($item_id);
} else {
    redirect('items.php');
}

// Set page variables
$page_title = 'Item Details';
$body_class = 'bg-light';

// Get item data
try {
    $item = $itemModel->findBySlug($item_slug);
    
    if (!$item) {
        header('Location: items.php?error=Item not found');
        exit;
    }

    // Get items id
    $item_id = $item['id'];

    // ================================================================
    // CRITICAL: CHECK APPROVAL STATUS AND UPDATES
    // ================================================================
    // Check if item is approved
    $is_approved = ($item['approval_status'] === 'approved');
    $has_pending_updates = isset($item['updates_pending']) && ($item['updates_pending'] == 1);
    $is_active = (!isset($item['status']) || $item['status'] !== 'inactive');
    
    // Check if current user is the vendor who owns this item
    $is_owner = false;
    if (Auth::check() && Auth::userType() === 'vendor') {
        $vendorModel = new Vendor();
        $vendor_data = $vendorModel->findByUserId(Auth::id());
        if ($vendor_data && $vendor_data['id'] == $item['vendor_id']) {
            $is_owner = true;
        }
    }
    
    // Check if user is admin
    $is_admin = Auth::check() && Auth::userType() === 'admin';
    
    // REDIRECT if item is not approved (unless viewer is owner or admin)
    if (!$is_approved && !$is_owner && !$is_admin) {
        flash('error', 'This item is currently under review and not available for booking.', 'warning');
        redirect('items.php');
    }
    
    // REDIRECT if item has pending updates (unless viewer is owner or admin)
    if ($has_pending_updates && !$is_owner && !$is_admin) {
        flash('info', 'This item has pending updates under review and is temporarily unavailable for new bookings.', 'info');
        redirect('items.php');
    }
    
    // REDIRECT if item is inactive (unless viewer is owner or admin)
    if (!$is_active && !$is_owner && !$is_admin) {
        flash('error', 'This item is no longer available.', 'warning');
        redirect('items.php');
    }

    // Initialize OrderRating model
    require_once __DIR__ . '/app/Models/OrderRating.php';
    $ratingModel = new OrderRating();

    // Get item average rating (from order_ratings table)
    $item_rating_data = $ratingModel->getItemAverageRating($item_id);
    $item_average_rating = $item_rating_data['average'];
    $item_total_ratings = $item_rating_data['count'];

    // Get vendor average rating (from order_ratings table)
    $vendor_rating_data = $ratingModel->getVendorAverageRating($item['vendor_id']);
    $vendor_average_rating = $vendor_rating_data['average'];
    $vendor_total_ratings = $vendor_rating_data['count'];

    // Get all item ratings with customer details for display
    $item_ratings_sql = "SELECT 
                            r.item_rating,
                            r.item_review,
                            r.created_at,
                            CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                            o.order_number
                        FROM order_ratings r
                        JOIN orders o ON r.order_id = o.id
                        JOIN customers c ON o.customer_id = c.id
                        WHERE o.item_id = ? 
                        AND r.rater_type = 'customer'
                        AND r.item_rating IS NOT NULL
                        ORDER BY r.created_at DESC";
    $item_ratings_list = $db->fetchAll($item_ratings_sql, [$item_id]);


    // Get related items
    $related_items = $itemModel->getRelatedByCategory($item_id, $item['category_id'], 4);
    
    // Get item reviews
    $reviews_sql = "SELECT r.*, c.first_name, c.last_name 
                    FROM reviews r 
                    JOIN customers c ON r.customer_id = c.id 
                    WHERE r.item_id = ? AND r.status = 'active' 
                    ORDER BY r.created_at DESC 
                    LIMIT 10";
    $reviews = $db->fetchAll($reviews_sql, [$item_id]);
    
    // Calculate average rating
    $avg_rating_sql = "SELECT AVG(rating) as avg_rating, COUNT(*) as total_reviews 
                       FROM reviews 
                       WHERE item_id = ? AND status = 'active'";
    $rating_data = $db->fetch($avg_rating_sql, [$item_id]);
    $average_rating = $rating_data['avg_rating'] ?? 0;
    $total_reviews = $rating_data['total_reviews'] ?? 0;
    
} catch (Exception $e) {
    header('Location: items.php?error=Database error');
    exit;
}

// Include header template
include __DIR__ . '/templates/layouts/frontend/header.php';
?>
<?php
?>

<!-- Status Notices for Owner/Admin -->
<?php if ($is_owner || $is_admin): ?>
    <?php if (!$is_approved): ?>
        <div class="container mt-3">
            <div class="alert alert-warning alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i>
                <strong>Status Notice:</strong>
                <?php if ($item['approval_status'] === 'pending'): ?>
                    This item is <strong>pending approval</strong> and not visible to customers.
                <?php elseif ($item['approval_status'] === 'rejected'): ?>
                    This item was <strong>rejected</strong>. 
                    <?php if (!empty($item['rejection_reason'])): ?>
                        Reason: <?= htmlspecialchars($item['rejection_reason']) ?>
                    <?php endif; ?>
                <?php endif; ?>
                <?php if (!$is_admin): ?>
                    <br><small>Only you can see this page. Customers cannot view or book this item until it's approved.</small>
                <?php endif; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
    <?php endif; ?>
    
    <?php if ($has_pending_updates): ?>
        <div class="container">
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="fas fa-clock"></i>
                <strong>Pending Updates:</strong>
                This item has pending updates awaiting admin approval. Customers cannot make new bookings until updates are approved.
                <?php if (!$is_admin): ?>
                    <br><small>You can view the item, but customers are temporarily blocked from booking.</small>
                <?php endif; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
    <?php endif; ?>
<?php endif; ?>

    <!-- start breadcrumb -->
    <div class="py-3 bg-light border-bottom">
        <div class="container">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="items.php">Browse Items</a></li>
                    <li class="breadcrumb-item"><a href="items.php?category=<?= urlencode($item['category_slug'] ?? '') ?>"><?= htmlspecialchars($item['category_name'] ?? '') ?></a></li>
                    <li class="breadcrumb-item active" aria-current="page"><?= htmlspecialchars($item['title']) ?></li>
                </ol>
            </nav>
        </div>
    </div>
    <!-- end breadcrumb -->

    <!-- start item details -->
    <div class="py-5">
        <div class="container">
            <div class="row g-5">
                <!-- start item images and basic info -->
                <div class="col-lg-8">
                    <!-- start image gallery -->
                    <?php
                    /**
                     * ================================================================
                     * ITEM IMAGE GALLERY - REPLACEMENT CODE
                     * ================================================================
                     * Replace the image section in item-details.php (lines 90-155)
                     * with this complete code
                     * ================================================================
                     */

                    // Fetch additional images from item_images table
                    $additional_images_sql = "SELECT image_path FROM item_images 
                                            WHERE item_id = ? 
                                            ORDER BY display_order ASC";
                    $additional_images = $db->fetchAll($additional_images_sql, [$item_id]);

                    // Build complete images array
                    $all_images = [];

                    // Add main image first
                    if (!empty($item['main_image'])) {
                        $all_images[] = [
                            'path' => 'public/uploads/items/' . $item['main_image'],
                            'is_main' => true
                        ];
                    }

                    // Add additional images
                    foreach ($additional_images as $img) {
                        $all_images[] = [
                            'path' => 'public/uploads/items/' . $img['image_path'],
                            'is_main' => false
                        ];
                    }

                    // Fallback if no images
                    if (empty($all_images)) {
                        $all_images[] = [
                            'path' => 'assets/images/default-item.jpg',
                            'is_main' => true
                        ];
                    }

                    $total_images = count($all_images);
                    ?>

                    <!-- Image Gallery Section -->
                    <div class="mb-4">
                        <!-- Main Image Display -->
                        <div class="position-relative mb-3">
                            <div class="main-image-container rounded-4 overflow-hidden" style="height: 500px; background: #f8f9fa;">
                                <img id="mainImage" 
                                    src="<?= htmlspecialchars($all_images[0]['path']) ?>" 
                                    class="w-100 h-100" 
                                    style="object-fit: cover; cursor: pointer;"
                                    alt="<?= htmlspecialchars($item['title']) ?>"
                                    onclick="openLightbox(0)">
                            </div>
                            
                            <!-- Image Counter & Zoom - Top Right -->
                            <div class="position-absolute top-0 end-0 m-3 d-flex gap-2">
                                <?php if ($total_images > 1): ?>
                                <span class="badge bg-dark bg-opacity-75 px-3 py-2">
                                    <i class="fas fa-images me-1"></i>
                                    <span id="currentImageNumber">1</span> / <?= $total_images ?>
                                </span>
                                <?php endif; ?>
                                
                                <button class="btn btn-dark btn-sm rounded-circle bg-opacity-75" 
                                        onclick="openLightbox(0)" 
                                        style="width: 40px; height: 40px;"
                                        title="View full image">
                                    <i class="fas fa-search-plus"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Thumbnail Navigation -->
                        <?php if ($total_images > 1): ?>
                        <div class="thumbnail-container">
                            <div class="d-flex gap-2 overflow-auto pb-2" id="thumbnailGrid">
                                <?php foreach ($all_images as $index => $image): ?>
                                <div class="thumbnail-item flex-shrink-0">
                                    <img src="<?= htmlspecialchars($image['path']) ?>" 
                                        class="rounded border thumbnail-img <?= $index === 0 ? 'active' : '' ?>" 
                                        style="width: 100px; height: 100px; object-fit: cover; cursor: pointer; transition: all 0.3s;"
                                        alt="Thumbnail <?= $index + 1 ?>"
                                        data-index="<?= $index ?>"
                                        onclick="changeMainImage(<?= $index ?>)">
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Lightbox Modal -->
                    <div class="modal fade" id="imageLightbox" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-fullscreen">
                            <div class="modal-content bg-dark">
                                <div class="modal-header border-0 position-absolute w-100 top-0 start-0 z-3" style="background: linear-gradient(to bottom, rgba(0,0,0,0.8), transparent);">
                                    <div class="container">
                                        <div class="d-flex justify-content-between align-items-center w-100">
                                            <h5 class="modal-title text-white">
                                                <?= htmlspecialchars($item['title']) ?>
                                            </h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-body p-0 d-flex align-items-center justify-content-center">
                                    <div class="position-relative w-100 h-100 d-flex align-items-center justify-content-center">
                                        <img id="lightboxImage" 
                                            src="" 
                                            class="img-fluid" 
                                            style="max-height: 90vh; max-width: 90%; object-fit: contain;"
                                            alt="<?= htmlspecialchars($item['title']) ?>">
                                        
                                        <?php if ($total_images > 1): ?>
                                        <!-- Previous Button -->
                                        <button class="btn btn-light rounded-circle position-absolute start-0 ms-3" 
                                                style="width: 50px; height: 50px; top: 50%; transform: translateY(-50%);"
                                                onclick="navigateLightbox(-1)">
                                            <i class="fas fa-chevron-left"></i>
                                        </button>
                                        
                                        <!-- Next Button -->
                                        <button class="btn btn-light rounded-circle position-absolute end-0 me-3" 
                                                style="width: 50px; height: 50px; top: 50%; transform: translateY(-50%);"
                                                onclick="navigateLightbox(1)">
                                            <i class="fas fa-chevron-right"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="modal-footer border-0 position-absolute w-100 bottom-0 start-0 z-3 justify-content-center" style="background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);">
                                    <span class="text-white">
                                        <span id="lightboxImageNumber">1</span> / <?= $total_images ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <style>
                    /* Thumbnail Styles */
                    .thumbnail-img {
                        border: 3px solid transparent;
                        opacity: 0.7;
                    }

                    .thumbnail-img:hover {
                        opacity: 1;
                        border-color: #dee2e6;
                    }

                    .thumbnail-img.active {
                        border-color: #0d6efd !important;
                        opacity: 1;
                    }

                    /* Smooth scrollbar for thumbnails */
                    .thumbnail-container::-webkit-scrollbar {
                        height: 6px;
                    }

                    .thumbnail-container::-webkit-scrollbar-track {
                        background: #f1f1f1;
                        border-radius: 10px;
                    }

                    .thumbnail-container::-webkit-scrollbar-thumb {
                        background: #888;
                        border-radius: 10px;
                    }

                    .thumbnail-container::-webkit-scrollbar-thumb:hover {
                        background: #555;
                    }

                    /* Main image container */
                    .main-image-container {
                        position: relative;
                        overflow: hidden;
                    }

                    .main-image-container img {
                        transition: transform 0.3s ease;
                    }

                    .main-image-container:hover img {
                        transform: scale(1.05);
                    }

                    </style>

                    <script>
                    // Store images data
                    const itemImages = <?= json_encode(array_column($all_images, 'path')) ?>;
                    let currentImageIndex = 0;
                    let lightboxIndex = 0;

                    // Change main image when thumbnail clicked
                    function changeMainImage(index) {
                        currentImageIndex = index;
                        
                        // Update main image
                        document.getElementById('mainImage').src = itemImages[index];
                        
                        // Update counter
                        const counter = document.getElementById('currentImageNumber');
                        if (counter) {
                            counter.textContent = index + 1;
                        }
                        
                        // Update thumbnail active state
                        document.querySelectorAll('.thumbnail-img').forEach((thumb, i) => {
                            if (i === index) {
                                thumb.classList.add('active');
                            } else {
                                thumb.classList.remove('active');
                            }
                        });
                        
                        // Scroll thumbnail into view
                        const activeThumbnail = document.querySelector(`.thumbnail-img[data-index="${index}"]`);
                        if (activeThumbnail) {
                            activeThumbnail.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
                        }
                    }

                    // Open lightbox
                    function openLightbox(index) {
                        lightboxIndex = index;
                        document.getElementById('lightboxImage').src = itemImages[index];
                        document.getElementById('lightboxImageNumber').textContent = index + 1;
                        
                        const lightbox = new bootstrap.Modal(document.getElementById('imageLightbox'));
                        lightbox.show();
                    }

                    // Navigate in lightbox
                    function navigateLightbox(direction) {
                        lightboxIndex += direction;
                        
                        // Loop around
                        if (lightboxIndex < 0) {
                            lightboxIndex = itemImages.length - 1;
                        } else if (lightboxIndex >= itemImages.length) {
                            lightboxIndex = 0;
                        }
                        
                        document.getElementById('lightboxImage').src = itemImages[lightboxIndex];
                        document.getElementById('lightboxImageNumber').textContent = lightboxIndex + 1;
                    }

                    // Keyboard navigation in lightbox
                    document.addEventListener('keydown', function(e) {
                        const lightbox = document.getElementById('imageLightbox');
                        if (lightbox.classList.contains('show')) {
                            if (e.key === 'ArrowLeft') {
                                navigateLightbox(-1);
                            } else if (e.key === 'ArrowRight') {
                                navigateLightbox(1);
                            } else if (e.key === 'Escape') {
                                bootstrap.Modal.getInstance(lightbox).hide();
                            }
                        }
                    });
                    </script>
                    <!-- end image gallery -->
                    
                    <!-- start item info -->
                    <div class="border-0 card rounded-4">
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <span class="badge bg-primary mb-2"><?= htmlspecialchars($item['category_name']) ?></span>
                                    <h1 class="h3 mb-2"><?= htmlspecialchars($item['title']) ?></h1>
                                    <div class="d-flex align-items-center gap-3">
                                            <div class="d-flex align-items-center">
                                                <div class="d-flex align-items-center me-2">
                                                    <?php
                                                    // Display stars based on item average rating
                                                    for ($i = 1; $i <= 5; $i++):
                                                        $filled = $i <= round($item_average_rating);
                                                    ?>
                                                        <i class="fas fa-star <?= $filled ? 'text-warning' : 'text-muted' ?>"></i>
                                                    <?php endfor; ?>
                                                </div>
                                                <span class="text-muted">
                                                    (<?= number_format($item_average_rating, 1) ?> • <?= $item_total_ratings ?> <?= $item_total_ratings === 1 ? 'Review' : 'Reviews' ?>)
                                                </span>
                                            </div>
                                        <span class="badge <?= $item['availability_status'] === 'available' ? 'bg-success' : 'bg-danger' ?>">
                                            <?= ucfirst($item['availability_status']) ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="text-end">
                                    <div class="fs-3 fw-bold text-primary">&#8358;<?= number_format($item['price_per_day'], 2) ?></div>
                                    <div class="text-muted">per day</div>
                                </div>
                            </div>
                            
                            <p class="text-muted mb-4">
                                <i class="fas fa-map-marker-alt me-2"></i>
                                <?= htmlspecialchars($item['location'] ?? $item['city'] . ', ' . $item['state']) ?>
                            </p>
                            
                            <!-- start description -->
                            <div class="mb-4">
                                <h5>Description</h5>
                                <p class="mb-0"><?= nl2br(htmlspecialchars($item['description'])) ?></p>
                            </div>
                            <!-- end description -->
                            
                            <!-- start features -->
                            <?php if (!empty($item['features'])): ?>
                                <div class="mb-4">
                                    <h5>Features</h5>
                                    <p class="mb-0"><?= nl2br(htmlspecialchars($item['features']) ?? '') ?></p>
                                </div>
                            <?php endif; ?>
                            <!-- end features -->
                            
                            <!-- start condition and quantity -->
                            <div class="row g-4 mb-4">
                                <div class="col-md-6">
                                    <h6>Condition</h6>
                                    <span class="badge bg-light text-dark"><?= ucfirst($item['condition_status']) ?></span>
                                </div>
                                <?php
                                    // Calculate REAL-TIME availability for TODAY
                                    $today = date('Y-m-d');

                                    $bookedTodaySql = "SELECT COALESCE(SUM(o.quantity), 0) as booked_today
                                                    FROM orders o
                                                    WHERE o.item_id = ?
                                                    AND o.status NOT IN ('cancelled', 'completed')
                                                    AND o.payment_status = 'paid'
                                                    AND ? BETWEEN o.start_date AND o.end_date";

                                    $bookedResult = $db->fetch($bookedTodaySql, [$item['id'], $today]);
                                    $bookedToday = $bookedResult['booked_today'];

                                    $totalQuantity = $item['quantity'];
                                    $availableToday = $totalQuantity - $bookedToday;
                                ?>

                                <div class="col-md-6 mb-3">
                                    <h6>Available Quantity (Today)</h6>
                                    <div>
                                        <?php if ($availableToday <= 0): ?>
                                            <span class="badge bg-danger fs-6">Fully Booked Today</span>
                                            <p class="text-muted small mb-0 mt-1"><b>Check future dates</b></p>
                                        <?php else: ?>
                                            <strong class="fs-5 text-success"><?= $availableToday ?></strong>
                                            <span class="text-muted">of <?= $totalQuantity ?> Available</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <!-- end condition and quantity -->
                        </div>
                    </div>
                    <!-- end item info -->

                    <br>
                    
                    <!-- start reviews section -->
                    <!-- Customer Reviews Section -->
                    <?php if (!empty($item_ratings_list)): ?>
                    <div class="card border-0 rounded-4 mb-4">
                        <div class="card-header bg-white border-0 pt-4 px-4">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="mb-1">
                                        <i class="fas fa-star text-warning me-2"></i>Customer Reviews
                                    </h5>
                                    <p class="text-muted mb-0 small">
                                        Based on <?= $item_total_ratings ?> verified rental<?= $item_total_ratings === 1 ? '' : 's' ?>
                                    </p>
                                </div>
                                <div class="text-end">
                                    <div class="h3 mb-0 text-warning"><?= number_format($item_average_rating, 1) ?></div>
                                    <div class="d-flex align-items-center">
                                        <?php
                                        for ($i = 1; $i <= 5; $i++):
                                            $filled = $i <= round($item_average_rating);
                                        ?>
                                            <i class="fas fa-star <?= $filled ? 'text-warning' : 'text-muted' ?>" style="font-size: 0.9rem;"></i>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-body p-4">
                            <?php foreach ($item_ratings_list as $index => $rating): ?>
                            <div class="review-item <?= $index < count($item_ratings_list) - 1 ? 'pb-4 mb-4 border-bottom' : '' ?>">
                                <div class="d-flex align-items-start">
                                    <!-- Customer Avatar -->
                                    <div class="flex-shrink-0">
                                        <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" 
                                            style="width: 45px; height: 45px;">
                                            <i class="fas fa-user"></i>
                                        </div>
                                    </div>
                                    
                                    <!-- Review Content -->
                                    <div class="flex-grow-1 ms-3">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div>
                                                <h6 class="mb-1"><?= htmlspecialchars($rating['customer_name']) ?></h6>
                                                <div class="d-flex align-items-center mb-1">
                                                    <?php
                                                    for ($i = 1; $i <= 5; $i++):
                                                        $filled = $i <= $rating['item_rating'];
                                                    ?>
                                                        <i class="fas fa-star <?= $filled ? 'text-warning' : 'text-muted' ?>" style="font-size: 0.85rem;"></i>
                                                    <?php endfor; ?>
                                                </div>
                                            </div>
                                            <small class="text-muted">
                                                <?= date('M d, Y', strtotime($rating['created_at'])) ?>
                                            </small>
                                        </div>
                                        
                                        <?php if (!empty($rating['item_review'])): ?>
                                        <p class="mb-0 text-muted">
                                            <i class="fas fa-quote-left me-1 text-primary opacity-50"></i>
                                            <?= htmlspecialchars($rating['item_review']) ?>
                                            <i class="fas fa-quote-right ms-1 text-primary opacity-50"></i>
                                        </p>
                                        <?php endif; ?>
                                        
                                        <small class="text-muted d-block mt-2">
                                            <i class="fas fa-check-circle text-success me-1"></i>
                                            Verified Rental
                                        </small>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php elseif ($item_total_ratings === 0): ?>
                    <!-- No Reviews Yet -->
                    <div class="card border-0 rounded-4 mb-4">
                        <div class="card-body p-5 text-center">
                            <i class="fas fa-star-half-alt fa-3x text-muted mb-3"></i>
                            <h5 class="mb-2">No Reviews Yet</h5>
                            <p class="text-muted mb-0">Be the first to rent and review this item!</p>
                        </div>
                    </div>
                    <?php endif; ?>

                    <style>
                    /* Review hover effect */
                    .review-item {
                        transition: background-color 0.2s ease;
                    }

                    .review-item:hover {
                        background-color: #f8f9fa;
                        border-radius: 8px;
                        padding-left: 1rem !important;
                        padding-right: 1rem !important;
                    }
                    </style>
                    <!-- end reviews section -->
                </div>
                <!-- end item images and basic info -->
                
                <!-- start booking sidebar -->
                <div class="col-lg-4">
                    <div class="sticky-top" style="top: 100px;">
                        <!-- start vendor info card -->
                        <div class="border-0 card rounded-4 mb-4">
                            <div class="card-body p-4">
                                <h5 class="mb-3">Vendor Information</h5>
                                <div class="d-flex align-items-center mb-3">
                                    <?php if (!empty($item['vendor_logo'])): ?>
                                        <img src="<?= htmlspecialchars($item['vendor_logo']) ?>" alt="Vendor Logo" class="rounded-circle me-3" style="width: 60px; height: 60px; object-fit: cover;">
                                    <?php else: ?>
                                        <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px;">
                                            <i class="fas fa-building fs-4 text-primary"></i>
                                        </div>
                                    <?php endif; ?>
                                    <div>
                                        <h6 class="mb-0"><?= htmlspecialchars($item['vendor_name']) ?></h6>
                                        <small class="text-muted"><?= htmlspecialchars($item['vendor_city'] . ', ' . $item['vendor_state']) ?></small>
                                    </div>

                                    </div>
                                    
                                    <?php if ($vendor_total_ratings > 0): ?>
                                    <div class="mt-3 pt-3 border-top">
                                    <div class="d-flex align-items-center">
                                        <div class="d-flex align-items-center me-2">
                                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                                <i class="fas fa-star <?= $i <= round($vendor_average_rating) ? 'text-warning' : 'text-muted' ?>" style="font-size: 0.85rem;"></i>
                                            <?php endfor; ?>
                                        </div>
                                        <small class="text-muted">
                                            (<?= number_format($vendor_average_rating, 1) ?> • <?= $vendor_total_ratings ?> Ratings)
                                        </small>
                                    </div>

                                    <?php endif; ?>
                                </div>
                                
                                <?php /* if (!empty($item['vendor_phone'])): ?>
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="fas fa-phone text-muted me-3"></i>
                                        <span><?= htmlspecialchars($item['vendor_phone']) ?></span>
                                    </div>
                                <?php endif; */ ?>
                                
                                <!-- <a href="#" class="btn btn-outline-primary w-100">Contact Vendor</a> -->
                            </div>
                        </div>
                        <!-- end vendor info card -->

                        <!-- Booking Calendar Section -->
                        <div class="card mb-4">
                            <div class="card-header bg-primary text-white" style="margin: 0; padding:10px; width:100%">
                                <h5 class="mb-0"><i class="fas fa-calendar-alt me-2"></i>Booking Calendar</h5>
                            </div>
                            <div class="card-body">
                                <div id="bookingCalendarMessage" class="alert alert-info mb-3" style="display: none;">
                                    <i class="fas fa-info-circle me-2"></i><span id="calendarMessageText"></span>
                                </div>
                                
                                <div id="bookingsTable" class="mb-3">
                                    <p class="text-muted">Loading booking information...</p>
                                </div>
                            </div>
                        </div>


                        
                        <!-- start booking form -->
                        <div class="border-0 card rounded-4 sticky-top">
                            <div class="card-header bg-primary text-white" style="margin: 0; padding:10px; width:100%">
                                <h5 class="mb-0"><i class="fas fa-edit me-2"></i>Book This Item</h5>
                            </div>
                            <div class="card-body p-4">
                                
                                <form id="bookingForm" method="POST" action="process-booking.php">
                                    <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                                    <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                                    
                                    <!-- Start Date -->
                                    <div class="mb-3">
                                        <label class="form-label">Start Date <span class="text-danger">*</span></label>
                                        <input type="date" 
                                            name="start_date" 
                                            id="startDate" 
                                            class="form-control" 
                                            min="<?= date('Y-m-d') ?>" 
                                            required>
                                        <div class="invalid-feedback">Please select a valid start date</div>
                                    </div>
                                    
                                    <!-- End Date -->
                                    <div class="mb-3">
                                        <label class="form-label">End Date <span class="text-danger">*</span></label>
                                        <input type="date" 
                                            name="end_date" 
                                            id="endDate" 
                                            class="form-control" 
                                            min="<?= date('Y-m-d') ?>" 
                                            required>
                                        <div class="invalid-feedback">End date must be on or after start date</div>
                                    </div>
                                    
                                    <!-- Quantity -->
                                    <div class="mb-3">
                                        <label class="form-label">Quantity <span class="text-danger">*</span></label>
                                        <select name="quantity" id="quantity" class="form-select" required>
                                            <?php for ($i = 1; $i <= min($item['available_quantity'], 10); $i++): ?>
                                                <option value="<?= $i ?>"><?= $i ?> <?= $i === 1 ? 'item' : 'items' ?></option>
                                            <?php endfor; ?>
                                        </select>
                                        <small class="text-muted"><?= $item['available_quantity'] ?> available</small>
                                    </div>
                                    
                                    <!-- Price Breakdown -->
                                    <div class="bg-light rounded-3 p-3 mb-3">
                                        <h6 class="mb-3">Price Breakdown</h6>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted">Daily Rate:</span>
                                            <span class="fw-semibold">₦<?= number_format($item['price_per_day'], 2) ?></span>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted">Number of Days:</span>
                                            <span class="fw-semibold" id="numberOfDays">0</span>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted">Quantity:</span>
                                            <span class="fw-semibold" id="selectedQuantity">1</span>
                                        </div>
                                        
                                        <hr>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="fw-bold">Subtotal:</span>
                                            <span class="fw-bold text-primary" id="subtotalAmount">₦0.00</span>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted">Security Deposit:</span>
                                            <span class="text-muted" id="totalSecurityDeposit">₦0.00</span>
                                        </div>
                                        
                                        <small class="text-muted d-block mb-2">
                                            (₦<?= number_format($item['security_deposit'], 2) ?> per item - Refundable)
                                        </small>
                                        
                                        <hr class="my-2">
                                        
                                        <div class="d-flex justify-content-between">
                                            <span class="fs-5 fw-bold">Total Amount:</span>
                                            <span class="fs-5 fw-bold text-success" id="grandTotal">₦0.00</span>
                                        </div>
                                    </div>
                                    
                                    <!-- Calculation Formula Display -->
                                    <div class="alert alert-info small mb-3" id="calculationFormula" style="display: none;">
                                        <strong>Calculation:</strong><br>
                                        <span id="formulaText"></span>
                                    </div>
                                    
                                    <!-- Error Messages -->
                                    <div class="alert alert-danger" id="availabilityError" style="display: none;">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        <span id="availabilityMessage"></span>
                                    </div>
                                    
                                    <small class="text-muted d-block text-center">
                                        <i class="fas fa-shield-alt"></i> Secure payment with Paystack/Flutterwave
                                    </small>
                                    
                                    <!-- Book Now Button -->
                                    <?php if (Auth::check() && Auth::userType() === 'customer'): ?>

                                        <?php if ($has_pending_updates): ?>
                                            <!-- Item temporarily unavailable -->
                                            <button type="button"
                                                    class="btn btn-secondary btn-lg w-100 mb-2"
                                                    disabled
                                                    data-bs-toggle="tooltip"
                                                    title="Temporarily unavailable due to pending updates">
                                                <i class="fas fa-clock me-2"></i>Temporarily Unavailable
                                            </button>

                                        <?php elseif (!$customer_is_kyc_verified): ?>
                                            <!-- Not KYC verified — disabled Book Now + Dojah web button -->
                                            <button type="button"
                                                    class="btn btn-secondary btn-lg w-100 mb-2"
                                                    disabled>
                                                <i class="fas fa-calendar-check me-2"></i>Book Now
                                            </button>

                                            <?php if ($kyc_widget_id): ?>
                                            <script defer src="https://widget.dojah.io/websdk.js"></script>
                                            <dojah-button
                                                widgetId="<?= htmlspecialchars($kyc_widget_id) ?>"
                                                text="Verify Your Identity to Book"
                                                textColor="#FFFFFF"
                                                backgroundColor="#f0a500"
                                                style="width:100%;display:block;">
                                            </dojah-button>
                                            <?php else: ?>
                                            <a href="customer/profile.php#kycSection"
                                               class="btn btn-warning btn-lg w-100 mb-2">
                                                <i class="fas fa-shield-alt me-2"></i>Verify Your Identity to Book
                                            </a>
                                            <?php endif; ?>

                                            <p class="text-muted text-center mt-1" style="font-size:12px;">
                                                <i class="fas fa-info-circle"></i>
                                                One-time identity verification required before booking.
                                            </p>

                                        <?php else: ?>
                                            <!-- Verified — normal Book Now -->
                                            <button type="submit"
                                                    id="bookNowBtn"
                                                    class="btn btn-primary btn-lg w-100 mb-2"
                                                    disabled>
                                                <i class="fas fa-calendar-check me-2"></i>Book Now
                                            </button>
                                        <?php endif; ?>

                                    <?php else: ?>
                                        <a href="auth/login.php" class="btn btn-primary btn-lg w-100 mb-2">
                                            <i class="fas fa-sign-in-alt me-2"></i>Login to Book
                                        </a>
                                    <?php endif; ?>

                                    <?php if (Auth::check() && Auth::userType() === 'customer'): 
                                        $customerModel = new Customer();
                                        $customer = $customerModel->findByUserId(Auth::user()['id']);
                                        $is_favorited = $customer ? $customerModel->hasItemInFavorites($customer['id'], $item_id) : false;
                                    ?>
                                    <button type="button" 
                                            class="btn btn-outline-primary w-100 mt-2" 
                                            id="favoriteBtn"
                                            data-item-id="<?= $item_id ?>"
                                            data-favorited="<?= $is_favorited ? 'true' : 'false' ?>">
                                        <i class="<?= $is_favorited ? 'fas' : 'far' ?> fa-heart me-2"></i>
                                        <span id="favoriteBtnText"><?= $is_favorited ? 'Remove from Favorites' : 'Save to Favorites' ?></span>
                                    </button>
                                    <?php endif; ?>
                                </form>
                                
                            </div>
                        </div>
                        <!-- end booking form -->
                    </div>
                </div>
                <!-- end booking sidebar -->
            </div>
        </div>
    </div>
    <!-- end item details -->
    
    <!-- start related items -->
    <?php if (!empty($related_items)): ?>
        <div class="py-5 bg-light">
            <div class="container">
                <div class="text-center mb-5">
                    <h4 class="mb-3">Related Items</h4>
                    <p class="text-muted">You might also be interested in these items</p>
                </div>
                
                <div class="row g-4">
                    <?php foreach ($related_items as $related_item): ?>
                        <div class="col-lg-3 col-md-4 col-sm-6">
                            <div class="border-0 card card-hover h-100 rounded-4 overflow-hidden">
                                <a href="item-details.php?id=<?= $related_item['id'] ?>" class="stretched-link"></a>
                                <div class="position-relative">
                                    <img src="<?= htmlspecialchars($related_item['main_image'] ?? 'assets/images/default-item.jpg') ?>" alt="<?= htmlspecialchars($related_item['title']) ?>" class="card-img-top h-200 object-fit-cover">
                                    <div class="position-absolute top-0 start-0 m-3">
                                        <span class="badge bg-primary"><?= htmlspecialchars($related_item['category_name']) ?></span>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div class="d-flex align-items-center">
                                                <div class="d-flex align-items-center me-2">
                                                    <?php
                                                    // Display stars based on item average rating
                                                    for ($i = 1; $i <= 5; $i++):
                                                        $filled = $i <= round($item_average_rating);
                                                    ?>
                                                        <i class="fas fa-star <?= $filled ? 'text-warning' : 'text-muted' ?>"></i>
                                                    <?php endfor; ?>
                                                </div>
                                                <span class="text-muted">
                                                    (<?= number_format($item_average_rating, 1) ?> • <?= $item_total_ratings ?> <?= $item_total_ratings === 1 ? 'review' : 'reviews' ?>)
                                                </span>
                                            </div>
                                        <span class="badge bg-success">Available</span>
                                        </div>
                                    <h5 class="fw-semibold mb-2"><?= htmlspecialchars($related_item['title']) ?></h5>
                                    <p class="text-muted small mb-2">
                                        <i class="fas fa-map-marker-alt me-1"></i>
                                        <?= htmlspecialchars($related_item['city'] . ', ' . $related_item['state']) ?>
                                    </p>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="fs-5 fw-bold text-primary">&#8358;<?= number_format($related_item['price_per_day'], 2) ?></span>
                                            <span class="text-muted small">/day</span>
                                        </div>
                                        <small class="text-muted">by <?= htmlspecialchars($related_item['vendor_name']) ?></small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>
    <!-- end related items -->

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const startDateInput = document.getElementById('startDate');
        const endDateInput = document.getElementById('endDate');
        const quantitySelect = document.getElementById('quantity');
        const bookingForm = document.getElementById('bookingForm');
        const bookNowBtn = document.getElementById('bookNowBtn');
        
        // Item data from PHP
        const itemData = {
            id: <?= $item['id'] ?>,
            dailyRate: <?= $item['price_per_day'] ?>,
            securityDeposit: <?= $item['security_deposit'] ?>,
            availableQuantity: <?= $item['available_quantity'] ?>
        };
        
        // Calculate and update prices
        function calculatePrices() {
            const startDate = startDateInput.value;
            const endDate = endDateInput.value;
            const quantity = parseInt(quantitySelect.value) || 1;
            
            // Validate dates first
            if (!startDate || !endDate) {
                resetCalculations();
                return;
            }
            
            // Calculate number of days (inclusive of start date)
            const start = new Date(startDate);
            const end = new Date(endDate);
            const timeDiff = end.getTime() - start.getTime();
            const numberOfDays = Math.floor(timeDiff / (1000 * 3600 * 24)) + 1; // +1 to include start date
            
            if (numberOfDays < 1) {
                resetCalculations();
                return;
            }
            
            // Calculate amounts
            const subtotal = quantity * numberOfDays * itemData.dailyRate;
            const totalDeposit = quantity * itemData.securityDeposit;
            const grandTotal = subtotal + totalDeposit;
            
            // Update display
            document.getElementById('numberOfDays').textContent = numberOfDays;
            document.getElementById('selectedQuantity').textContent = quantity;
            document.getElementById('subtotalAmount').textContent = '₦' + subtotal.toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            document.getElementById('totalSecurityDeposit').textContent = '₦' + totalDeposit.toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            document.getElementById('grandTotal').textContent = '₦' + grandTotal.toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            
            // Show calculation formula
            const formulaDiv = document.getElementById('calculationFormula');
            const formulaText = document.getElementById('formulaText');
            formulaText.innerHTML = `
                Subtotal: ${quantity} items × ${numberOfDays} days × ₦${itemData.dailyRate.toLocaleString()} = ₦${subtotal.toLocaleString()}<br>
                Security: ${quantity} items × ₦${itemData.securityDeposit.toLocaleString()} = ₦${totalDeposit.toLocaleString()}<br>
                <strong>Total: ₦${grandTotal.toLocaleString()}</strong>
            `;
            formulaDiv.style.display = 'block';
            
            // Enable book button if all valid
            if (validateDates() && numberOfDays > 0) {
                bookNowBtn.disabled = false;
            } else {
                bookNowBtn.disabled = true;
            }
        }
        
        function resetCalculations() {
            document.getElementById('numberOfDays').textContent = '0';
            document.getElementById('selectedQuantity').textContent = '1';
            document.getElementById('subtotalAmount').textContent = '₦0.00';
            document.getElementById('totalSecurityDeposit').textContent = '₦0.00';
            document.getElementById('grandTotal').textContent = '₦0.00';
            document.getElementById('calculationFormula').style.display = 'none';
            bookNowBtn.disabled = true;
        }
        
        // Validate dates
        function validateDates() {
            const startDate = startDateInput.value;
            const endDate = endDateInput.value;
            
            if (!startDate || !endDate) {
                return false;
            }
            
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const start = new Date(startDate);
            const end = new Date(endDate);
            
            // Check if start date is in the past
            if (start < today) {
                startDateInput.classList.add('is-invalid');
                startDateInput.setCustomValidity('Start date cannot be in the past');
                return false;
            } else {
                startDateInput.classList.remove('is-invalid');
                startDateInput.setCustomValidity('');
            }
            
            // Check if end date is before start date
            if (end < start) {
                endDateInput.classList.add('is-invalid');
                endDateInput.setCustomValidity('End date must be on or after start date');
                return false;
            } else {
                endDateInput.classList.remove('is-invalid');
                endDateInput.setCustomValidity('');
            }
            
            return true;
        }
        
        // Update end date minimum when start date changes
        startDateInput.addEventListener('change', function() {
            endDateInput.min = this.value || '<?= date('Y-m-d') ?>';
            validateDates();
            calculatePrices();
        });
        
        // Recalculate when any input changes
        endDateInput.addEventListener('change', function() {
            validateDates();
            calculatePrices();
        });
        
        quantitySelect.addEventListener('change', calculatePrices);
        
        // Form submission - Check availability
        bookingForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            if (!validateDates()) {
                alert('Please select valid dates');
                return;
            }
            
            const formData = new FormData(this);
            const startDate = formData.get('start_date');
            const endDate = formData.get('end_date');
            const quantity = formData.get('quantity');
            
            // Disable button and show loading
            bookNowBtn.disabled = true;
            bookNowBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Checking availability...';
            
            try {
                // Check availability via AJAX
                const response = await fetch('check-availability.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        item_id: itemData.id,
                        start_date: startDate,
                        end_date: endDate,
                        quantity: quantity
                    })
                });
                
                const result = await response.json();
                
                if (result.available) {
                    // Item is available, proceed with payment modal
                    document.getElementById('availabilityError').style.display = 'none';
                    
                    // Submit form to process booking (which will show payment modal)
                    this.submit();
                } else {
                    // Show availability error
                    const errorDiv = document.getElementById('availabilityError');
                    const errorMsg = document.getElementById('availabilityMessage');
                    
                    errorMsg.innerHTML = `<strong>Not enough items available!</strong><br>${result.message}`;
                    errorDiv.style.display = 'block';
                    
                    // Scroll to error
                    errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    
                    // Re-enable button
                    bookNowBtn.disabled = false;
                    bookNowBtn.innerHTML = '<i class="fas fa-calendar-check me-2"></i>Book Now';
                }
            } catch (error) {
                console.error('Error checking availability:', error);
                alert('Error checking availability. Please try again.');
                
                // Re-enable button
                bookNowBtn.disabled = false;
                bookNowBtn.innerHTML = '<i class="fas fa-calendar-check me-2"></i>Book Now';
            }
        });
        
        // Initial calculation
        calculatePrices();
    });
    </script>

    <!-- ADD/UPDATE this JavaScript at the bottom before </body> -->
    <script>
    // Load booked dates when page loads
    document.addEventListener('DOMContentLoaded', function() {
        loadBookingCalendar();
    });

    function loadBookingCalendar() {
        fetch('ajax/get-booked-dates.php?item_id=<?= $item['id'] ?>')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayBookingRanges(data);
                } else {
                    document.getElementById('bookingsTable').innerHTML = 
                        '<p class="text-danger">Error loading booking information</p>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('bookingsTable').innerHTML = 
                    '<p class="text-danger">Error loading booking information</p>';
            });
    }

    function displayBookingRanges(data) {
        const container = document.getElementById('bookingsTable');
        const messageDiv = document.getElementById('bookingCalendarMessage');
        const messageText = document.getElementById('calendarMessageText');
        
        if (!data.has_bookings) {
            messageDiv.className = 'alert alert-success mb-3';
            messageDiv.style.display = 'block';
            messageText.textContent = `All ${data.total_quantity} units available for booking on all dates`;
            container.innerHTML = '<p class="text-muted small mb-0">No current or future bookings</p>';
            return;
        }
        
        // Show message
        // messageDiv.className = 'alert alert-info mb-3';
        // messageDiv.style.display = 'block';
        // messageText.textContent = `This item has ${data.total_quantity} total units. See booked periods below:`;
        
        // Build table
        let html = '<div class="table-responsive">';
        html += '<table class="table table-bordered table-hover">';
        html += '<thead class="table-light">';
        html += '<tr>';
        html += '<th>Booking Period</th>';
        html += '<th>Units</th>';
        // html += '<th>Available Units</th>';
        // html += '<th>Status</th>';
        html += '</tr>';
        html += '</thead>';
        html += '<tbody>';
        
        data.bookings.forEach(booking => {
            const startDate = formatDate(booking.start_date);
            const endDate = formatDate(booking.end_date);
            
            let statusBadge = '';
            let statusClass = '';
            
            if (booking.available_quantity === 0) {
                statusBadge = '<span class="badge bg-danger">Fully Booked</span>';
                statusClass = 'table-danger';
            } else if (booking.available_quantity < data.total_quantity) {
                statusBadge = '<span class="badge bg-warning text-dark">Partially Booked</span>';
                statusClass = 'table-warning';
            } else {
                statusBadge = '<span class="badge bg-success">Available</span>';
            }
            
            html += `<tr class="${statusClass}">`;
            html += `<td>${startDate} - ${endDate}</td>`;
            html += `<td>${booking.booked_quantity} unit${booking.booked_quantity > 1 ? 's' : ''}</td>`;
            // html += `<td>${booking.available_quantity} unit${booking.available_quantity !== 1 ? 's' : ''}</td>`;
            // html += `<td>${statusBadge}</td>`;
            html += `</tr>`;
        });
        
        html += '</tbody></table></div>';
        
        html += '<div class="alert alert-info mt-3 mb-0">';
        html += '<i class="fas fa-lightbulb me-2"></i>';
        html += '<strong>Tip:</strong> You can still book this item for dates not listed above or for available units during partially booked periods.';
        html += '</div>';
        
        container.innerHTML = html;
    }

    function formatDate(dateString) {
        const date = new Date(dateString + 'T00:00:00');
        const options = { day: 'numeric', month: 'short', year: 'numeric' };
        return date.toLocaleDateString('en-US', options);
    }

    // Update calculateTotal to check availability in real-time
    const startDateInput = document.getElementById('start_date');
    const endDateInput = document.getElementById('end_date');
    const quantityInput = document.getElementById('quantity');

    if (startDateInput && endDateInput && quantityInput) {
        [startDateInput, endDateInput, quantityInput].forEach(input => {
            input.addEventListener('change', function() {
                const startDate = startDateInput.value;
                const endDate = endDateInput.value;
                const quantity = parseInt(quantityInput.value) || 1;
                
                if (startDate && endDate) {
                    checkAvailabilityForDates(startDate, endDate, quantity);
                }
            });
        });
    }

    function checkAvailabilityForDates(startDate, endDate, quantity) {
        const formData = new FormData();
        formData.append('item_id', <?= $item['id'] ?>);
        formData.append('start_date', startDate);
        formData.append('end_date', endDate);
        formData.append('quantity', quantity);
        
        fetch('ajax/check-item-availability.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            showAvailabilityMessage(data);
        })
        .catch(error => {
            console.error('Error checking availability:', error);
        });
    }

    function showAvailabilityMessage(data) {
        // Remove old message if exists
        const oldMessage = document.getElementById('availabilityAlert');
        if (oldMessage) {
            oldMessage.remove();
        }
        
        // Create new message
        const alertDiv = document.createElement('div');
        alertDiv.id = 'availabilityAlert';
        alertDiv.className = data.available ? 'alert alert-success' : 'alert alert-danger';
        alertDiv.innerHTML = `
            <i class="fas fa-${data.available ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
            ${data.message}
        `;
        
        // Insert before submit button
        const form = document.querySelector('form[action="process-booking.php"]');
        const submitBtn = form.querySelector('button[type="submit"]');
        form.insertBefore(alertDiv, submitBtn);
        
        // Enable/disable submit button
        submitBtn.disabled = !data.available;
        
        if (!data.available) {
            submitBtn.classList.add('btn-secondary');
            submitBtn.classList.remove('btn-success');
        } else {
            submitBtn.classList.add('btn-success');
            submitBtn.classList.remove('btn-secondary');
        }
    }
    </script>


<script>
    // ================================================================
    // FAVORITE BUTTON FUNCTIONALITY
    // ================================================================
    const favoriteBtn = document.getElementById('favoriteBtn');
    
    if (favoriteBtn) {
        favoriteBtn.addEventListener('click', function() {
            const itemId = this.dataset.itemId;
            const button = this;
            const icon = button.querySelector('i');
            const text = document.getElementById('favoriteBtnText');
            
            // Disable button during request
            button.disabled = true;
            
            // Send AJAX request
            const formData = new FormData();
            formData.append('item_id', itemId);
            
            fetch('ajax/toggle-favourite.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update button state
                    if (data.is_favorited) {
                        // Item is now favorited
                        icon.classList.remove('far');
                        icon.classList.add('fas');
                        text.textContent = 'Remove from Favorites';
                        button.dataset.favorited = 'true';
                        
                        // Show success message
                        showNotification('success', data.message);
                    } else {
                        // Item is now unfavorited
                        icon.classList.remove('fas');
                        icon.classList.add('far');
                        text.textContent = 'Save to Favorites';
                        button.dataset.favorited = 'false';
                        
                        // Show success message
                        showNotification('info', data.message);
                    }
                } else {
                    // Show error message
                    showNotification('danger', data.message);
                }
                
                // Re-enable button
                button.disabled = false;
            })
            .catch(error => {
                console.error('Error toggling favorite:', error);
                showNotification('danger', 'An error occurred. Please try again.');
                button.disabled = false;
            });
        });
    }
    
    // Helper function to show notification
    function showNotification(type, message) {
        // Check if notification container exists
        let container = document.getElementById('notification-container');
        
        if (!container) {
            // Create notification container
            container = document.createElement('div');
            container.id = 'notification-container';
            container.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999; max-width: 350px;';
            document.body.appendChild(container);
        }
        
        // Create notification
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-dismissible fade show`;
        notification.role = 'alert';
        notification.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'danger' ? 'exclamation-circle' : 'info-circle'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
        
        // Add to container
        container.appendChild(notification);
        
        // Auto-remove after 3 seconds
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 150);
        }, 3000);
    }
</script>


<?php
// Include footer template
include __DIR__ . '/templates/layouts/frontend/footer.php';
?>