<?php
// search.php - Advanced Product Search (Shows Reserved Products with Badge)
// File location: /bidwheels.net/product/search.php

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

// Get search parameters
$keyword = isset($_GET['keyword']) ? sanitize($_GET['keyword']) : '';
$category_id = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$min_price = isset($_GET['min_price']) ? (float)$_GET['min_price'] : 0;
$max_price = isset($_GET['max_price']) ? (float)$_GET['max_price'] : 0;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'relevance';

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

// Build WHERE clause - REMOVED is_reserved = 0 to show reserved products
$where = "p.end_time > NOW()";

if (!empty($keyword)) {
    $where .= " AND (p.name LIKE '%$keyword%' OR p.short_desc LIKE '%$keyword%' OR p.long_desc LIKE '%$keyword%' OR p.tags LIKE '%$keyword%')";
}

if ($category_id > 0) {
    $where .= " AND p.category_id = $category_id";
}

if ($min_price > 0) {
    $where .= " AND p.starting_price >= $min_price";
}

if ($max_price > 0) {
    $where .= " AND p.starting_price <= $max_price";
}

// 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 'relevance':
    default:
        $order_by = "ORDER BY p.created_at DESC";
        break;
}

// Get total count
$total_query = "SELECT COUNT(*) as total FROM products p WHERE $where";
$total_result = fetchOne($total_query);
$total = $total_result['total'];
$total_pages = ceil($total / PRODUCTS_PER_PAGE);

// Get 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 $where
    $order_by
    LIMIT $offset, " . PRODUCTS_PER_PAGE
);

// Get all categories for filter
$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">
    <meta name="description" content="Search for vehicles on <?php echo SITE_NAME; ?> - Find your dream car, motorcycle, or yacht by keyword, category, and price range.">
    <title>Search Vehicles - <?php echo SITE_NAME; ?></title>
    
    <style>
        .search-page {
            background: linear-gradient(135deg, #EFEBE0 0%, #e5e0d4 100%);
            min-height: 100vh;
            padding: 40px 0;
        }
        
        .search-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 24px;
        }
        
        .page-header {
            text-align: center;
            margin-bottom: 40px;
        }
        
        .page-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: 10px;
        }
        
        .page-header p {
            color: #666;
            font-size: 16px;
        }
        
        .search-hero {
            background: white;
            border-radius: 28px;
            padding: 30px;
            margin-bottom: 35px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
        }
        
        .search-form-main {
            display: grid;
            grid-template-columns: 2fr 1fr 1fr auto;
            gap: 15px;
            align-items: end;
        }
        
        .search-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .search-group label {
            font-size: 13px;
            font-weight: 600;
            color: #333;
        }
        
        .search-group label i {
            color: #FF8C3E;
            margin-right: 6px;
        }
        
        .search-group input,
        .search-group select {
            padding: 14px 16px;
            border: 2px solid #f0f0f0;
            border-radius: 16px;
            font-size: 14px;
            transition: all 0.3s;
            background: #f8f8f8;
        }
        
        .search-group input:focus,
        .search-group select:focus {
            outline: none;
            border-color: #FF8C3E;
            background: white;
        }
        
        .price-inputs {
            display: flex;
            gap: 10px;
        }
        
        .price-inputs input {
            width: 50%;
        }
        
        .search-btn {
            padding: 14px 28px;
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            border: none;
            border-radius: 16px;
            color: white;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
        }
        
        .search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255,140,62,0.3);
        }
        
        .reset-btn {
            padding: 14px 20px;
            background: #f0f0f0;
            border: none;
            border-radius: 16px;
            color: #666;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }
        
        .reset-btn:hover {
            background: #e0e0e0;
        }
        
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 25px;
            background: white;
            padding: 15px 20px;
            border-radius: 20px;
        }
        
        .result-count {
            font-size: 14px;
            color: #666;
        }
        
        .result-count span {
            color: #FF8C3E;
            font-weight: 700;
            font-size: 18px;
        }
        
        .sort-wrapper {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .sort-wrapper label {
            font-size: 13px;
            color: #666;
        }
        
        .sort-select {
            padding: 10px 16px;
            border: 1px solid #e0e0e0;
            border-radius: 30px;
            font-size: 13px;
            background: white;
            cursor: pointer;
        }
        
        .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: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.4s;
        }
        
        .product-card:hover .product-image img {
            transform: scale(1.05);
        }
        
        .product-badge {
            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-badge 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-row {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            margin-bottom: 10px;
        }
        
        .product-current-bid {
            font-size: 18px;
            font-weight: 700;
            color: #FF8C3E;
        }
        
        .product-starting {
            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: #1a1a1a;
            color: white;
            padding: 10px;
            border-radius: 30px;
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s;
        }
        
        .product-btn:hover {
            background: #FF8C3E;
            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;
        }
        
        .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: 10px;
            margin-top: 40px;
            flex-wrap: wrap;
        }
        
        .pagination a {
            padding: 8px 14px;
            background: white;
            color: #333;
            text-decoration: none;
            border-radius: 10px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .pagination a:hover {
            background: #FF8C3E;
            color: white;
        }
        
        .pagination a.active {
            background: #FF8C3E;
            color: white;
        }
        
        @media (max-width: 1200px) {
            .products-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        @media (max-width: 992px) {
            .search-form-main {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .price-inputs {
                flex-direction: column;
            }
            
            .price-inputs input {
                width: 100%;
            }
            
            .search-btn, .reset-btn {
                justify-content: center;
            }
        }
        
        @media (max-width: 768px) {
            .search-page {
                padding: 30px 0;
            }
            
            .search-container {
                padding: 0 16px;
            }
            
            .page-header h1 {
                font-size: 32px;
            }
            
            .products-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .results-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
        
        @media (max-width: 480px) {
            .search-hero {
                padding: 20px;
            }
        }
    </style>
</head>
<body>

<div class="search-page">
    <div class="search-container">
        <div class="page-header">
            <h1>Search Vehicles</h1>
            <p>Find your perfect vehicle by keyword, category, or price range</p>
        </div>
        
        <!-- Search Form -->
        <div class="search-hero">
            <form method="GET" action="" id="searchForm">
                <div class="search-form-main">
                    <div class="search-group">
                        <label><i class="fas fa-search"></i> Keyword</label>
                        <input type="text" name="keyword" placeholder="Search by name, description, tags..." value="<?php echo htmlspecialchars($keyword); ?>">
                    </div>
                    <div class="search-group">
                        <label><i class="fas fa-filter"></i> Category</label>
                        <select name="category">
                            <option value="0">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>" <?php echo $category_id == $cat['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="search-group">
                        <label><i class="fas fa-dollar-sign"></i> Price Range</label>
                        <div class="price-inputs">
                            <input type="number" name="min_price" placeholder="Min" value="<?php echo $min_price ?: ''; ?>">
                            <input type="number" name="max_price" placeholder="Max" value="<?php echo $max_price ?: ''; ?>">
                        </div>
                    </div>
                    <div class="search-group" style="flex-direction: row; gap: 10px;">
                        <button type="submit" class="search-btn"><i class="fas fa-search"></i> Search</button>
                        <a href="search.php" class="reset-btn"><i class="fas fa-times"></i> Reset</a>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Results Header -->
        <div class="results-header">
            <div class="result-count">
                <i class="fas fa-car"></i> Found <span><?php echo $total; ?></span> vehicles
                <?php if (!empty($keyword)): ?>
                    for "<strong><?php echo htmlspecialchars($keyword); ?></strong>"
                <?php endif; ?>
            </div>
            <div class="sort-wrapper">
                <label><i class="fas fa-sort-amount-down"></i> Sort by:</label>
                <select class="sort-select" id="sortSelect">
                    <option value="relevance" <?php echo $sort == 'relevance' ? 'selected' : ''; ?>>Most Recent</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>
        </div>
        
        <!-- Products Grid -->
        <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-badge">
                                <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-row">
                                <span class="product-current-bid"><?php echo formatPrice($product['highest_bid'] ?? $product['starting_price']); ?></span>
                                <span class="product-starting"><?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>Try adjusting your search criteria or browse all categories.</p>
                    <a href="search.php" class="product-btn" style="display: inline-block; padding: 12px 28px;">Clear All Filters</a>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?keyword=<?php echo urlencode($keyword); ?>&category=<?php echo $category_id; ?>&min_price=<?php echo $min_price; ?>&max_price=<?php echo $max_price; ?>&sort=<?php echo $sort; ?>&page=<?php echo $page - 1; ?>"><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="?keyword=' . urlencode($keyword) . '&category=' . $category_id . '&min_price=' . $min_price . '&max_price=' . $max_price . '&sort=' . $sort . '&page=1">1</a>';
                    if ($start_page > 2) echo '<span style="padding: 8px 6px;">...</span>';
                }
                
                for ($i = $start_page; $i <= $end_page; $i++): ?>
                    <a href="?keyword=<?php echo urlencode($keyword); ?>&category=<?php echo $category_id; ?>&min_price=<?php echo $min_price; ?>&max_price=<?php echo $max_price; ?>&sort=<?php echo $sort; ?>&page=<?php echo $i; ?>" 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="?keyword=' . urlencode($keyword) . '&category=' . $category_id . '&min_price=' . $min_price . '&max_price=' . $max_price . '&sort=' . $sort . '&page=' . $total_pages . '">' . $total_pages . '</a>';
                }
                ?>
                
                <?php if ($page < $total_pages): ?>
                    <a href="?keyword=<?php echo urlencode($keyword); ?>&category=<?php echo $category_id; ?>&min_price=<?php echo $min_price; ?>&max_price=<?php echo $max_price; ?>&sort=<?php echo $sort; ?>&page=<?php echo $page + 1; ?>">Next <i class="fas fa-chevron-right"></i></a>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Sort select change handler
document.getElementById('sortSelect').addEventListener('change', function() {
    const url = new URL(window.location.href);
    url.searchParams.set('sort', this.value);
    url.searchParams.set('page', '1');
    window.location.href = url.toString();
});

// Update countdown timers
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'; ?>