<?php
require("mainconfig.php");

// Assuming you have the database connection established already

// Function to calculate the total number of pages based on the number of records per page
function getTotalPages($totalRecords, $recordsPerPage) {
    return ceil($totalRecords / $recordsPerPage);
}

$recordsPerPage = isset($_GET['recordsPerPage']) ? intval($_GET['recordsPerPage']) : 5;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;

// Calculate the OFFSET for the current page
$offset = ($page - 1) * $recordsPerPage;

// Fetch data from the 'news' table for the current page
$query = "SELECT * FROM news ORDER BY date DESC LIMIT $recordsPerPage OFFSET $offset";
$result = mysqli_query($db, $query);

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = array(
        "date" => $row['date'],
        "content" => $row['content']
    );
}

// Get the total number of records in the 'news' table
$totalRecordsQuery = "SELECT COUNT(*) AS total FROM news";
$totalRecordsResult = mysqli_query($db, $totalRecordsQuery);
$totalRecordsRow = mysqli_fetch_assoc($totalRecordsResult);
$totalRecords = $totalRecordsRow['total'];

// Calculate total pages
$totalPages = getTotalPages($totalRecords, $recordsPerPage);

// Return data as JSON
echo json_encode(array(
    "news" => $data,
    "totalPages" => $totalPages
));
?>
