<?php
// attrbar.php
require_once __DIR__ . '/lib/bootstrap.php';
$conn = db_connect();
$currentCategory = isset($_GET['category']) ? $_GET['category'] : 'all';

$catId = null;
$categoriesConfig = [
    'iphone'  => 20,
    'ipad'    => 21,
    'macbook' => 22,
    'airpods' => 23,
    'accessories' => 24,
];

if (isset($categoriesConfig[$currentCategory])) {
    $catId = $categoriesConfig[$currentCategory];
}

// Fetch available attributes for the category if selected
$attributes = [];
if ($catId) {
    // Show attributes related to the active category
    $stmtAttr = $conn->prepare("
        SELECT a.attributeID, a.name, a.unit, a.dataType
        FROM attributes a
        JOIN categoryAttributes ca ON a.attributeID = ca.attributeID
        WHERE ca.categoryID = ?
        ORDER BY a.name
    ");
    $stmtAttr->bind_param("i", $catId);
    $stmtAttr->execute();
    $resAttr = $stmtAttr->get_result();
    while ($row = $resAttr->fetch_assoc()) {
        $attributes[] = $row;
    }
    $stmtAttr->close();
}
?>

<?php if (!empty($attributes)): ?>
<div class="attrbar" aria-label="Attributfilter">
    <div class="attrbar__inner container">
        <form action="index.php" method="GET" class="attr-filter-form">
            <?php if (isset($_GET['category'])): ?>
                <input type="hidden" name="category" value="<?= htmlspecialchars($_GET['category']) ?>">
            <?php endif; ?>
            <?php if (isset($_GET['search'])): ?>
                <input type="hidden" name="search" value="<?= htmlspecialchars($_GET['search']) ?>">
            <?php endif; ?>

            <?php foreach ($attributes as $attr): 
                $attrId = $attr['attributeID'];
                $attrName = $attr['name'] . ($attr['unit'] ? ' (' . $attr['unit'] . ')' : '');
                
                // Fetch distinct values for this attribute based on current category
                if ($catId) {
                    $vStmt = $conn->prepare("
                        SELECT DISTINCT pa.valueString, pa.valueNumber, pa.valueBool
                        FROM productAttributes pa
                        JOIN products p ON pa.productID = p.productID
                        WHERE p.categoryID = ? AND pa.attributeID = ?
                    ");
                    $vStmt->bind_param("ii", $catId, $attrId);
                } else {
                    $vStmt = $conn->prepare("
                        SELECT DISTINCT valueString, valueNumber, valueBool
                        FROM productAttributes
                        WHERE attributeID = ?
                    ");
                    $vStmt->bind_param("i", $attrId);
                }
                $vStmt->execute();
                $vRes = $vStmt->get_result();
                $values = [];
                while ($vRow = $vRes->fetch_assoc()) {
                    if ($attr['dataType'] === 'boolean' || $vRow['valueBool'] !== null) {
                        $val = $vRow['valueBool'] ? 'Ja' : 'Nein';
                        if (!in_array($val, $values)) $values[] = $val;
                    } elseif ($attr['dataType'] === 'number' || $vRow['valueNumber'] !== null) {
                        $val = $vRow['valueNumber'];
                        // strip trailing zero for decimals if desired, e.g. 5.00 -> 5
                        $val = rtrim(rtrim((string)$val, '0'), '.');
                        if (!in_array($val, $values)) $values[] = $val;
                    } elseif ($vRow['valueString'] !== null) {
                        $val = $vRow['valueString'];
                        if (!in_array($val, $values)) $values[] = $val;
                    }
                }
                $vStmt->close();
                
                // Sort values
                if ($attr['dataType'] === 'number') {
                    usort($values, function($a, $b) { return (float)$a <=> (float)$b; });
                } else {
                    sort($values);
                }
                
                if (empty($values)) continue;
                $paramName = "attr_" . $attrId;
                $selectedValue = isset($_GET[$paramName]) ? $_GET[$paramName] : '';
            ?>
                <div class="attr-filter-item">
                    <label for="attr_<?= $attrId ?>"><?= htmlspecialchars($attrName) ?>:</label>
                    <select name="<?= $paramName ?>" id="attr_<?= $attrId ?>" onchange="this.form.submit()">
                        <option value="">Alle</option>
                        <?php foreach ($values as $val): ?>
                            <option value="<?= htmlspecialchars($val) ?>" <?= (string)$val === (string)$selectedValue ? 'selected' : '' ?>>
                                <?= htmlspecialchars($val) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            <?php endforeach; ?>
            
            <noscript>
                <button type="submit">Filtern</button>
            </noscript>
            <?php 
            // Show reset button only if at least one attr filter is active
            $hasActiveFilter = false;
            foreach ($_GET as $k => $v) {
                if (strpos($k, 'attr_') === 0 && $v !== '') {
                    $hasActiveFilter = true;
                    break;
                }
            }
            if ($hasActiveFilter): ?>
                <div class="attr-filter-action">
                    <a href="index.php<?= isset($_GET['category']) ? '?category='.urlencode($_GET['category']) : '' ?>" class="attr-filter-reset">Filter zurücksetzen</a>
                </div>
            <?php endif; ?>
        </form>
    </div>
</div>
<?php endif; ?>

