<?php
/**
 * ============================================================================
 * marketplace/search.php - Advanced Product Search
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Search Products';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get search query
$searchQuery = $_GET['q'] ?? '';
$category = $_GET['category'] ?? '';
$minPrice = $_GET['min_price'] ?? '';
$maxPrice = $_GET['max_price'] ?? '';
$location = $_GET['location'] ?? '';

// Build search query
$sql = "SELECT p.*, 
        u.full_name as seller_name, 
        u.phone_number as seller_phone,
        u.profile_picture as seller_avatar
        FROM products p
        JOIN users u ON p.seller_id = u.id
        WHERE p.status = 'available'";

$params = [];

if ($searchQuery) {
    $sql .= " AND (p.product_name LIKE ? OR p.description LIKE ?)";
    $params[] = "%{$searchQuery}%";
    $params[] = "%{$searchQuery}%";
}

if ($category) {
    $sql .= " AND p.category = ?";
    $params[] = $category;
}

if ($minPrice) {
    $sql .= " AND p.price_per_unit >= ?";
    $params[] = $minPrice;
}

if ($maxPrice) {
    $sql .= " AND p.price_per_unit <= ?";
    $params[] = $maxPrice;
}

if ($location) {
    $sql .= " AND p.location LIKE ?";
    $params[] = "%{$location}%";
}

$sql .= " ORDER BY p.created_at DESC LIMIT 50";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process images
foreach ($products as &$product) {
    $product['images'] = json_decode($product['images'], true) ?? [];
}

global $PRODUCT_CATEGORIES;

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Search Header -->
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="mb-3">
                <i class="bi bi-search text-primary"></i> Search Results
                <?php if ($searchQuery): ?>
                    for "<?php echo htmlspecialchars($searchQuery); ?>"
                <?php endif; ?>
            </h2>
            <p class="text-muted">
                Found <?php echo count($products); ?> product(s)
            </p>
        </div>
    </div>

    <!-- Search Form -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <form method="GET">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <input type="text" class="form-control" name="q" 
                                       placeholder="Search products..." 
                                       value="<?php echo htmlspecialchars($searchQuery); ?>">
                            </div>
                            <div class="col-md-2">
                                <select class="form-select" name="category">
                                    <option value="">All Categories</option>
                                    <?php foreach ($PRODUCT_CATEGORIES as $key => $cat): ?>
                                        <option value="<?php echo $key; ?>" 
                                                <?php echo $category === $key ? 'selected' : ''; ?>>
                                            <?php echo $cat['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <input type="number" class="form-control" name="min_price" 
                                       placeholder="Min Price" 
                                       value="<?php echo htmlspecialchars($minPrice); ?>">
                            </div>
                            <div class="col-md-2">
                                <input type="number" class="form-control" name="max_price" 
                                       placeholder="Max Price" 
                                       value="<?php echo htmlspecialchars($maxPrice); ?>">
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-search"></i> Search
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Results -->
    <div class="row">
        <?php if (!empty($products)): ?>
            <?php foreach ($products as $product): ?>
                <div class="col-sm-6 col-lg-4 col-xl-3 mb-4">
                    <div class="card h-100 border-0 shadow-sm hover-lift">
                        <!-- Product Image -->
                        <div class="position-relative">
                            <?php $firstImage = !empty($product['images']) ? $product['images'][0] : null; ?>
                            <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>">
                                <?php if ($firstImage): ?>
                                    <img src="<?php echo APP_URL . '/' . htmlspecialchars($firstImage); ?>" 
                                         class="card-img-top" 
                                         style="height: 200px; object-fit: cover;"
                                         alt="<?php echo htmlspecialchars($product['product_name']); ?>">
                                <?php else: ?>
                                    <div class="bg-light d-flex align-items-center justify-content-center" 
                                         style="height: 200px;">
                                        <i class="bi bi-image text-muted" style="font-size: 3rem;"></i>
                                    </div>
                                <?php endif; ?>
                            </a>
                            
                            <span class="position-absolute top-0 start-0 m-2 badge" 
                                  style="background-color: <?php echo getCategoryColor($product['category']); ?>">
                                <?php echo $PRODUCT_CATEGORIES[$product['category']]['name'] ?? $product['category']; ?>
                            </span>
                        </div>

                        <div class="card-body">
                            <h5 class="card-title">
                                <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" 
                                   class="text-decoration-none text-dark">
                                    <?php echo htmlspecialchars($product['product_name']); ?>
                                </a>
                            </h5>
                            
                            <p class="card-text text-muted small">
                                <?php echo truncate($product['description'], 60); ?>
                            </p>
                            
                            <div class="mb-2">
                                <h4 class="text-success mb-0">
                                    <?php echo formatCurrency($product['price_per_unit']); ?>
                                    <small class="text-muted fs-6">/ <?php echo htmlspecialchars($product['unit']); ?></small>
                                </h4>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center text-muted small">
                                <span>
                                    <i class="bi bi-box"></i> 
                                    <?php echo number_format($product['quantity'], 2); ?> <?php echo htmlspecialchars($product['unit']); ?>
                                </span>
                                <?php if ($product['location']): ?>
                                    <span>
                                        <i class="bi bi-geo-alt"></i> 
                                        <?php echo htmlspecialchars($product['location']); ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="card-footer bg-transparent border-top-0">
                            <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['id']; ?>" 
                               class="btn btn-sm btn-primary w-100">
                                <i class="bi bi-eye"></i> View Details
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-body text-center py-5">
                        <i class="bi bi-search text-muted" style="font-size: 4rem;"></i>
                        <h4 class="mt-3">No Products Found</h4>
                        <p class="text-muted">Try adjusting your search criteria</p>
                        <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-primary">
                            Browse All Products
                        </a>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
.hover-lift {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
}
</style>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>