<?php
include("dashboard/config.inc.php");

// Pagination setup
$papersPerPage = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1; // Ensure page is at least 1
$offset = ($page - 1) * $papersPerPage; // Correct offset


// Fetch papers
$sql = "SELECT * FROM epapers WHERE p_status='Published' ORDER BY p_id DESC LIMIT $offset, $papersPerPage";
$result = $conn->query($sql);

// Total papers count for pagination
$countResult = $conn->query("SELECT COUNT(*) AS total FROM epapers WHERE p_status='Published'");
$totalPapers = $countResult->fetch_assoc()['total'];
$totalPages = ceil($totalPapers / $papersPerPage);

$data = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $datax = $row;
        if(file_exists("dashboard/covers/".$row['p_path'].".jpg")){
            $datax['img_url'] = "dashboard/covers/".$row['p_path'].".jpg";

        }
        else {
            $datax['img_url'] = "dashboard/covers/cover.png";
        }
        

        $data[] = $datax;

       
    }
}

// Response
header('Content-Type: application/json');
echo json_encode(['papers' => $data, 'totalPages' => $totalPages]);

$conn->close();
?>
