<?php
require_once '../init.php';

// Pagination setup
$itemsPerPage = 10;
$currentPage = max(1, intval($_GET['page'] ?? 1));
$offset = ($currentPage - 1) * $itemsPerPage;

// Get total products count
$totalProducts = $database->selectOne(
    "SELECT COUNT(*) as count FROM products WHERE user_id = ? AND is_active = 1",
    [$_SESSION['user_id']]
);
$totalCount = $totalProducts['count'] ?? 0;
$totalPages = ceil($totalCount / $itemsPerPage);

// Ensure current page is valid
if ($currentPage > $totalPages && $totalPages > 0) {
    $currentPage = $totalPages;
    $offset = ($currentPage - 1) * $itemsPerPage;
}

// Get products for current page (same as POS)
$products = $database->select(
    "SELECT * FROM products WHERE user_id = ? AND is_active = 1 ORDER BY name ASC LIMIT " . intval($itemsPerPage) . " OFFSET " . intval($offset),
    [$_SESSION['user_id']]
);

$canManage = $_SESSION['role'] === 'admin' || (isset($subsStats) && $subsStats['is_active']);

$pageTitle = 'Daftar Produk - KasirMurah.biz.id';
?>
<?php include '../layout/header.php'; ?>
    <?php include '../layout/navbar.php'; ?>

    <div class="container-fluid mt-4 px-3 px-md-4" style="max-width:900px;margin-left:auto;margin-right:auto;">
        <div class="page-header">
            <h1><i class="fas fa-box me-2" style="color:var(--primary)"></i>Daftar Produk</h1>
            <?php if ($canManage): ?>
            <a href="create.php" class="btn btn-primary">
                <i class="fas fa-plus me-1"></i> Tambah Produk
            </a>
            <?php else: ?>
            <a href="<?php echo APP_URL; ?>/subscription/upgrade.php" class="btn btn-warning">
                <i class="fas fa-crown me-1"></i> Upgrade untuk Tambah Produk
            </a>
            <?php endif; ?>
        </div>

        <?php if (!$canManage): ?>
        <div class="alert alert-warning d-flex align-items-center gap-2 mb-3">
            <i class="fas fa-lock"></i>
            <span>Langganan Anda tidak aktif. <a href="<?php echo APP_URL; ?>/subscription/upgrade.php">Upgrade sekarang</a> untuk menambah dan mengedit produk.</span>
        </div>
        <?php endif; ?>

        <?php if (empty($products)): ?>
        <div class="card">
            <div class="card-body text-center py-5">
                <i class="fas fa-box fa-3x mb-3 d-block" style="color:var(--primary-light)"></i>
                <p class="text-muted mb-3">Belum ada produk.</p>
                <?php if ($canManage): ?>
                <a href="create.php" class="btn btn-primary">Tambah produk pertama</a>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0 table-mobile-card">
                        <thead>
                            <tr>
                                <th>SKU</th>
                                <th>Nama Produk</th>
                                <th>Kategori</th>
                                <th>Harga Jual</th>
                                <th>Stok</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($products as $prod): ?>
                            <tr>
                                <td data-label="SKU"><small class="font-monospace text-muted"><?php echo htmlspecialchars($prod['sku']); ?></small></td>
                                <td data-label="Nama"><strong><?php echo htmlspecialchars($prod['name']); ?></strong></td>
                                <td data-label="Kategori"><?php echo htmlspecialchars($prod['category'] ?: '—'); ?></td>
                                <td data-label="Harga" style="color:var(--primary);font-weight:700"><?php echo Helper::formatCurrency($prod['selling_price']); ?></td>
                                <td data-label="Stok">
                                    <span class="badge <?php echo $prod['quantity'] < 10 ? 'bg-danger' : 'bg-success'; ?>">
                                        <?php echo $prod['quantity']; ?>
                                    </span>
                                </td>
                                <td data-label="Aksi">
                                    <?php if ($canManage): ?>
                                    <div class="d-flex gap-2 flex-wrap">
                                        <a href="edit.php?id=<?php echo $prod['id']; ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        <form method="POST" action="delete.php" class="d-inline"
                                              onsubmit="return confirm('Hapus produk ini?')">
                                            <input type="hidden" name="id" value="<?php echo $prod['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-trash"></i> Hapus
                                            </button>
                                        </form>
                                    </div>
                                    <?php else: ?>
                                    <span class="text-muted small"><i class="fas fa-lock me-1"></i>Terkunci</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <!-- Previous button -->
                        <li class="page-item <?php echo $currentPage === 1 ? 'disabled' : ''; ?>">
                            <a class="page-link" href="<?php echo $currentPage > 1 ? '?page=' . ($currentPage - 1) : '#'; ?>">
                                <i class="fas fa-chevron-left me-1"></i> Sebelumnya
                            </a>
                        </li>

                        <!-- Page numbers -->
                        <?php
                        $startPage = max(1, $currentPage - 2);
                        $endPage = min($totalPages, $currentPage + 2);

                        if ($startPage > 1) {
                            echo '<li class="page-item"><a class="page-link" href="?page=1">1</a></li>';
                            if ($startPage > 2) {
                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                            }
                        }

                        for ($i = $startPage; $i <= $endPage; $i++) {
                            $active = $i === $currentPage ? 'active' : '';
                            echo "<li class=\"page-item {$active}\"><a class=\"page-link\" href=\"?page={$i}\">{$i}</a></li>";
                        }

                        if ($endPage < $totalPages) {
                            if ($endPage < $totalPages - 1) {
                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                            }
                            echo '<li class="page-item"><a class="page-link" href="?page=' . $totalPages . '">' . $totalPages . '</a></li>';
                        }
                        ?>

                        <!-- Next button -->
                        <li class="page-item <?php echo $currentPage === $totalPages ? 'disabled' : ''; ?>">
                            <a class="page-link" href="<?php echo $currentPage < $totalPages ? '?page=' . ($currentPage + 1) : '#'; ?>">
                                Selanjutnya <i class="fas fa-chevron-right ms-1"></i>
                            </a>
                        </li>
                    </ul>
                </nav>

                <!-- Pagination info -->
                <div class="text-center text-muted small mt-3">
                    Menampilkan <?php echo count($products) > 0 ? $offset + 1 : 0; ?>
                    sampai <?php echo min($offset + $itemsPerPage, $totalCount); ?>
                    dari <strong><?php echo $totalCount; ?></strong> produk
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <?php include '../layout/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
