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

// Set page variables
$page_title = 'Browse Items';
$body_class = 'bg-light';


// Initialize models
$itemModel = new Item();
$categoryModel = new Category();
$ratingModel = new OrderRating();

// Get filter parameters
$search = $_GET['search'] ?? '';
$category = $_GET['category'] ?? '';
$location = $_GET['location'] ?? '';
$min_price = $_GET['min_price'] ?? '';
$max_price = $_GET['max_price'] ?? '';
$sort = $_GET['sort'] ?? 'newest';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = isset($_GET['per_page']) ? max(10, intval($_GET['per_page'])) : 15;

// Prepare filters for database query
$filters = [];
if (!empty($search)) $filters['search'] = $search;
if (!empty($category)) $filters['category'] = $category;
if (!empty($location)) $filters['location'] = $location;
if (!empty($min_price)) $filters['min_price'] = floatval($min_price);
if (!empty($max_price)) $filters['max_price'] = floatval($max_price);
$filters['sort'] = $sort;
$filters['page'] = $page;
$filters['per_page'] = $per_page;

try {
    // Get items with filters
    $items_data = $itemModel->getWithFilters($filters);
    $items = $items_data['items'];
    $total_items = $items_data['total'];
    $total_pages = ceil($total_items / $per_page);
    
    // Get categories for filter dropdown
    $categories = $categoryModel->getActive();
    
    // Get unique locations for filter dropdown
    $locations_sql = "SELECT DISTINCT city, state FROM items WHERE status = 'approved' AND approval_status = 'approved' ORDER BY city, state LIMIT 100";
    $locations = $db->fetchAll($locations_sql);
    
} catch (Exception $e) {
    $items = [];
    $total_items = 0;
    $total_pages = 0;
    $categories = [];
    $locations = [];
    error_log('Database error: ' . $e->getMessage());
}


// Get real ratings for all items
foreach ($items as &$item) {
    $itemRating = $ratingModel->getItemAverageRating($item['id']);
    $item['item_average_rating'] = $itemRating['average'];
    $item['item_total_ratings'] = $itemRating['count'];
}
unset($item); // CRITICAL: Unset reference to prevent bugs in subsequent loops

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


    <!-- start main content -->
    <div class="py-5">
        <div class="container">
            <div class="row">
                <!-- start sidebar filters -->
                <div class="col-lg-3">
                    <div class="card rounded-4 border-0 sticky-top" style="top: 100px;">
                        <div class="card-body p-4">
                            <h5 class="mb-4">Filters</h5>
                            <form id="filterForm" method="GET" action="items.php">
                                <!-- Search filter -->
                                <div class="mb-4">
                                    <label class="form-label">Search</label>
                                    <input type="text" name="search" class="form-control" placeholder="Search items..." value="<?= htmlspecialchars($search) ?>">
                                </div>
                                
                                <!-- Category filter -->
                                <div class="mb-4">
                                    <label class="form-label">Category</label>
                                    <select name="category" class="form-select">
                                        <option value="">All Categories</option>
                                        <?php foreach ($categories as $cat): ?>
                                            <option value="<?= htmlspecialchars($cat['slug']) ?>" <?= $category === $cat['slug'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($cat['name']) ?> (<?= $cat['total_items'] ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <!-- Location filter -->
                                <div class="mb-4">
                                    <label class="form-label">Location</label>
                                    <select name="location" class="form-select">
                                        <option value="">All Locations</option>
                                        <?php foreach ($locations as $loc): ?>
                                            <?php $location_str = $loc['city'] . ', ' . $loc['state']; ?>
                                            <option value="<?= htmlspecialchars($location_str) ?>" <?= $location === $location_str ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($location_str) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <!-- Price range filter -->
                                <div class="mb-4">
                                    <label class="form-label">Price Range (per day)</label>
                                    <div class="row g-2">
                                        <div class="col-6">
                                            <input type="number" name="min_price" class="form-control" placeholder="Min &#8358;" value="<?= htmlspecialchars($min_price) ?>">
                                        </div>
                                        <div class="col-6">
                                            <input type="number" name="max_price" class="form-control" placeholder="Max &#8358;" value="<?= htmlspecialchars($max_price) ?>">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Sort filter -->
                                <div class="mb-4">
                                    <label class="form-label">Sort By</label>
                                    <select name="sort" class="form-select">
                                        <option value="newest" <?= $sort === 'newest' ? 'selected' : '' ?>>Newest First</option>
                                        <option value="oldest" <?= $sort === 'oldest' ? 'selected' : '' ?>>Oldest First</option>
                                        <option value="price_low" <?= $sort === 'price_low' ? 'selected' : '' ?>>Price: Low to High</option>
                                        <option value="price_high" <?= $sort === 'price_high' ? 'selected' : '' ?>>Price: High to Low</option>
                                        <option value="rating" <?= $sort === 'rating' ? 'selected' : '' ?>>Highest Rated</option>
                                        <option value="popular" <?= $sort === 'popular' ? 'selected' : '' ?>>Most Popular</option>
                                    </select>
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                                    <a href="items.php" class="btn btn-outline-secondary">Clear All</a>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <!-- end sidebar filters -->
                
                <!-- start main content area -->
                <div class="col-lg-9">
                    <!-- start results header -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div>
                            <h4 class="mb-0"><?= number_format($total_items) ?> Items Found</h4>
                            <?php if (!empty($search) || !empty($category) || !empty($location)): ?>
                                <p class="text-muted small mb-0">
                                    <?php if (!empty($search)): ?>Search: "<?= htmlspecialchars($search) ?>"<?php endif; ?>
                                    <?php if (!empty($category)): ?> <?= !empty($search) ? '• ' : '' ?>Category: <?= htmlspecialchars($category) ?><?php endif; ?>
                                    <?php if (!empty($location)): ?> <?= (!empty($search) || !empty($category)) ? '• ' : '' ?>Location: <?= htmlspecialchars($location) ?><?php endif; ?>
                                </p>
                            <?php endif; ?>
                        </div>
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-primary d-lg-none" type="button" data-bs-toggle="offcanvas" data-bs-target="#filterSidebar" aria-controls="filterSidebar">
                                <i class="fas fa-filter me-2"></i>Filters
                            </button>
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                    View: <?= $per_page ?> per page
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="?<?= http_build_query(array_merge($_GET, ['per_page' => 15, 'page' => 1])) ?>">15 per page</a></li>
                                    <li><a class="dropdown-item" href="?<?= http_build_query(array_merge($_GET, ['per_page' => 30, 'page' => 1])) ?>">30 per page</a></li>
                                    <li><a class="dropdown-item" href="?<?= http_build_query(array_merge($_GET, ['per_page' => 45, 'page' => 1])) ?>">45 per page</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <!-- end results header -->
                    
                    <!-- start items grid -->
                    <?php if (!empty($items)): ?>
                        <div class="row g-4">
                            <?php foreach ($items as $item): ?>
                                <div class="col-md-6 col-lg-4">
                                    <!-- start item card -->
                                    <div class="border-0 card card-hover h-100 rounded-4 overflow-hidden">
                                        <a href="item-details.php?slug=<?= $item['slug'] ?>" class="stretched-link"></a>
                                        <div class="position-relative">
                                            <!-- start item image -->
                                            <?php 
                                            $main_image = !empty($images) ? $images[0] : (!empty($item['main_image']) ? upload('items/' . $item['main_image']) : 'assets/images/default-item.jpg'); ?>
                                            <img src="<?= htmlspecialchars($main_image) ?>" alt="<?= htmlspecialchars($item['title']) ?>" class="card-img-top h-200 object-fit-cover">
                                            
                                            <!-- end /. item image -->
                                            <!-- start badges -->
                                            <div class="position-absolute top-0 start-0 m-3">
                                                <span class="badge bg-primary"><?= htmlspecialchars($item['category_name']) ?></span>
                                            </div>
                                            <?php if ($item['featured']): ?>
                                                <div class="position-absolute top-0 end-0 m-3">
                                                    <span class="badge bg-warning text-dark">Featured</span>
                                                </div>
                                            <?php endif; ?>
                                            <!-- end /. badges -->
                                        </div>
                                        <div class="card-body">
                                            <!-- start item title -->
                                            <h6 class="fw-semibold mb-2"><?= htmlspecialchars($item['title']) ?></h6>
                                            <!-- end /. item title -->
                                            <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">
                                                        <?php
                                                        $item_rating = $item['item_average_rating'] ?? 0;
                                                        $item_reviews = $item['item_total_ratings'] ?? 0;
                                                        
                                                        // Display stars
                                                        for ($i = 1; $i <= 5; $i++):
                                                            $filled = $i <= round($item_rating);
                                                        ?>
                                                            <i class="fas fa-star <?= $filled ? 'text-warning' : 'text-muted' ?>" style="font-size: 0.85rem;"></i>
                                                        <?php endfor; ?>
                                                        <span class="small ms-2">
                                                            <?= number_format($item_rating, 1) ?> (<?= $item_reviews ?> <?= $item_reviews === 1 ? 'review' : 'reviews' ?>)
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <?php
                                                    // Calculate REAL-TIME availability for TODAY
                                                    $today = date('Y-m-d');

                                                    // Get total booked for this specific item TODAY
                                                    $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'];

                                                    // Use 'quantity' as total, not 'available_quantity'
                                                    $totalQuantity = $item['quantity'];
                                                    $availableToday = $totalQuantity - $bookedToday;

                                                    if ($availableToday <= 0):
                                                ?>
                                                    <span class="badge bg-danger">Fully Booked Today</span>
                                                <?php elseif ($availableToday < $totalQuantity): ?>
                                                    <span class="badge bg-warning"><?= $availableToday ?> of <?= $totalQuantity ?> Available</span>
                                                <?php else: ?>
                                                    <span class="badge bg-success"><?= $availableToday ?> Available</span>
                                                <?php endif; ?>
                                            </div>
                                            <!-- start location -->
                                            <p class="text-muted small mb-2">
                                                <i class="fas fa-map-marker-alt me-1"></i>
                                                <?= htmlspecialchars($item['location'] ?? $item['city'] . ', ' . $item['state']) ?>
                                            </p>
                                            <p class="text-muted small mb-2">
                                                <i class="fas fa-store me-1"></i>
                                                <?= htmlspecialchars($item['vendor_name']) ?>
                                            </p>
                                            <!-- end /. location -->
                                            <!-- start price -->
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <span class="fs-5 fw-bold text-primary">&#8358;<?= number_format($item['price_per_day'], 2) ?></span>
                                                    <span class="text-muted small">/day</span>
                                                </div>
                                            </div>                                     
                                            <!-- end /. price -->
                                        </div>
                                    </div>
                                    <!-- end /. item card -->
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <!-- start no results -->
                        <div class="text-center py-5">
                            <div class="mb-4">
                                <i class="fas fa-search fs-1 text-muted"></i>
                            </div>
                            <h4>No items found</h4>
                            <p class="text-muted">Try adjusting your search criteria or browse all items.</p>
                            <a href="items.php" class="btn btn-primary">Browse All Items</a>
                        </div>
                        <!-- end no results -->
                    <?php endif; ?>
                    <!-- end items grid -->
                    
                    
                    <!-- start pagination -->
                    <?php if ($total_pages > 1): ?>
                    <nav class="justify-content-center mt-5 pagination align-items-center">
                        <?php if ($page > 1): ?>
                            <a class="prev page-numbers" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>" aria-label="Previous">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-left-short" viewBox="0 0 16 16">
                                <path fill-rule="evenodd" d="M12 8a.5.5 0 0 1-.5.5H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5a.5.5 0 0 1 .5.5z" />
                            </svg>
                            Previous
                        </a>
                        <?php endif; ?>
                        <!-- Page numbers -->
                                <?php
                                $start_page = max(1, $page - 2);
                                $end_page = min($total_pages, $page + 2);
                                
                                for ($i = $start_page; $i <= $end_page; $i++):

                                    if($i == $page){
                                ?>
                                <span class="page-numbers current"><?= $i; ?></span>
                                <?php } else { ?>
                                <a style="border:1px solid #999; border-radius:5px; padding:10px;" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i; ?></a>
                                <?php } ?>
                        <?php endfor; ?>

                        <!-- Next page -->
                        <?php if ($page < $total_pages): ?>
                        <a class="next page-numbers" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" aria-label="Next">
                            Next
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-right-short" viewBox="0 0 16 16">
                                <path fill-rule="evenodd" d="M4 8a.5.5 0 0 1 .5-.5h5.793L8.146 5.354a.5.5 0 1 1 .708-.708l3 3a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708-.708L10.293 8.5H4.5A.5.5 0 0 1 4 8z" />
                            </svg>
                        </a>
                        <?php endif; ?>
                    </nav>
                    <?php endif; ?>
                    <!-- end /. pagination -->
                </div>
                <!-- end main content area -->
            </div>
        </div>
    </div>
    <!-- end main content -->

    <!-- start mobile filter offcanvas -->
    <div class="offcanvas offcanvas-start" tabindex="-1" id="filterSidebar" aria-labelledby="filterSidebarLabel">
        <div class="offcanvas-header">
            <h5 class="offcanvas-title" id="filterSidebarLabel">Filters</h5>
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
        </div>
        <div class="offcanvas-body">
            <!-- Same filter form as sidebar -->
            <form id="filterFormMobile" method="GET" action="items.php">
                <!-- Hidden fields to preserve other parameters -->
                <?php foreach ($_GET as $key => $value): ?>
                    <?php if (!in_array($key, ['search', 'category', 'location', 'min_price', 'max_price', 'sort', 'page'])): ?>
                        <input type="hidden" name="<?= htmlspecialchars($key) ?>" value="<?= htmlspecialchars($value) ?>">
                    <?php endif; ?>
                <?php endforeach; ?>
                
                <!-- Same filter fields as desktop version -->
                <div class="mb-4">
                    <label class="form-label">Search</label>
                    <input type="text" name="search" class="form-control" placeholder="Search items..." value="<?= htmlspecialchars($search) ?>">
                </div>
                
                <div class="mb-4">
                    <label class="form-label">Category</label>
                    <select name="category" class="form-select">
                        <option value="">All Categories</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= htmlspecialchars($cat['slug']) ?>" <?= $category === $cat['slug'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cat['name']) ?> (<?= $cat['total_items'] ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="mb-4">
                    <label class="form-label">Location</label>
                    <select name="location" class="form-select">
                        <option value="">All Locations</option>
                        <?php foreach ($locations as $loc): ?>
                            <?php $location_str = $loc['city'] . ', ' . $loc['state']; ?>
                            <option value="<?= htmlspecialchars($location_str) ?>" <?= $location === $location_str ? 'selected' : '' ?>>
                                <?= htmlspecialchars($location_str) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="mb-4">
                    <label class="form-label">Price Range (per day)</label>
                    <div class="row g-2">
                        <div class="col-6">
                            <input type="number" name="min_price" class="form-control" placeholder="Min &#8358;" value="<?= htmlspecialchars($min_price) ?>">
                        </div>
                        <div class="col-6">
                            <input type="number" name="max_price" class="form-control" placeholder="Max &#8358;" value="<?= htmlspecialchars($max_price) ?>">
                        </div>
                    </div>
                </div>
                
                <div class="mb-4">
                    <label class="form-label">Sort By</label>
                    <select name="sort" class="form-select">
                        <option value="newest" <?= $sort === 'newest' ? 'selected' : '' ?>>Newest First</option>
                        <option value="oldest" <?= $sort === 'oldest' ? 'selected' : '' ?>>Oldest First</option>
                        <option value="price_low" <?= $sort === 'price_low' ? 'selected' : '' ?>>Price: Low to High</option>
                        <option value="price_high" <?= $sort === 'price_high' ? 'selected' : '' ?>>Price: High to Low</option>
                        <option value="rating" <?= $sort === 'rating' ? 'selected' : '' ?>>Highest Rated</option>
                        <option value="popular" <?= $sort === 'popular' ? 'selected' : '' ?>>Most Popular</option>
                    </select>
                </div>
                
                <div class="d-grid gap-2">
                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                    <a href="items.php" class="btn btn-outline-secondary">Clear All</a>
                </div>
            </form>
        </div>
    </div>
    <!-- end mobile filter offcanvas -->

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