<?php
require_once __DIR__ . '/../includes/header_customer.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$categories = $pdo->query('SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name')->fetchAll();

$categoryId = isset($_GET['category']) ? (int) $_GET['category'] : 0;
$search = trim($_GET['q'] ?? '');
$page = max(1, (int) ($_GET['p'] ?? 1));
$limit = 9;
$offset = ($page - 1) * $limit;

$where = ['is_active = 1'];
$params = [];

if ($categoryId > 0) {
    $where[] = 'category_id = ?';
    $params[] = $categoryId;
}

if ($search !== '') {
    $where[] = '(name LIKE ? OR description LIKE ?)';
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM products {$whereSql}");
$countStmt->execute($params);
$totalRows = (int) $countStmt->fetchColumn();
$totalPages = (int) ceil($totalRows / $limit);

$listStmt = $pdo->prepare("SELECT id, name, price, photo, stock FROM products {$whereSql} ORDER BY created_at DESC LIMIT {$limit} OFFSET {$offset}");
$listStmt->execute($params);
$products = $listStmt->fetchAll();
?>

<section class="mb-4">
    <h2 class="fw-bold">Produk</h2>
    <form class="row g-2" method="get" action="<?= base_url('public/index.php'); ?>">
        <input type="hidden" name="page" value="products">
        <div class="col-md-4">
            <select class="form-select" name="category">
                <option value="0">Semua Kategori</option>
                <?php foreach ($categories as $category): ?>
                    <option value="<?= (int) $category['id']; ?>" <?= $categoryId === (int) $category['id'] ? 'selected' : ''; ?>>
                        <?= sanitize($category['name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-6">
            <input class="form-control" type="text" name="q" placeholder="Cari produk" value="<?= sanitize($search); ?>">
        </div>
        <div class="col-md-2">
            <button class="btn w-100" type="submit">Filter</button>
        </div>
    </form>
</section>

<section>
    <div class="row g-4">
        <?php if (!$products): ?>
            <div class="col-12">
                <div class="alert error">Produk tidak ditemukan.</div>
            </div>
        <?php endif; ?>
        <?php foreach ($products as $product): ?>
            <div class="col-sm-6 col-lg-4">
                <a class="text-decoration-none text-dark" href="<?= base_url('public/index.php?page=product_detail&id=' . (int) $product['id']); ?>">
                    <div class="product-card">
                        <div class="product-image-wrapper">
                            <?php if (!empty($product['photo'])): ?>
                                <img src="<?= base_url('uploads/' . sanitize($product['photo'])); ?>" alt="<?= sanitize($product['name']); ?>">
                            <?php else: ?>
                                <div class="product-thumb">Al-Qanuni</div>
                            <?php endif; ?>
                            <div class="card-actions">
                                <span class="action-btn" title="Lihat Detail"><i class="bi bi-eye"></i></span>
                                <span class="action-btn" title="Beli Sekarang"><i class="bi bi-bag-plus"></i></span>
                            </div>
                        </div>
                        <div class="p-3">
                            <h6 class="fw-bold mb-1 text-truncate"><?= sanitize($product['name']); ?></h6>
                            <div class="small text-muted mb-1">Stok: <?= (int) $product['stock']; ?></div>
                            <div class="price-tag mb-2"><?= format_currency($product['price']); ?></div>
                            <span class="btn btn-sm w-100 btn-outline-primary">Detail Produk</span>
                        </div>
                    </div>
                </a>
            </div>
        <?php endforeach; ?>
    </div>
</section>

<?php if ($totalPages > 1): ?>
<nav class="mt-4">
    <ul class="pagination">
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <?php
                $query = http_build_query([
                    'page' => 'products',
                    'category' => $categoryId ?: null,
                    'q' => $search ?: null,
                    'p' => $i,
                ]);
            ?>
            <li class="page-item <?= $i === $page ? 'active' : ''; ?>">
                <a class="page-link" href="<?= base_url('public/index.php?' . $query); ?>"><?= $i; ?></a>
            </li>
        <?php endfor; ?>
    </ul>
</nav>
<?php endif; ?>

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