<?php
require_once 'header.php';

// Get filter parameters
$category = $_GET['category'] ?? 'all';
$brand = $_GET['brand'] ?? 'all';
$min_price = $_GET['min_price'] ?? 0;
$max_price = $_GET['max_price'] ?? 5000;
$search = $_GET['search'] ?? '';

// Build query
$query = "SELECT l.*, c.name as category_name 
          FROM laptops l 
          LEFT JOIN laptop_categories c ON l.category_id = c.id 
          WHERE l.is_active = 1";

$params = [];

if ($category != 'all') {
    $query .= " AND l.category_id = ?";
    $params[] = $category;
}

if ($brand != 'all') {
    $query .= " AND l.brand = ?";
    $params[] = $brand;
}

if ($min_price > 0) {
    $query .= " AND l.price >= ?";
    $params[] = $min_price;
}

if ($max_price < 5000) {
    $query .= " AND l.price <= ?";
    $params[] = $max_price;
}

if (!empty($search)) {
    $query .= " AND (l.brand LIKE ? OR l.model LIKE ? OR l.processor LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$query .= " ORDER BY l.is_featured DESC, l.created_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$laptops = $stmt->fetchAll();

// Get unique brands for filter
$brands = $pdo->query("SELECT DISTINCT brand FROM laptops WHERE is_active = 1 ORDER BY brand")->fetchAll();

// Get categories for filter
$categories = $pdo->query("SELECT * FROM laptop_categories WHERE is_active = 1")->fetchAll();
?>

    <style>
        .laptop-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            transition: all 0.3s;
            margin-bottom: 30px;
            height: 100%;
        }
        
        .laptop-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.15);
        }
        
        .laptop-image {
            position: relative;
            overflow: hidden;
            background: #f8f9fa;
            text-align: center;
            padding: 20px;
            height: 250px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .laptop-image img {
            max-width: 100%;
            max-height: 200px;
            object-fit: contain;
            transition: transform 0.3s;
        }
        
        .laptop-card:hover .laptop-image img {
            transform: scale(1.05);
        }
        
        .gallery-btn {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background: rgba(0,123,255,0.9);
            color: white;
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s;
            opacity: 0;
        }
        
        .laptop-card:hover .gallery-btn {
            opacity: 1;
        }
        
        .gallery-btn:hover {
            background: #0056b3;
            transform: scale(1.1);
        }
        
        .laptop-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            background: #ffc107;
            color: #000;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .laptop-badge.featured {
            background: #dc3545;
            color: white;
        }
        
        .laptop-badge.discount {
            background: #28a745;
            color: white;
        }
        
        .laptop-info {
            padding: 20px;
        }
        
        .laptop-title {
            font-size: 1.2rem;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .laptop-specs {
            margin: 15px 0;
            font-size: 0.9rem;
        }
        
        .laptop-specs i {
            width: 20px;
            color: #007bff;
        }
        
        .laptop-price {
            font-size: 1.5rem;
            font-weight: bold;
            color: #28a745;
        }
        
        .old-price {
            font-size: 0.9rem;
            color: #999;
            text-decoration: line-through;
            margin-left: 10px;
        }
        
        .filter-sidebar {
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            position: sticky;
            top: 80px;
        }
        
        /* Modal Gallery Styles */
        .modal-gallery {
            position: relative;
        }
        
        .gallery-main-image {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .gallery-main-image img {
            max-width: 100%;
            max-height: 400px;
            object-fit: contain;
        }
        
        .gallery-thumbnails {
            display: flex;
            gap: 10px;
            overflow-x: auto;
            padding: 10px 0;
        }
        
        .gallery-thumb {
            width: 80px;
            height: 80px;
            object-fit: cover;
            cursor: pointer;
            border: 2px solid transparent;
            border-radius: 5px;
            transition: all 0.3s;
        }
        
        .gallery-thumb:hover, .gallery-thumb.active {
            border-color: #007bff;
            transform: scale(1.05);
        }
        
        .specs-table {
            width: 100%;
            margin-top: 20px;
        }
        
        .specs-table tr td {
            padding: 8px;
            border-bottom: 1px solid #eee;
        }
        
        .specs-table tr td:first-child {
            font-weight: bold;
            width: 35%;
            background: #f8f9fa;
        }
        
        .stock-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #28a745;
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 12px;
        }
        
        .out-of-stock {
            background: #dc3545;
        }
        
        @media (max-width: 768px) {
            .filter-sidebar {
                margin-bottom: 20px;
                position: relative;
                top: 0;
            }
        }
    </style>
</head>
<body>


<!-- Page Header -->
<div class="page-header bg-primary text-white py-5 mt-5">
    <div class="container text-center">
        <h1>Premium Laptops</h1>
        <p class="lead">Find the perfect laptop for your needs at competitive prices</p>
    </div>
</div>

<!-- Main Content -->
<div class="container py-5">
    <div class="row">
        <!-- Sidebar Filters -->
        <div class="col-lg-3 mb-4">
            <div class="filter-sidebar">
                <h4 class="mb-4">Filter Laptops</h4>
                
                <form method="GET" action="">
                    <!-- Search -->
                    <div class="mb-4">
                        <label class="form-label">Search</label>
                        <div class="input-group">
                            <input type="text" name="search" class="form-control" placeholder="Search by brand/model..." value="<?php echo htmlspecialchars($search); ?>">
                            <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button>
                        </div>
                    </div>
                    
                    <!-- Category Filter -->
                    <div class="mb-4">
                        <label class="form-label">Category</label>
                        <select name="category" class="form-select" onchange="this.form.submit()">
                            <option value="all">All Categories</option>
                            <?php foreach($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>" <?php echo $category == $cat['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Brand Filter -->
                    <div class="mb-4">
                        <label class="form-label">Brand</label>
                        <select name="brand" class="form-select" onchange="this.form.submit()">
                            <option value="all">All Brands</option>
                            <?php foreach($brands as $b): ?>
                                <option value="<?php echo $b['brand']; ?>" <?php echo $brand == $b['brand'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($b['brand']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Price Range -->
                    <div class="mb-4">
                        <label class="form-label">Price Range</label>
                        <div class="row g-2">
                            <div class="col-6">
                                <input type="number" name="min_price" class="form-control" placeholder="Min" value="<?php echo $min_price; ?>">
                            </div>
                            <div class="col-6">
                                <input type="number" name="max_price" class="form-control" placeholder="Max" value="<?php echo $max_price; ?>">
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
                    <a href="laptops.php" class="btn btn-secondary w-100 mt-2">Reset Filters</a>
                </form>
            </div>
        </div>
        
        <!-- Laptops Grid -->
        <div class="col-lg-9">
            <?php if(count($laptops) > 0): ?>
                <div class="row">
                    <?php foreach($laptops as $laptop): 
                        // Get primary image
                        $stmt = $pdo->prepare("SELECT image_url FROM laptop_images WHERE laptop_id = ? AND is_primary = 1 LIMIT 1");
                        $stmt->execute([$laptop['id']]);
                        $primary_image = $stmt->fetch();
                        $image_url = $primary_image ? $primary_image['image_url'] : 'assets/images/laptops/placeholder.jpg';
                        
                        // Get all images for gallery
                        $stmt = $pdo->prepare("SELECT image_url FROM laptop_images WHERE laptop_id = ? ORDER BY sort_order");
                        $stmt->execute([$laptop['id']]);
                        $gallery_images = $stmt->fetchAll();
                    ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="laptop-card">
                                <div class="laptop-image">
                                    <img src="<?php echo $image_url; ?>" alt="<?php echo $laptop['brand'] . ' ' . $laptop['model']; ?>" onerror="this.src='https://via.placeholder.com/300x200?text=No+Image'">
                                    
                                    <?php if($laptop['is_featured']): ?>
                                        <span class="laptop-badge featured"><i class="fas fa-star"></i> Featured</span>
                                    <?php endif; ?>
                                    
                                    <?php if($laptop['discount_price'] && $laptop['discount_price'] < $laptop['price']): ?>
                                        <span class="laptop-badge discount"><i class="fas fa-tag"></i> Sale</span>
                                    <?php endif; ?>
                                    
                                    <span class="stock-badge <?php echo $laptop['stock_quantity'] > 0 ? '' : 'out-of-stock'; ?>">
                                        <?php echo $laptop['stock_quantity'] > 0 ? 'In Stock' : 'Out of Stock'; ?>
                                    </span>
                                    
                                    <?php if(count($gallery_images) > 0): ?>
                                        <button class="gallery-btn" onclick="openGallery(<?php echo $laptop['id']; ?>)">
                                            <i class="fas fa-images"></i>
                                        </button>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="laptop-info">
                                    <div class="laptop-title">
                                        <?php echo htmlspecialchars($laptop['brand'] . ' ' . $laptop['model']); ?>
                                    </div>
                                    
                                    <div class="laptop-specs">
                                        <div><i class="fas fa-microchip"></i> <?php echo htmlspecialchars($laptop['processor']); ?></div>
                                        <div><i class="fas fa-memory"></i> <?php echo htmlspecialchars($laptop['ram']); ?></div>
                                        <div><i class="fas fa-hdd"></i> <?php echo htmlspecialchars($laptop['storage']); ?></div>
                                        <div><i class="fas fa-tv"></i> <?php echo htmlspecialchars($laptop['display']); ?></div>
                                    </div>
                                    
                                    <div class="laptop-price">
                                        N<?php echo number_format($laptop['discount_price'] ?? $laptop['price'], 2); ?>
                                        <?php if($laptop['discount_price']): ?>
                                            <span class="old-price">N<?php echo number_format($laptop['price'], 2); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <button class="btn btn-primary w-100 mt-3" onclick="viewLaptopDetails(<?php echo $laptop['id']; ?>)">
                                        <i class="fas fa-info-circle"></i> View Details
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="alert alert-info text-center">
                    <i class="fas fa-info-circle fa-3x mb-3"></i>
                    <h4>No laptops found</h4>
                    <p>Try adjusting your filters or check back later for new arrivals.</p>
                    <a href="laptops.php" class="btn btn-primary">View All Laptops</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Laptop Details Modal -->
<div class="modal fade" id="laptopModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalTitle">Laptop Details</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="modalContent">
                <!-- Content loaded via AJAX -->
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <a href="contact.php" class="btn btn-primary">Inquire Now</a>
            </div>
        </div>
    </div>
</div>

<!-- Gallery Modal -->
<div class="modal fade" id="galleryModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Product Gallery</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="galleryContent">
                <!-- Gallery content loaded via AJAX -->
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php
require_once 'footer.php';
?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// View laptop details
function viewLaptopDetails(laptopId) {
    fetch(`get_laptop_details.php?id=${laptopId}`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('modalContent').innerHTML = html;
            new bootstrap.Modal(document.getElementById('laptopModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('modalContent').innerHTML = '<div class="alert alert-danger">Failed to load laptop details</div>';
        });
}

// Open gallery
function openGallery(laptopId) {
    fetch(`get_laptop_gallery.php?id=${laptopId}`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('galleryContent').innerHTML = html;
            new bootstrap.Modal(document.getElementById('galleryModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('galleryContent').innerHTML = '<div class="alert alert-danger">Failed to load gallery</div>';
        });
}

// Gallery image navigation
function setMainImage(element, imageUrl) {
    document.getElementById('mainGalleryImage').src = imageUrl;
    document.querySelectorAll('.gallery-thumb').forEach(thumb => {
        thumb.classList.remove('active');
    });
    element.classList.add('active');
}
</script>
</body>
</html>