<?php require_once '../includes/header.php'; 

// Pagination & search
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

$search = $_GET['search'] ?? '';
$categoryFilter = $_GET['category'] ?? '';

$where = "WHERE 1=1";
$params = [];

if ($search !== '') {
    // Escape special characters for LIKE (makes literal search safe)
    $escapedSearch = addcslashes($search, '%_');
    $where .= " AND (p.name LIKE :search OR p.product_code LIKE :search2)";
    $params[':search'] = "%$escapedSearch%";
    $params[':search2'] = "%$escapedSearch%";
}
if ($categoryFilter !== '') {
    $where .= " AND p.category_id = :cat";
    $params[':cat'] = (int)$categoryFilter;
}

// Total count
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM products p $where");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$totalPages = ceil($total / $perPage);

// Fetch products
$dataStmt = $pdo->prepare("
    SELECT p.*, c.name AS category_name, b.name AS brand_name
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    LEFT JOIN brands b ON p.brand_id = b.id
    $where
    ORDER BY p.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$dataStmt->execute($params);
$products = $dataStmt->fetchAll();

// Categories for filter dropdown
$catList = $pdo->query("SELECT id, name FROM categories ORDER BY name")->fetchAll();
?>

<h1 class="h2 mb-4">Products</h1>

<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Filter & Search -->
<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-4">
                <label class="form-label">Search</label>
                <input type="text" name="search" class="form-control" placeholder="Name or code" value="<?= htmlspecialchars($search) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Category</label>
                <select name="category" class="form-select">
                    <option value="">All</option>
                    <?php foreach ($catList as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= $categoryFilter == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary">Filter</button>
                <a href="products.php" class="btn btn-outline-secondary">Reset</a>
            </div>
            <div class="col-md-3 text-end">
                <a href="product_add.php" class="btn btn-success"><i class="bi bi-plus-circle"></i> Add Product</a>
            </div>
        </form>
    </div>
</div>

<!-- Products Table -->
<div class="card shadow-sm">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Thumb</th>
                        <th>Product Name</th>
                        <th>Code</th>
                        <th>Category</th>
                        <th>Stock</th>
                        <th>Sell Price</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($products)): ?>
                    <tr><td colspan="9" class="text-center py-3">No products found.</td></tr>
                <?php else: foreach ($products as $p): ?>
                    <tr>
                        <td><?= $p['id'] ?></td>
                        <td>
                            <?php if ($p['thumbnail_url']): ?>
                                <!-- ✅ Use the full URL directly, no ../assets/uploads/ prefix -->
                                <img src="<?= htmlspecialchars($p['thumbnail_url']) ?>" width="40" height="40" style="object-fit:cover;" class="rounded">
                            <?php else: ?>
                                <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($p['name']) ?></td>
                        <td><?= htmlspecialchars($p['product_code']) ?></td>
                        <td><?= htmlspecialchars($p['category_name'] ?? '—') ?></td>
                        <td>
                            <?= $p['stock_qty'] ?>
                            <?= $p['is_in_stock'] ? '<span class="badge bg-success ms-1">In Stock</span>' : '<span class="badge bg-danger ms-1">Out of Stock</span>' ?>
                        </td>
                        <td>৳<?= number_format($p['default_sell_price'], 2) ?></td>
                        <td>
                            <?= $p['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>' ?>
                            <?php if ($p['section_tag']): ?>
                                <span class="badge bg-info text-dark"><?= htmlspecialchars($p['section_tag']) ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <a href="product_edit.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-warning"><i class="bi bi-pencil"></i></a>
                            <a href="product_delete.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this product?')"><i class="bi bi-trash"></i></a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Pagination -->
<?php if ($totalPages > 1): ?>
<nav class="mt-4">
    <ul class="pagination justify-content-center">
        <li class="page-item <?= $page == 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&category=<?= $categoryFilter ?>">&laquo;</a>
        </li>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&category=<?= $categoryFilter ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>
        <li class="page-item <?= $page == $totalPages ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&category=<?= $categoryFilter ?>">&raquo;</a>
        </li>
    </ul>
</nav>
<?php endif; ?>

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