<?php
/**
 * BROWSE ITEMS PAGE
 * File: customer/browse.php
 * Items listing page with filters and search
 */

require_once '../app/Core/init.php';

// Get filter parameters
$search = $_GET['search'] ?? '';
$category = $_GET['category'] ?? '';
$location = $_GET['location'] ?? '';
$min_price = $_GET['min_price'] ?? 0;
$max_price = $_GET['max_price'] ?? 100000;
$sort = $_GET['sort'] ?? 'newest';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 12;

// Get categories for filter
$categoryModel = new Category();
$categories = $categoryModel->getAll();

// Build filter array
$filters = [
    'search' => $search,
    'category' => $category,
    'location' => $location,
    'min_price' => $min_price,
    'max_price' => $max_price,
    'sort' => $sort,
    'page' => $page,
    'per_page' => $per_page
];

// Get items with filters
$itemModel = new Item();
$result = $itemModel->getWithFilters($filters);
$items = $result['items'];
$total_items = $result['total'];
$total_pages = ceil($total_items / $per_page);

$page_title = 'Browse Items - ' . APP_NAME;
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="../assets/images/favicon.png">
    <title><?= $page_title ?></title>
    
    <!-- CSS Files -->
    <link href="../assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../assets/plugins/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="../assets/plugins/ion.rangeSlider/ion.rangeSlider.min.css" rel="stylesheet">
    <link href="../assets/plugins/select2/select2.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>

<body>
    <!-- Header -->
    <div class="border-0 card header rounded-0 sticky-top">
        <nav class="navbar navbar-expand-lg navbar-light">
            <div class="container">
                <a class="navbar-brand m-0" href="../index.php">
                    <img class="logo-white" src="../assets/images/logo-white.png" alt="<?= APP_NAME ?>">
                    <img class="logo-dark" src="../assets/images/logo.png" alt="<?= APP_NAME ?>">
                </a>
                
                <div class="d-flex order-lg-2">
                    <?php if (Auth::check()): ?>
                        <a href="favorites.php" class="d-flex align-items-center justify-content-center p-0 btn-user position-relative" data-bs-toggle="tooltip" data-bs-title="Favorites">
                            <i class="fa-solid fa-heart"></i>
                            <?php 
                            $favoriteCount = (new Customer())->getFavoritesCount(Auth::user()['id']);
                            if ($favoriteCount > 0):
                            ?>
                            <span class="align-items-center bg-primary d-flex end-0 fs-11 justify-content-center nav-count position-absolute rounded-circle text-white">
                                <?= $favoriteCount ?>
                            </span>
                            <?php endif; ?>
                        </a>
                        
                        <a href="<?= url('/' . Auth::userType() . '/index.php') ?>" class="d-flex align-items-center justify-content-center p-0 btn-user" data-bs-toggle="tooltip" data-bs-title="Dashboard">
                            <i class="fa-solid fa-gauge"></i>
                        </a>
                    <?php else: ?>
                        <a href="../auth/login.php" class="d-flex align-items-center justify-content-center p-0 btn-user" data-bs-toggle="tooltip" data-bs-title="Sign In">
                            <i class="fa-solid fa-user-plus"></i>
                        </a>
                    <?php endif; ?>
                    
                    <button type="button" id="themeToggleBtn" class="align-items-center bg-transparent border-0 btn-user d-flex justify-content-center p-0">
                        <i class="fa-solid fa-moon"></i>
                    </button>
                    
                    <?php if (Auth::check() && Auth::userType() === 'vendor'): ?>
                    <a href="../vendor/item-form.php" class="btn btn-primary d-none d-sm-flex fw-medium gap-2 hstack rounded-5">
                        <i class="fas fa-plus-circle"></i>
                        <span class="d-none d-sm-inline-block">Add Item</span>
                    </a>
                    <?php else: ?>
                    <a href="../auth/register.php?type=vendor" class="btn btn-primary d-none d-sm-flex fw-medium gap-2 hstack rounded-5">
                        <i class="fas fa-store"></i>
                        <span class="d-none d-sm-inline-block">Become a Vendor</span>
                    </a>
                    <?php endif; ?>
                    
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
                        <span id="nav-icon">
                            <span></span>
                            <span></span>
                            <span></span>
                        </span>
                    </button>
                </div>
                
                <div class="collapse navbar-collapse" id="navbarContent">
                    <ul class="navbar-nav m-auto mb-2 mb-lg-0">
                        <li class="nav-item">
                            <a class="nav-link" href="../index.php">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="browse.php">Browse Items</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../about.php">About</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../contact.php">Contact</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        
        <!-- Search Bar -->
        <div class="bg-light border-top py-3">
            <div class="container">
                <form method="GET" action="browse.php" class="row g-2 align-items-center">
                    <div class="col-md-4 col-lg-5">
                        <div class="position-relative">
                            <i class="fas fa-search position-absolute top-50 translate-middle-y ms-3 text-muted"></i>
                            <input type="text" name="search" class="form-control ps-5" placeholder="Search items..." value="<?= Security::escapeOutput($search) ?>">
                        </div>
                    </div>
                    
                    <div class="col-md-3 col-lg-3">
                        <select name="location" class="form-select">
                            <option value="">All Locations</option>
                            <option value="Lagos" <?= $location === 'Lagos' ? 'selected' : '' ?>>Lagos</option>
                            <option value="Abuja" <?= $location === 'Abuja' ? 'selected' : '' ?>>Abuja</option>
                            <option value="Port Harcourt" <?= $location === 'Port Harcourt' ? 'selected' : '' ?>>Port Harcourt</option>
                            <option value="Kano" <?= $location === 'Kano' ? 'selected' : '' ?>>Kano</option>
                            <option value="Ibadan" <?= $location === 'Ibadan' ? 'selected' : '' ?>>Ibadan</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3 col-lg-3">
                        <select name="category" class="form-select">
                            <option value="">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['slug'] ?>" <?= $category === $cat['slug'] ? 'selected' : '' ?>>
                                <?= Security::escapeOutput($cat['name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2 col-lg-1">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Main Content -->
    <div class="py-3 py-xl-5 bg-gradient">
        <div class="container">
            <div class="row">
                <!-- Sidebar Filters -->
                <aside class="col-lg-3 mb-4 mb-lg-0">
                    <div class="card border-0 shadow-sm rounded-4">
                        <div class="card-body">
                            <form method="GET" action="browse.php" id="filterForm">
                                <!-- Keep existing search and location -->
                                <input type="hidden" name="search" value="<?= Security::escapeOutput($search) ?>">
                                <input type="hidden" name="location" value="<?= Security::escapeOutput($location) ?>">
                                <input type="hidden" name="category" value="<?= Security::escapeOutput($category) ?>">
                                
                                <!-- Price Filter -->
                                <div class="mb-4 pb-4 border-bottom">
                                    <h5 class="fw-semibold mb-3">Price Range</h5>
                                    <p class="small text-muted">₦<?= number_format($min_price) ?> - ₦<?= number_format($max_price) ?></p>
                                    <input type="range" class="form-range" name="min_price" min="0" max="100000" step="1000" value="<?= $min_price ?>" id="minPrice">
                                    <input type="range" class="form-range" name="max_price" min="0" max="100000" step="1000" value="<?= $max_price ?>" id="maxPrice">
                                </div>
                                
                                <!-- Categories Filter -->
                                <div class="mb-4 pb-4 border-bottom">
                                    <h5 class="fw-semibold mb-3">Categories</h5>
                                    <?php foreach ($categories as $cat): ?>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="radio" name="category" value="<?= $cat['slug'] ?>" 
                                               id="cat_<?= $cat['id'] ?>" <?= $category === $cat['slug'] ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="cat_<?= $cat['id'] ?>">
                                            <?= Security::escapeOutput($cat['name']) ?>
                                        </label>
                                    </div>
                                    <?php endforeach; ?>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="radio" name="category" value="" id="cat_all" <?= empty($category) ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="cat_all">All Categories</label>
                                    </div>
                                </div>
                                
                                <!-- Sort Options -->
                                <div class="mb-4">
                                    <h5 class="fw-semibold mb-3">Sort By</h5>
                                    <select name="sort" class="form-select" onchange="this.form.submit()">
                                        <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="popular" <?= $sort === 'popular' ? 'selected' : '' ?>>Most Popular</option>
                                        <option value="rating" <?= $sort === 'rating' ? 'selected' : '' ?>>Highest Rated</option>
                                    </select>
                                </div>
                                
                                <button type="submit" class="btn btn-primary w-100 mb-2">Apply Filters</button>
                                <a href="browse.php" class="btn btn-outline-secondary w-100">Clear Filters</a>
                            </form>
                        </div>
                    </div>
                </aside>
                
                <!-- Items Grid -->
                <div class="col-lg-9">
                    <!-- Toolbox -->
                    <div class="d-flex flex-wrap align-items-center justify-content-between mb-4">
                        <div class="fs-5">
                            Found <span class="fw-bold text-primary"><?= number_format($total_items) ?></span> items
                        </div>
                        
                        <div class="d-flex gap-2">
                            <a href="?<?= http_build_query(array_merge($filters, ['view' => 'grid'])) ?>" class="btn btn-sm btn-outline-primary <?= (!isset($_GET['view']) || $_GET['view'] === 'grid') ? 'active' : '' ?>">
                                <i class="fas fa-th"></i>
                            </a>
                            <a href="?<?= http_build_query(array_merge($filters, ['view' => 'list'])) ?>" class="btn btn-sm btn-outline-primary <?= (isset($_GET['view']) && $_GET['view'] === 'list') ? 'active' : '' ?>">
                                <i class="fas fa-list"></i>
                            </a>
                        </div>
                    </div>
                    
                    <!-- Items Grid -->
                    <?php if (empty($items)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-search fa-4x text-muted mb-3"></i>
                        <h4>No items found</h4>
                        <p class="text-muted">Try adjusting your filters or search terms</p>
                        <a href="browse.php" class="btn btn-primary">Clear Filters</a>
                    </div>
                    <?php else: ?>
                    <div class="row g-4 mb-5">
                        <?php foreach ($items as $item): ?>
                        <div class="col-sm-6 col-xl-4">
                            <div class="card border-0 shadow-sm rounded-4 h-100 card-hover overflow-hidden">
                                <a href="item-details.php?slug=<?= $item['slug'] ?>" class="position-relative d-block">
                                    <?php 
                                    $images = json_decode($item['images'], true);
                                    $main_image = !empty($images) ? $images[0] : '../assets/images/default-item.jpg';
                                    ?>
                                    <img src="<?= Security::escapeOutput($main_image) ?>" class="card-img-top" alt="<?= Security::escapeOutput($item['title']) ?>" style="height: 200px; object-fit: cover;">
                                    
                                    <?php if ($item['featured']): ?>
                                    <span class="badge bg-primary position-absolute top-0 start-0 m-3">
                                        <i class="fas fa-star"></i> Featured
                                    </span>
                                    <?php endif; ?>
                                    
                                    <?php if ($item['availability_status'] !== 'available'): ?>
                                    <span class="badge bg-danger position-absolute top-0 end-0 m-3">Not Available</span>
                                    <?php endif; ?>
                                </a>
                                
                                <div class="card-body">
                                    <div class="d-flex align-items-center mb-2">
                                        <div class="badge bg-light text-dark me-2">
                                            <i class="fas fa-star text-warning"></i>
                                            <?= number_format($item['average_rating'] ?? 0, 1) ?>
                                        </div>
                                        <small class="text-muted">(<?= $item['total_reviews'] ?? 0 ?>)</small>
                                    </div>
                                    
                                    <h5 class="card-title mb-2">
                                        <a href="item-details.php?slug=<?= $item['slug'] ?>" class="text-decoration-none text-dark">
                                            <?= Security::escapeOutput($item['title']) ?>
                                        </a>
                                    </h5>
                                    
                                    <p class="card-text text-muted small mb-3">
                                        <?= Security::escapeOutput(substr($item['description'], 0, 60)) ?>...
                                    </p>
                                    
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="fw-bold text-primary fs-5">₦<?= number_format($item['daily_rate']) ?></span>
                                            <span class="text-muted small">/day</span>
                                        </div>
                                        
                                        <?php if (Auth::check() && Auth::userType() === 'customer'): ?>
                                        <button type="button" class="btn btn-sm btn-outline-danger favorite-btn" data-item-id="<?= $item['id'] ?>">
                                            <i class="fas fa-heart"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?<?= http_build_query(array_merge($filters, ['page' => $page - 1])) ?>">
                                    <i class="fas fa-chevron-left"></i>
                                </a>
                            </li>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                            <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                <a class="page-link" href="?<?= http_build_query(array_merge($filters, ['page' => $i])) ?>">
                                    <?= $i ?>
                                </a>
                            </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?<?= http_build_query(array_merge($filters, ['page' => $page + 1])) ?>">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <?php include '../templates/layouts/frontend/footer.php'; ?>
    
    <!-- Scripts -->
    <script src="../assets/plugins/jQuery/jquery.min.js"></script>
    <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/plugins/ion.rangeSlider/ion.rangeSlider.min.js"></script>
    <script src="../assets/js/script.js"></script>
    
    <script>
        // Favorite functionality
        document.querySelectorAll('.favorite-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const itemId = this.dataset.itemId;
                
                fetch('../ajax/toggle-favorite.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({item_id: itemId})
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        this.classList.toggle('btn-outline-danger');
                        this.classList.toggle('btn-danger');
                    }
                });
            });
        });
        
        // Price range update
        document.getElementById('minPrice').addEventListener('input', function() {
            document.querySelector('p.small').textContent = 
                '₦' + parseInt(this.value).toLocaleString() + ' - ₦' + parseInt(document.getElementById('maxPrice').value).toLocaleString();
        });
        
        document.getElementById('maxPrice').addEventListener('input', function() {
            document.querySelector('p.small').textContent = 
                '₦' + parseInt(document.getElementById('minPrice').value).toLocaleString() + ' - ₦' + parseInt(this.value).toLocaleString();
        });
    </script>
</body>
</html>