<?php
// search.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';

$search_term = $_GET['q'] ?? '';

if ($search_term) {
    $stmt = $pdo->prepare("SELECT p.*, c.name as category_name 
                          FROM products p 
                          LEFT JOIN categories c ON p.category_id = c.id 
                          WHERE p.status = 1 
                          AND (p.name LIKE ? OR p.description LIKE ? OR p.product_code LIKE ?)
                          ORDER BY p.created_at DESC");
    $search = "%$search_term%";
    $stmt->execute([$search, $search, $search]);
    $products = $stmt->fetchAll();
} else {
    $products = [];
}

include __DIR__ . '/includes/header.php';
?>

<div class="container py-4">
    <h4>Search Results for "<?php echo htmlspecialchars($search_term); ?>"</h4>
    <hr>
    
    <?php if (empty($products)): ?>
    <div class="alert alert-info">No products found matching your search.</div>
    <?php else: ?>
    <div class="row g-2 g-lg-3">
        <?php foreach ($products as $product): ?>
        <div class="col-xxl-3 col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4">
            <div class="product-card">
                <div class="image">
                    <a href="product.php?slug=<?php echo $product['slug']; ?>">
                        <img src="assets/images/products/<?php echo $product['image'] ?: 'default.jpg'; ?>" alt="<?php echo $product['name']; ?>">
                    </a>
                    <?php if ($product['sale_price']): ?>
                    <span class="discount">-<?php echo round((1 - $product['sale_price']/$product['price']) * 100); ?>%</span>
                    <?php endif; ?>
                </div>
                <div class="content">
                    <a href="product.php?slug=<?php echo $product['slug']; ?>" class="name"><?php echo $product['name']; ?></a>
                    <div class="price">
                        <span class="current"><?php echo number_format($product['sale_price'] ?: $product['price']); ?> TK</span>
                        <?php if ($product['sale_price']): ?>
                        <span class="old"><?php echo number_format($product['price']); ?> TK</span>
                        <?php endif; ?>
                    </div>
                    <a href="product.php?slug=<?php echo $product['slug']; ?>" class="btn-order">View Details</a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>