<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));

$allowedLimits = [10, 25, 50, 100];
$limit = (int)($_GET['limit'] ?? 10);

if (!in_array($limit, $allowedLimits)) {
    $limit = 10;
}

$offset = ($page - 1) * $limit;

/*
    COUNT QUERY
*/
$countSql = "SELECT COUNT(*) FROM items";
$countParams = [];

if (!empty($search)) {
    $countSql .= " WHERE name LIKE ? OR barcode LIKE ?";
    $countParams[] = "%$search%";
    $countParams[] = "%$search%";
}

$stmt = $db->prepare($countSql);
$stmt->execute($countParams);
$totalItems = $stmt->fetchColumn();

$totalPages = ceil($totalItems / $limit);

/*
    MAIN QUERY
*/
$sql = "
    SELECT
        i.*,
        c.name AS category_name,
        u.name AS unit_name
    FROM items i
    LEFT JOIN categories c ON i.category_id = c.id
    LEFT JOIN units u ON i.unit_id = u.id
";

$params = [];

if (!empty($search)) {
    $sql .= " WHERE i.name LIKE ? OR i.barcode LIKE ?";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$sql .= " ORDER BY i.name ASC LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="card shadow-sm">
    <div class="card-body table-responsive">

        <table class="table table-bordered table-hover align-middle">

            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>Item Name</th>
                    <th>Category</th>
                    <th>Barcode</th>
                    <th>Unit</th>
                    <th>Current Stock</th>
                </tr>
            </thead>

            <tbody>

            <?php if (empty($items)): ?>
                <tr>
                    <td colspan="6" class="text-center">
                        No stock items found.
                    </td>
                </tr>
            <?php endif; ?>

            <?php foreach ($items as $item): ?>
                <tr>
                    <td><?= $item['id'] ?></td>

                    <td><?= htmlspecialchars($item['name']) ?></td>

                    <td><?= htmlspecialchars($item['category_name'] ?? '') ?></td>

                    <td><?= htmlspecialchars($item['barcode']) ?></td>

                    <td><?= htmlspecialchars($item['unit_name'] ?? '') ?></td>

                    <td>
                        <strong>
                            <?= number_format((float)$item['stock'], 2) ?>
                        </strong>
                    </td>
                </tr>
            <?php endforeach; ?>

            </tbody>

        </table>

        <!-- PAGINATION -->
        <?php if ($totalPages > 1): ?>
            <nav>
                <ul class="pagination justify-content-center">

                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <button
                                class="page-link"
                                onclick="loadStock(<?= $page - 1 ?>)"
                            >
                                Previous
                            </button>
                        </li>
                    <?php endif; ?>

                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?= $page == $i ? 'active' : '' ?>">
                            <button
                                class="page-link"
                                onclick="loadStock(<?= $i ?>)"
                            >
                                <?= $i ?>
                            </button>
                        </li>
                    <?php endfor; ?>

                    <?php if ($page < $totalPages): ?>
                        <li class="page-item">
                            <button
                                class="page-link"
                                onclick="loadStock(<?= $page + 1 ?>)"
                            >
                                Next
                            </button>
                        </li>
                    <?php endif; ?>

                </ul>
            </nav>
        <?php endif; ?>

    </div>
</div>