<?php
// category.php - Browse Products by Category (Shows Reserved Products with Badge)
// File location: /bidwheels.net/product/category.php

require_once '../includes/functions.php';
require_once '../includes/header.php';

$category_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($category_id <= 0) {
    redirect('/product/index.php');
}

// Get category details
$category = fetchOne("SELECT * FROM categories WHERE id = $category_id");

if (!$category) {
    redirect('/product/index.php');
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * PRODUCTS_PER_PAGE;

// Sort
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'newest';

// Build order by
$order_by = "ORDER BY p.created_at DESC";
switch($sort) {
    case 'price_low':
        $order_by = "ORDER BY p.starting_price ASC";
        break;
    case 'price_high':
        $order_by = "ORDER BY p.starting_price DESC";
        break;
    case 'bid_high':
        $order_by = "ORDER BY (SELECT MAX(amount) FROM bids WHERE product_id = p.id) DESC";
        break;
    case 'ending_soon':
        $order_by = "ORDER BY p.end_time ASC";
        break;
    case 'newest':
    default:
        $order_by = "ORDER BY p.created_at DESC";
        break;
}

// Get products in this category - REMOVED is_reserved = 0 to show reserved products
$products = fetchAll("
    SELECT p.*, c.name as category_name,
           (SELECT COUNT(*) FROM bids WHERE product_id = p.id) as total_bids,
           (SELECT MAX(amount) FROM bids WHERE product_id = p.id) as highest_bid
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    WHERE p.category_id = $category_id 
    AND p.end_time > NOW()
    $order_by
    LIMIT $offset, " . PRODUCTS_PER_PAGE
);

$total = getCount('products', "category_id = $category_id AND end_time > NOW()");
$total_pages = ceil($total / PRODUCTS_PER_PAGE);

// Get all categories for sidebar
$all_categories = fetchAll("SELECT * FROM categories ORDER BY name");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($category['name']); ?> - <?php echo SITE_NAME; ?></title>
    
    <style>
        .category-page {
            background: linear-gradient(135deg, #EFEBE0 0%, #e5e0d4 100%);
            min-height: 100vh;
            padding: 50px 0 70px;
        }
        
        .category-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 24px;
        }
        
        .breadcrumb {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 30px;
            padding: 12px 20px;
            background: white;
            border-radius: 50px;
            width: fit-content;
            box-shadow: 0 2px 10px rgba(0,0,0,0.03);
        }
        
        .breadcrumb a {
            color: #666;
            text-decoration: none;
            font-size: 14px;
            transition: color 0.3s;
        }
        
        .breadcrumb a:hover {
            color: #FF8C3E;
        }
        
        .breadcrumb span {
            color: #FF8C3E;
            font-weight: 500;
        }
        
        .breadcrumb i {
            font-size: 10px;
            color: #ccc;
        }
        
        .category-header {
            text-align: center;
            margin-bottom: 50px;
            position: relative;
        }
        
        .category-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            border-radius: 30px;
            margin-bottom: 20px;
            box-shadow: 0 10px 25px rgba(255,140,62,0.3);
        }
        
        .category-icon i {
            font-size: 40px;
            color: white;
        }
        
        .category-header h1 {
            font-size: 42px;
            font-weight: 800;
            background: linear-gradient(135deg, #1a1a1a 0%, #FF8C3E 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 12px;
        }
        
        .category-header p {
            color: #666;
            font-size: 16px;
        }
        
        .category-stats {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: white;
            padding: 6px 16px;
            border-radius: 40px;
            margin-top: 15px;
            font-size: 13px;
            color: #666;
        }
        
        .category-stats i {
            color: #FF8C3E;
        }
        
        .category-stats span {
            color: #FF8C3E;
            font-weight: 700;
        }
        
        .products-layout {
            display: grid;
            grid-template-columns: 280px 1fr;
            gap: 35px;
        }
        
        .products-sidebar {
            position: sticky;
            top: 100px;
            height: fit-content;
        }
        
        .sidebar-widget {
            background: white;
            border-radius: 24px;
            padding: 20px 24px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            transition: transform 0.3s, box-shadow 0.3s;
        }
        
        .sidebar-widget:last-child {
            margin-bottom: 0;
        }
        
        .sidebar-widget:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .sidebar-widget h3 {
            font-size: 16px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #FF8C3E;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .sidebar-widget h3 i {
            color: #FF8C3E;
            font-size: 14px;
        }
        
        .category-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .category-list li {
            margin-bottom: 5px;
        }
        
        .category-list li:last-child {
            margin-bottom: 0;
        }
        
        .category-list li a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 12px;
            color: #444;
            text-decoration: none;
            border-radius: 12px;
            transition: all 0.3s;
            font-size: 13px;
            font-weight: 500;
        }
        
        .category-list li a i {
            width: 20px;
            color: #FF8C3E;
            font-size: 14px;
        }
        
        .category-list li a:hover {
            background: #f8f8f8;
            color: #FF8C3E;
            transform: translateX(3px);
        }
        
        .category-list li a.active {
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            color: white;
        }
        
        .category-list li a.active i {
            color: white;
        }
        
        .sort-select {
            width: 100%;
            padding: 10px 14px;
            border: 2px solid #f0f0f0;
            border-radius: 12px;
            font-size: 13px;
            background: #f8f8f8;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .sort-select:focus {
            outline: none;
            border-color: #FF8C3E;
            background: white;
        }
        
        .products-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 25px;
        }
        
        .product-card {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            position: relative;
        }
        
        .product-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #FF8C3E, #046307);
            transform: scaleX(0);
            transition: transform 0.4s;
        }
        
        .product-card:hover::before {
            transform: scaleX(1);
        }
        
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(255,140,62,0.15);
        }
        
        .product-image {
            position: relative;
            aspect-ratio: 4/3;
            overflow: hidden;
            cursor: pointer;
        }
        
        .product-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s;
        }
        
        .product-card:hover .product-image img {
            transform: scale(1.05);
        }
        
        .product-bid-count {
            position: absolute;
            bottom: 10px;
            left: 10px;
            background: rgba(0,0,0,0.7);
            backdrop-filter: blur(4px);
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            color: white;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .product-bid-count i {
            color: #FF8C3E;
        }
        
        .reserved-badge-card {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #dc3545;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 5px;
            z-index: 10;
        }
        
        .product-info {
            padding: 15px;
        }
        
        .product-title {
            font-size: 15px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 6px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        
        .product-category {
            font-size: 11px;
            color: #FF8C3E;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .product-price {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            margin-bottom: 10px;
        }
        
        .current-bid {
            font-size: 18px;
            font-weight: 700;
            color: #FF8C3E;
        }
        
        .starting-price {
            font-size: 11px;
            color: #aaa;
            text-decoration: line-through;
        }
        
        .product-time {
            font-size: 11px;
            color: #666;
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 12px;
            padding: 5px 10px;
            background: #f8f8f8;
            border-radius: 20px;
            width: fit-content;
        }
        
        .product-time i {
            color: #046307;
        }
        
        .product-btn {
            display: block;
            text-align: center;
            background: linear-gradient(135deg, #1a1a1a, #2a2a2a);
            color: white;
            padding: 10px;
            border-radius: 30px;
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s;
        }
        
        .product-btn:hover {
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            transform: translateY(-2px);
        }
        
        .product-btn-disabled {
            display: block;
            text-align: center;
            background: #6c757d;
            color: white;
            padding: 10px;
            border-radius: 30px;
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            cursor: not-allowed;
        }
        
        .result-count {
            background: white;
            border-radius: 40px;
            padding: 6px 16px;
            display: inline-block;
            margin-bottom: 20px;
            font-size: 13px;
            font-weight: 500;
            color: #666;
        }
        
        .result-count span {
            color: #FF8C3E;
            font-weight: 700;
        }
        
        .no-results {
            text-align: center;
            padding: 60px;
            background: white;
            border-radius: 24px;
            grid-column: 1/-1;
        }
        
        .no-results i {
            font-size: 60px;
            color: #ddd;
            margin-bottom: 20px;
        }
        
        .no-results h3 {
            font-size: 24px;
            color: #333;
            margin-bottom: 10px;
        }
        
        .no-results p {
            color: #888;
            margin-bottom: 20px;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-top: 40px;
            flex-wrap: wrap;
        }
        
        .pagination a {
            padding: 8px 14px;
            background: white;
            color: #333;
            text-decoration: none;
            border-radius: 10px;
            transition: all 0.3s;
            font-weight: 500;
            font-size: 13px;
        }
        
        .pagination a:hover {
            background: #FF8C3E;
            color: white;
            transform: translateY(-2px);
        }
        
        .pagination a.active {
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            color: white;
        }
        
        @media (max-width: 1200px) {
            .products-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        @media (max-width: 992px) {
            .products-layout {
                grid-template-columns: 1fr;
            }
            
            .products-sidebar {
                display: none;
            }
            
            .products-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        @media (max-width: 768px) {
            .category-page {
                padding: 30px 0 50px;
            }
            
            .category-container {
                padding: 0 16px;
            }
            
            .category-header h1 {
                font-size: 28px;
            }
            
            .category-icon {
                width: 60px;
                height: 60px;
            }
            
            .category-icon i {
                font-size: 28px;
            }
            
            .breadcrumb {
                padding: 8px 16px;
                font-size: 12px;
            }
            
            .products-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .product-image {
                width: 100%;
                aspect-ratio: 4/3;
            }
            
            .product-image img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
        
        @media (max-width: 480px) {
            .category-header h1 {
                font-size: 24px;
            }
            
            .current-bid {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>

<div class="category-page">
    <div class="category-container">
        <!-- Breadcrumb -->
        <div class="breadcrumb">
            <a href="<?php echo SITE_URL; ?>/index.php"><i class="fas fa-home"></i> Home</a>
            <i class="fas fa-chevron-right"></i>
            <a href="index.php">Vehicles</a>
            <i class="fas fa-chevron-right"></i>
            <span><?php echo htmlspecialchars($category['name']); ?></span>
        </div>
        
        <!-- Category Header -->
        <div class="category-header">
            <div class="category-icon">
                <i class="<?php echo $category['icon'] ?? 'fas fa-car'; ?>"></i>
            </div>
            <h1><?php echo htmlspecialchars($category['name']); ?></h1>
            <p>Browse our collection of premium <?php echo strtolower(htmlspecialchars($category['name'])); ?></p>
            <div class="category-stats">
                <i class="fas fa-car"></i>
                <span><?php echo $total; ?></span> vehicles available
            </div>
        </div>
        
        <div class="products-layout">
            <!-- Sidebar -->
            <aside class="products-sidebar">
                <div class="sidebar-widget">
                    <h3><i class="fas fa-filter"></i> Categories</h3>
                    <ul class="category-list">
                        <li><a href="index.php"><i class="fas fa-car"></i> All Categories</a></li>
                        <?php foreach ($all_categories as $cat): ?>
                            <li>
                                <a href="category.php?id=<?php echo $cat['id']; ?>" <?php echo $cat['id'] == $category_id ? 'class="active"' : ''; ?>>
                                    <i class="<?php echo $cat['icon'] ?? 'fas fa-car'; ?>"></i> <?php echo htmlspecialchars($cat['name']); ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                
                <div class="sidebar-widget">
                    <h3><i class="fas fa-sort-amount-down"></i> Sort By</h3>
                    <select class="sort-select" id="sortSelect" onchange="updateSort()">
                        <option value="newest" <?php echo $sort == 'newest' ? 'selected' : ''; ?>>Newest First</option>
                        <option value="price_low" <?php echo $sort == 'price_low' ? 'selected' : ''; ?>>Price: Low to High</option>
                        <option value="price_high" <?php echo $sort == 'price_high' ? 'selected' : ''; ?>>Price: High to Low</option>
                        <option value="bid_high" <?php echo $sort == 'bid_high' ? 'selected' : ''; ?>>Highest Bid</option>
                        <option value="ending_soon" <?php echo $sort == 'ending_soon' ? 'selected' : ''; ?>>Ending Soon</option>
                    </select>
                </div>
            </aside>
            
            <!-- Products Content -->
            <div class="products-content">
                <div class="result-count">
                    <i class="fas fa-car"></i> Found <span><?php echo $total; ?></span> vehicles in <?php echo htmlspecialchars($category['name']); ?>
                </div>
                
                <div class="products-grid">
                    <?php if (count($products) > 0): ?>
                        <?php foreach ($products as $product): ?>
                            <div class="product-card">
                                <?php if ($product['is_reserved'] == 1): ?>
                                    <div class="reserved-badge-card">
                                        <i class="fas fa-ban"></i> RESERVED
                                    </div>
                                <?php endif; ?>
                                <div class="product-image" onclick="window.location.href='detail.php?id=<?php echo $product['id']; ?>'">
                                    <img src="<?php echo getFeaturedImage($product['id']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                                    <div class="product-bid-count">
                                        <i class="fas fa-gavel"></i> <?php echo $product['total_bids']; ?> bids
                                    </div>
                                </div>
                                <div class="product-info">
                                    <h3 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h3>
                                    <div class="product-category">
                                        <i class="fas fa-tag"></i> <?php echo htmlspecialchars($product['category_name']); ?>
                                    </div>
                                    <div class="product-price">
                                        <span class="current-bid"><?php echo formatPrice($product['highest_bid'] ?? $product['starting_price']); ?></span>
                                        <span class="starting-price"><?php echo formatPrice($product['starting_price']); ?></span>
                                    </div>
                                    <div class="product-time" data-end-time="<?php echo $product['end_time']; ?>">
                                        <i class="fas fa-clock"></i> <?php echo getRemainingTime($product['end_time']); ?>
                                    </div>
                                    <?php if ($product['is_reserved'] == 1): ?>
                                        <div class="product-btn-disabled">
                                            <i class="fas fa-ban"></i> Not Available
                                        </div>
                                    <?php else: ?>
                                        <a href="detail.php?id=<?php echo $product['id']; ?>" class="product-btn">Place Bid <i class="fas fa-arrow-right"></i></a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="no-results">
                            <i class="fas fa-search"></i>
                            <h3>No vehicles found</h3>
                            <p>There are no active listings in this category at the moment.</p>
                            <a href="index.php" class="product-btn" style="display: inline-block; padding: 12px 28px;">Browse All Categories</a>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?id=<?php echo $category_id; ?>&page=<?php echo $page - 1; ?>&sort=<?php echo $sort; ?>"><i class="fas fa-chevron-left"></i> Prev</a>
                        <?php endif; ?>
                        
                        <?php
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $page + 2);
                        
                        if ($start_page > 1) {
                            echo '<a href="?id=' . $category_id . '&page=1&sort=' . $sort . '">1</a>';
                            if ($start_page > 2) echo '<span style="padding: 8px 6px;">...</span>';
                        }
                        
                        for ($i = $start_page; $i <= $end_page; $i++): ?>
                            <a href="?id=<?php echo $category_id; ?>&page=<?php echo $i; ?>&sort=<?php echo $sort; ?>" class="<?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
                        <?php endfor;
                        
                        if ($end_page < $total_pages) {
                            if ($end_page < $total_pages - 1) echo '<span style="padding: 8px 6px;">...</span>';
                            echo '<a href="?id=' . $category_id . '&page=' . $total_pages . '&sort=' . $sort . '">' . $total_pages . '</a>';
                        }
                        ?>
                        
                        <?php if ($page < $total_pages): ?>
                            <a href="?id=<?php echo $category_id; ?>&page=<?php echo $page + 1; ?>&sort=<?php echo $sort; ?>">Next <i class="fas fa-chevron-right"></i></a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function updateSort() {
    const sort = document.getElementById('sortSelect').value;
    const currentUrl = new URL(window.location.href);
    currentUrl.searchParams.set('sort', sort);
    currentUrl.searchParams.set('page', 1);
    window.location.href = currentUrl.toString();
}

function updateCountdowns() {
    document.querySelectorAll('.product-time').forEach(el => {
        const endTime = el.getAttribute('data-end-time');
        if (endTime) {
            const remaining = getRemainingTime(endTime);
            el.innerHTML = `<i class="fas fa-clock"></i> ${remaining}`;
        }
    });
}

function getRemainingTime(endTime) {
    const now = new Date().getTime();
    const end = new Date(endTime).getTime();
    const distance = end - now;
    
    if (distance < 0) return 'Ended';
    
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (86400000)) / (3600000));
    const minutes = Math.floor((distance % (3600000)) / (60000));
    
    if (days > 0) {
        return days + 'd ' + hours + 'h';
    } else if (hours > 0) {
        return hours + 'h ' + minutes + 'm';
    } else if (minutes > 0) {
        return minutes + 'm left';
    } else {
        return 'Ending soon';
    }
}

setInterval(updateCountdowns, 1000);
</script>

<?php require_once '../includes/footer.php'; ?>