<?php
ini_set('log_errors', 1);
ini_set('error_log', '/home/ubuntu/.gemini/tmp/ec2c6b8cb2ac3d6ef62b888a61e62d5ab1e71e46b3c4963f2a040a3c33c7038b/php_errors.log');
error_reporting(E_ALL);

require_once __DIR__ . '/includes/init.php';

$page_title = t('catalog_title');

require_once __DIR__ . '/includes/html_head.php';
require_once __DIR__ . '/includes/header.php';

try {
    $pdo = db();
    
    // Fetch products and their primary images
    $sql = "SELECT 
                p.*,
                (SELECT file_path 
                 FROM product_images 
                 WHERE product_id = p.id 
                 ORDER BY is_primary DESC, id ASC 
                 LIMIT 1) AS image_path
            FROM 
                products p
            WHERE 
                p.is_active = 1
            ORDER BY 
                CASE p.product_role WHEN 'membrana' THEN 1 WHEN 'akcesoria' THEN 2 ELSE 3 END, p.name ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Separate products into main and accessories
    $main_products = [];
    $accessories = [];
    foreach ($products as $product) {
        if ($product['product_role'] === 'akcesoria') {
            $accessories[] = $product;
        } else {
            $main_products[] = $product;
        }
    }
    
} catch (Exception $e) {
    $error = t('db_error') . $e->getMessage();
    $products = [];
    $main_products = [];
    $accessories = [];
}
?>

    <main class="container my-5">
        <h1 class="mb-4"><?= t('catalog_title') ?></h1>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4 g-4">
            <?php foreach ($main_products as $product): 
                        $prices = getEffectivePrice($pdo, $product['id'], $_SESSION['client_id'] ?? null);
                        if (isset($prices['net'])) {
                $image_url = !empty($product['image_path'])
                    ? 'uploads/products/' . htmlspecialchars($product['image_path'])
                    : 'https://placehold.co/600x400/EEE/31343C?text=' . t('no_image_placeholder');
                ?>
                <div class="col">
                    <div class="card h-100 product-card shadow-sm">
                        <a href="product.php?id=<?= (int)$product['id'] ?>">
                            <img src="<?= $image_url ?>" class="card-img-top" alt="<?= htmlspecialchars($product['name']) ?>" style="height: 200px; object-fit: cover;">
                        </a>
                        <div class="card-body d-flex flex-column">
                            <h5 class="card-title">
                                <a href="product.php?id=<?= (int)$product['id'] ?>" class="text-decoration-none text-dark">
                                    <?= htmlspecialchars($product['name']) ?>
                                </a>
                            </h5>
                            <p class="card-text text-secondary small flex-grow-1"><?php
                                $desc = $product['description'];
                                echo htmlspecialchars(strlen($desc) > 100 ? substr($desc, 0, 100) . '...' : $desc);
                            ?></p>
                            <div class="mt-auto">
                                <p class="card-text text-muted small mb-0"><?= format_money($prices['net'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <?= t('net') ?></p>
                                <p class="card-text fw-bold fs-5"><?= format_money($prices['gross'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <?= t('gross') ?></p>
                            </div>
                        </div>
                        <div class="card-footer bg-white border-top-0 pb-3">
                             <form action="cart_actions.php" method="POST" class="d-grid">
                                <input type="hidden" name="action" value="add">
                                <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                                <input type="hidden" name="redirect_to" value="index.php">
                                <div class="input-group">
                                    <input type="number" class="form-control" name="quantity" value="1" min="1" aria-label="<?= t('quantity_aria') ?>" step="1">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-cart-plus"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            <?php } endforeach; ?>
        </div>

        <?php if (!empty($accessories)): ?>
            <hr class="my-5">
            <h2 class="mb-4"><?= t('accessories_and_complementary_products') ?></h2>
            <div class="row row-cols-1 row-cols-sm-2 row-cols-md-4 row-cols-lg-5 g-4">
                <?php foreach ($accessories as $product):
                    $prices = getEffectivePrice($pdo, $product['id'], $_SESSION['client_id'] ?? null);
                    if (isset($prices['net'])) {
                    $image_url = !empty($product['image_path'])
                        ? 'uploads/products/' . htmlspecialchars($product['image_path'])
                        : 'https://placehold.co/600x400/EEE/31343C?text=' . t('no_image_placeholder');
                    ?>
                    <div class="col">
                        <div class="card h-100 product-card shadow-sm">
                            <a href="product.php?id=<?= (int)$product['id'] ?>">
                                <img src="<?= $image_url ?>" class="card-img-top" alt="<?= htmlspecialchars($product['name']) ?>" style="height: 150px; object-fit: cover;">
                            </a>
                            <div class="card-body d-flex flex-column">
                                <h6 class="card-title">
                                    <a href="product.php?id=<?= (int)$product['id'] ?>" class="text-decoration-none text-dark">
                                        <?= htmlspecialchars($product['name']) ?>
                                    </a>
                                </h6>
                                <div class="mt-auto">
                                    <p class="card-text text-muted small mb-0"><?= format_money($prices['net'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <?= t('net') ?></p>
                                    <p class="card-text fw-bold"><?= format_money($prices['gross'], $_SESSION['lang'] ?? 'pl', $pdo) ?> <?= t('gross') ?></p>
                                </div>
                            </div>
                            <div class="card-footer bg-white border-top-0 pb-3">
                                 <form action="cart_actions.php" method="POST" class="d-grid">
                                    <input type="hidden" name="action" value="add">
                                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                                    <input type="hidden" name="redirect_to" value="index.php">
                                    <div class="input-group">
                                        <input type="number" class="form-control form-control-sm" name="quantity" value="1" min="1" aria-label="<?= t('quantity_aria') ?>" step="1">
                                        <button type="submit" class="btn btn-sm btn-primary">
                                            <i class="bi bi-cart-plus"></i>
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php } endforeach; ?>
            </div>
        <?php endif; ?>

    </main>

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