<?php
include("config.inc.php");
include("header.php");
// Pagination setup
$papersPerPage = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $papersPerPage;

// Fetch e-papers for the current page
$sql = "SELECT p_id, p_name, p_date, p_type, p_status, p_path FROM epapers ORDER BY p_id DESC LIMIT $offset, $papersPerPage";
$result = $conn->query($sql);

// Get the total number of e-papers
$totalResult = $conn->query("SELECT COUNT(*) AS total FROM epapers");
$totalPapers = $totalResult->fetch_assoc()['total'];
$totalPages = ceil($totalPapers / $papersPerPage);
?>

    <div class="container mt-5">
        <h1 class="mb-4">List of E-Papers</h1>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Title</th>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['p_id']; ?></td>
                            <td><?php echo htmlspecialchars($row['p_name']); ?></td>
                            <td><?php echo date("d-m-Y", strtotime($row['p_date'])); ?></td>
                            <td><?php echo $row['p_type']; ?></td>
                            <td><?php echo $row['p_status']; ?></td>
                            <td>
                                <a href="edit_epaper.php?id=<?php echo $row['p_id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                                <a href="delete_epaper.php?id=<?php echo $row['p_id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this e-paper?');">Delete</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" class="text-center">No E-Papers Found</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <nav>
            <ul class="pagination justify-content-center">
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                        <a class="page-link" href="list-epapers.php?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>
    </div>
<?php 
$conn->close(); 
include("footer.php");
?>