<?php
session_start();
require 'config/db.php';
require_once 'includes/functions.php'; // Essential for currency conversion
include 'includes/header.php';

$query = isset($_GET['q']) ? trim($_GET['q']) : '';
$results = [];

if ($query) {
    // Search in Name OR Description
    $stmt = $pdo->prepare("SELECT * FROM products WHERE (name LIKE ? OR description LIKE ?) AND is_active = 1");
    $searchTerm = "%" . $query . "%";
    $stmt->execute([$searchTerm, $searchTerm]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Optional: Log the search keyword for Analytics
    try {
        // Create search_logs table if not exists to prevent crash
        $pdo->query("CREATE TABLE IF NOT EXISTS search_logs (id INT AUTO_INCREMENT PRIMARY KEY, keyword VARCHAR(255), result_count INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
        
        $logStmt = $pdo->prepare("INSERT INTO search_logs (keyword, result_count) VALUES (?, ?)");
        $logStmt->execute([$query, count($results)]);
    } catch (Exception $e) { /* Silent fail */ }
}
?>

<div class="container" style="min-height: 60vh; padding-top: 30px;">
    
    <h1 style="border-bottom: 2px solid #eee; padding-bottom: 15px; margin-bottom: 20px;">
        Search Results for "<span style="color: #3498db;"><?php echo htmlspecialchars($query); ?></span>"
    </h1>
    <p style="color: #666; margin-bottom: 30px;">Found <?php echo count($results); ?> products.</p>

    <?php if (count($results) > 0): ?>
        <div class="product-grid">
            <?php foreach ($results as $product): 
                // 1. Fetch Lowest Price
                $pStmt = $pdo->prepare("SELECT MIN(price) as min_price FROM product_variants WHERE product_id = ?");
                $pStmt->execute([$product['id']]);
                $priceData = $pStmt->fetch();
                $price = $priceData['min_price'] ? $priceData['min_price'] : 0;
                
                // 2. Fix Link Structure
                $link = "product.php?id=" . $product['id'];
            ?>
                <div class="card">
                    <a href="<?php echo $link; ?>">
                        <img src="<?php echo !empty($product['thumbnail_url']) ? $product['thumbnail_url'] : 'assets/images/no-image.png'; ?>" 
                             alt="<?php echo htmlspecialchars($product['name']); ?>" loading="lazy">
                    </a>
                    
                    <h3><?php echo htmlspecialchars($product['name']); ?></h3>
                    
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">
                        <span style="color: #666; font-size: 13px;">Starting at:</span>
                        <span class="price" style="font-size: 18px; color: #2c3e50; font-weight: bold;">
                            <!-- Currency Conversion -->
                            <?php echo convertPrice($price); ?>
                        </span>
                    </div>

                    <?php if(isset($_SESSION['user_id'])): ?>
                        <a href="<?php echo $link; ?>" class="btn-view">View Details</a>
                    <?php else: ?>
                        <a href="login.php" class="btn-view" style="background: #e67e22;">
                            <i class="fas fa-lock"></i> Login to View
                        </a>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>

    <?php else: ?>
        <!-- No Results Found -->
        <div style="text-align: center; margin-top: 50px; background: #f9f9f9; padding: 40px; border-radius: 8px;">
            <i class="fas fa-search" style="font-size: 50px; color: #ccc; margin-bottom: 20px;"></i>
            <h3 style="color: #555;">No products found.</h3>
            <p style="color: #777;">Try searching for "Adobe", "Windows", or "Canva".</p>
            <a href="index.php" class="btn btn-primary" style="width: auto; display: inline-block; margin-top: 20px; padding: 10px 30px;">
                View All Products
            </a>
        </div>
    <?php endif; ?>

</div>

<?php include 'includes/footer.php'; ?>