<?php
require_once __DIR__ . '/lib/bootstrap.php';
$conn = db_connect();

$title = "Produktvergleich | Geizkragen";
include 'header.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_compare'])) {
    $removeId = (int)$_POST['remove_compare_id'];
    if (isset($_SESSION['compare']) && is_array($_SESSION['compare'])) {
        foreach ($_SESSION['compare'] as $cat => &$prodList) {
            $key = array_search($removeId, $prodList);
            if ($key !== false) {
                unset($prodList[$key]);
            }
        }
        unset($prodList);
    }
}
?>

<div class="container compare-page">
    <h1 class="compare-title">Produktvergleich</h1>
    
    <?php
    $hasProducts = false;
    if (isset($_SESSION['compare']) && is_array($_SESSION['compare'])) {
        foreach ($_SESSION['compare'] as $categoryId => $productIds) {
            if (empty($productIds)) continue;
            $hasProducts = true;
            
            // Kategorie-Namen holen
            $catName = "Kategorie $categoryId";
            $stmtCat = $conn->prepare("SELECT name FROM categories WHERE categoryID = ?");
            if ($stmtCat) {
                $stmtCat->bind_param("i", $categoryId);
                $stmtCat->execute();
                $resCat = $stmtCat->get_result();
                if ($row = $resCat->fetch_assoc()) {
                    $catName = $row['name'];
                }
                $stmtCat->close();
            }
            
            // Attribute der Kategorie holen
            $attributes = [];
            $stmtAttr = $conn->prepare("
                SELECT a.attributeID, a.name, a.unit, a.dataType 
                FROM categoryAttributes ca
                JOIN attributes a ON ca.attributeID = a.attributeID
                WHERE ca.categoryID = ?
                ORDER BY a.attributeID
            ");
            if ($stmtAttr) {
                $stmtAttr->bind_param("i", $categoryId);
                $stmtAttr->execute();
                $resAttr = $stmtAttr->get_result();
                while ($row = $resAttr->fetch_assoc()) {
                    $attributes[$row['attributeID']] = $row;
                }
                $stmtAttr->close();
            }
            
            // Produktdaten holen
            $products = [];
            $idList = implode(',', array_map('intval', $productIds));
            $stmtProd = $conn->query("SELECT productID, model, imagePath, description FROM products WHERE productID IN ($idList)");
            if ($stmtProd) {
                while ($row = $stmtProd->fetch_assoc()) {
                    $products[$row['productID']] = $row;
                }
            }
            
            // Produktattribute holen
            $productAttrVals = [];
            $stmtProdAttr = $conn->query("SELECT productID, attributeID, valueString, valueNumber, valueBool FROM productAttributes WHERE productID IN ($idList)");
            if ($stmtProdAttr) {
                while ($row = $stmtProdAttr->fetch_assoc()) {
                    $productAttrVals[$row['productID']][$row['attributeID']] = $row;
                }
                $stmtProdAttr->close();
            }
            ?>
            
            <h2 class="compare-category-title"><?= htmlspecialchars($catName) ?></h2>
            
            <div class="compare-table-wrapper">
                <table class="compare-table">
                    <thead>
                        <tr>
                            <th>Eigenschaft</th>
                            <?php foreach ($productIds as $pId): ?>
                                <?php if (!isset($products[$pId])) continue; ?>
                                <th>
                                    <div>
                                        <a href="productpage.php?id=<?= $pId ?>">
                                            <img src="<?= htmlspecialchars($products[$pId]['imagePath'] ?? 'assets/images/placeholder.png') ?>" alt="Produktbild" class="compare-product-img">
                                        </a>
                                    </div>
                                    <h3><a href="productpage.php?id=<?= $pId ?>" class="compare-product-name"><?= htmlspecialchars($products[$pId]['model']) ?></a></h3>
                                    
                                    <form method="POST" action="compare.php">
                                        <input type="hidden" name="remove_compare" value="1">
                                        <input type="hidden" name="remove_compare_id" value="<?= $pId ?>">
                                        <button type="submit" class="compare-remove-btn">Entfernen</button>
                                    </form>
                                </th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Beschreibung</td>
                            <?php foreach ($productIds as $pId): ?>
                                <?php if (!isset($products[$pId])) continue; ?>
                                <td>
                                    <span class="desc-text"><?= htmlspecialchars($products[$pId]['description']) ?></span>
                                </td>
                            <?php endforeach; ?>
                        </tr>
                        <?php foreach ($attributes as $attrId => $attr): ?>
                            <tr>
                                <td><?= htmlspecialchars($attr['name'] ?? '') ?></td>
                                <?php foreach ($productIds as $pId): ?>
                                    <?php if (!isset($products[$pId])) continue; ?>
                                    <td>
                                        <?php
                                        if (isset($productAttrVals[$pId][$attrId])) {
                                            $valRow = $productAttrVals[$pId][$attrId];
                                            if (!empty($valRow['valueString'])) {
                                                echo htmlspecialchars($valRow['valueString'] ?? '');
                                            } elseif (!empty($valRow['valueNumber']) || $valRow['valueNumber'] === '0.00' || $valRow['valueNumber'] === 0) {
                                                echo htmlspecialchars((string)floatval($valRow['valueNumber'])) . " " . htmlspecialchars($attr['unit'] ?? '');
                                            } elseif ($valRow['valueBool'] !== null) {
                                                echo $valRow['valueBool'] ? 'Ja' : 'Nein';
                                            } else {
                                                echo '-';
                                            }
                                        } else {
                                            echo '-';
                                        }
                                        ?>
                                    </td>
                                <?php endforeach; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php
        }
    }
    
    if (!$hasProducts) {
        echo "<div class='compare-empty'><p>Du hast noch keine Produkte zum Vergleich hinzugefügt. Gehe auf eine Produktseite, um Produkte hinzuzufügen.</p></div>";
    }
    ?>
</div>

<?php include 'footer.php'; ?>
