<?php
// login.php

require_once __DIR__ . '/lib/bootstrap.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 1) DB-Verbindung (einmal)
$conn = db_connect();
?>

<?php
// ─────────────────────────────────────────────
// Reine PHP-Suche (GET ?search=...)
// Wenn ein Suchbegriff vorhanden ist, zeigen wir nur Suchergebnisse
// (statt der Kategorie-Sektionen).
// ─────────────────────────────────────────────
$searchTerm = isset($_GET['search']) ? trim((string)$_GET['search']) : '';
$searchLen = function_exists('mb_strlen') ? mb_strlen($searchTerm, 'UTF-8') : strlen($searchTerm);
if ($searchTerm !== '') {
    $like = addcslashes($searchTerm, "%_\\");
    $like = '%' . $like . '%';

    $stmtSearch = $conn->prepare("
        SELECT productID, model, description, imagePath
        FROM products
        WHERE model LIKE ? OR description LIKE ?
        ORDER BY model ASC
        LIMIT 60
    ");

    if ($stmtSearch) {
        $stmtSearch->bind_param('ss', $like, $like);
        $stmtSearch->execute();
        $resultSearch = $stmtSearch->get_result();
        ?>

        <section class="product-section">
            <h2>Suchergebnisse für „<?= htmlspecialchars($searchTerm) ?>“</h2>

            <?php if ($resultSearch->num_rows <= 0): ?>
                <p class="search-empty">Keine Produkte gefunden.</p>
            <?php else: ?>
                <div class="product-grid">
                    <?php while ($product = $resultSearch->fetch_assoc()): ?>
                        <?php $productId = (int)$product['productID']; ?>
                        <a class="product-card" href="productpage.php?id=<?= $productId ?>">
                            <img
                                src="<?= !empty($product['imagePath']) ? htmlspecialchars($product['imagePath']) : 'assets/images/placeholder.png' ?>"
                                alt="<?= htmlspecialchars($product['model'] ?? '') ?>">

                            <div class="product-card__content">
                                <h3><?= htmlspecialchars($product['model'] ?? '') ?></h3>
                                <p><?= htmlspecialchars($product['description'] ?? '') ?></p>
                            </div>
                        </a>
                    <?php endwhile; ?>
                </div>
            <?php endif; ?>
        </section>

        <?php
        $stmtSearch->close();
    }

    // Wichtig: In Suchmodus KEINE Kategorien rendern.
    return;
}
?>

<?php
$activeCategory = isset($_GET['category']) ? $_GET['category'] : 'all';
?>

<?php
$categories = [
        'iphone'  => ['id' => 20, 'label' => 'iPhone'],
        'ipad'    => ['id' => 21, 'label' => 'iPad'],
        'macbook' => ['id' => 22, 'label' => 'MacBook'],
        'airpods' => ['id' => 23, 'label' => 'AirPods'],
        'accessories' => ['id' => 24, 'label' => 'Accessories'],
];
?>




<?php foreach ($categories as $key => $cat): ?>

    <?php if ($activeCategory === 'all' || $activeCategory === $key): ?>

        <?php
        $baseQuery = "SELECT DISTINCT p.productID, p.model, p.description, p.imagePath FROM products p ";
        $whereClauses = ["p.categoryID = ?"];
        $params = [$cat['id']];
        $types = "i";
        
        // Find attribute filters from $_GET
        $attrIndex = 0;
        foreach ($_GET as $k => $v) {
            if ($v !== '' && strpos($k, 'attr_') === 0) {
                $attrId = (int)substr($k, 5);
                $attrAlias = "pa" . $attrIndex;
                $baseQuery .= " JOIN productAttributes $attrAlias ON p.productID = $attrAlias.productID ";
                
                // Assume string or number comparison. For simplicity, check string or number.
                // In DB, valueString, valueNumber, valueBool can be checked.
                $whereClauses[] = "($attrAlias.attributeID = ? AND ($attrAlias.valueString = ? OR $attrAlias.valueNumber = ? OR ($attrAlias.valueBool = 1 AND ? = 'Ja') OR ($attrAlias.valueBool = 0 AND ? = 'Nein')))";

                $params[] = $attrId;
                $params[] = $v;
                $params[] = is_numeric($v) ? (float)$v : 0;
                $params[] = $v;
                $params[] = $v;
                $types .= "isdss";
                
                $attrIndex++;
            }
        }
        
        $sql = $baseQuery . " WHERE " . implode(" AND ", $whereClauses);
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        ?>

        <?php if ($result->num_rows > 0): ?>
            <section class="product-section">
                <h2><?= htmlspecialchars($cat['label']) ?></h2>

                <div class="product-scroll">
                    <?php while ($product = $result->fetch_assoc()): ?>
                        <?php $productId = (int)$product['productID']; ?>
                        <a class="product-card" href="productpage.php?id=<?= $productId ?>">
                            <img
                                    src="<?= isset($product['imagePath']) ? $product['imagePath'] : 'assets/images/placeholder.png' ?>"
                                    alt="<?= htmlspecialchars($product['model']) ?>">

                            <div class="product-card__content">
                                <h3><?= htmlspecialchars($product['model']) ?></h3>
                                <p><?= htmlspecialchars($product['description']) ?></p>
                            </div>
                        </a>
                    <?php endwhile; ?>
                </div>
            </section>
        <?php endif; ?>

        <?php $stmt->close(); ?>

    <?php endif; ?>

<?php endforeach; ?>

