<?php
$conn = mysqli_connect('localhost', 'root', 'indev@123', 'bharat_impact');

$results_per_page = 12;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start_limit = ($page - 1) * $results_per_page;


$total_results = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM winner_and_finalist"));
$total_pages = ceil($total_results / $results_per_page);
$start_record = $start_limit + 1;

$end_record = min($start_limit + $results_per_page, $total_results);

 $record_count_html = "<h4>Total records: $total_results | Showing $start_record to $end_record of $total_results</h4>";


$data_query = mysqli_query($conn, "SELECT * FROM winner_and_finalist ORDER BY name ASC LIMIT $start_limit, $results_per_page");

$data_html = '<div class="row align-items-center g-3">';
while ($row = mysqli_fetch_array($data_query)) {
    $image_path = empty($row['path']) ? 'assets/images/no-image.jpg' : 'assets/images/winnerlist/' . $row['path'];
    $data_html .= '
        <div class="col-md-3">
            <div class="card community-card">
                <div class="icon">
                    <img src="' . $image_path . '" alt="' . $row['name'] . '" class="w-100">
                </div>
                <div class="card-body">
                    <h3 class="h5 fw-semi-bold"> ' . $row['name'] . ' </h3>
                    <p class="mb-0">' . $row['domain'] . ' </p>
                </div>
            </div>
        </div>';
}
$data_html .= '</div>';

$pagination_html = '';
if ($page > 1) {
    $pagination_html .= '<a href="#" class="page-link btn btn-secondary" data-page="' . ($page - 1) . '">Previous</a>';
}
for ($i = 1; $i <= $total_pages; $i++) {
    $active_class = ($i == $page) ? 'btn-primary' : 'btn-light';
    $pagination_html .= '<a href="#" class="page-link btn ' . $active_class . '" data-page="' . $i . '">' . $i . '</a>';
}
if ($page < $total_pages) {
    $pagination_html .= '<a href="#" class="page-link btn btn-secondary" data-page="' . ($page + 1) . '">Next</a>';
}

echo json_encode(['record_count' => $record_count_html, 'data' => $data_html, 'pagination' => $pagination_html]);
?>