<?php
include '../connection.php';

// Get the limit and page from the GET request, default to 10 records per page and page 1 if not provided
$limit = isset($_GET['limit']) ? $_GET['limit'] : 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// Adjust the limit and offset if "All" is selected
if ($limit === "All") {
    // If "All" is selected, set the limit to a large number (or remove pagination)
    $limit = PHP_INT_MAX; // This is a safe way to ensure you don't get an unlimited number of records (adjust according to your data)
    $offset = 0;  // No pagination needed
} else {
    // Calculate the offset for pagination
    $offset = ($page - 1) * $limit;
}

// SQL query to join items_allocation_office with the other tables, adding LIMIT and OFFSET for pagination
$sql = "
    SELECT iao.ID, iao.office_id, o.office_name, iao.item_id, i.item_name, iao.reciver_id, of.official_name, iao.reciving_date
    FROM items_allocation_office iao
    JOIN offices o ON iao.office_id = o.ID
    JOIN office_items_assets i ON iao.item_id = i.ID
    JOIN civil_court_officials of ON iao.reciver_id = of.ID
";

// If limit is not "All", apply the LIMIT and OFFSET
if ($limit !== "All") {
    $sql .= " LIMIT ? OFFSET ?";
}

// Prepare and execute the query with the limit and offset parameters
$stmt = $conn->prepare($sql);

// Bind the parameters for limit and offset if limit is not "All"
if ($limit !== "All") {
    $stmt->bind_param("ii", $limit, $offset); // "ii" for two integer parameters
}

$stmt->execute();

// Fetch the results
$result = $stmt->get_result();
$allocations = array();
while ($row = $result->fetch_assoc()) {
    $allocations[] = $row;
}

// Return the result as JSON
echo json_encode($allocations);

// Close the database connection
$conn->close();
?>
