<?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
*/
$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);

/*
    DATA
*/
$sql = "
    SELECT
        i.*,
        c.name AS category_name,
        u.name AS unit_name,
        t.name AS type_name
    FROM items i
    LEFT JOIN categories c ON i.category_id = c.id
    LEFT JOIN units u ON i.unit_id = u.id
    LEFT JOIN item_types t ON i.type_id = t.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>Image</th>
                    <th>Name</th>
                    <th>Category</th>
                    <th>Price</th>
                    <th>GST</th>
                    <th>Stock</th>
                    <th>Barcode</th>
                    <th>Unit</th>
                    <th>Type</th>
                    <th width="180">Actions</th>
                </tr>
            </thead>

            <tbody>

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

            <?php foreach ($items as $item): ?>

                <?php
                $imagePath = !empty($item['image_path'])
                    ? '../../assets/images/' . ltrim($item['image_path'], '/')
                    : '../../assets/images/no_image.jpg';
                ?>

                <tr>
                    <td><?= $item['id'] ?></td>

                    <td>
                        <img
                            src="<?= $imagePath ?>"
                            width="60"
                            height="60"
                            style="object-fit: cover;"
                            onerror="this.src='../../assets/images/no_image.jpg'"
                        >
                    </td>

                    <td><?= htmlspecialchars($item['name']) ?></td>
                    <td><?= htmlspecialchars($item['category_name'] ?? '') ?></td>
                    <td>₹ <?= number_format($item['price'], 2) ?></td>
                    <td><?= number_format($item['gst'], 2) ?></td>
                    <td><?= number_format($item['stock'], 2) ?></td>
                    <td><?= htmlspecialchars($item['barcode']) ?></td>
                    <td><?= htmlspecialchars($item['unit_name'] ?? '') ?></td>
                    <td><?= htmlspecialchars($item['type_name'] ?? '') ?></td>

                    <td>
                        <a
                            href="edit.php?id=<?= $item['id'] ?>"
                            class="btn btn-warning btn-sm"
                        >
                            Edit
                        </a>

                        <a
                            href="delete.php?id=<?= $item['id'] ?>"
                            class="btn btn-danger btn-sm"
                            onclick="return confirm('Delete this item?')"
                        >
                            Delete
                        </a>
                    </td>
                </tr>

            <?php endforeach; ?>

            </tbody>

        </table>

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

                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <button
                                class="page-link"
                                onclick="loadItems(<?= $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="loadItems(<?= $i ?>)"
                            >
                                <?= $i ?>
                            </button>
                        </li>
                    <?php endfor; ?>

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

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

    </div>
</div>