<?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 = "$total_results";
$showing_html = "Showing results from $start_record to $end_record";
$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 g-4">';
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-xl-3 col-lg-4 col-sm-6">
                        <div class="card community-card p-0 overflow-hidden border-0 h-100">
                            <div class="img-bg  bg-light p-3">
                                <div class="icon rounded-circle border-4 border border-white overflow-hidden">
                                    <img src="' . $image_path . '" alt="' . $row['name'] . '" class="w-100">
                                </div>
                            </div>
                            <div class="card-body">
                                <h3 class="h5 fw-semi-bold"> ' . $row['name'] . ' </h3>
                                <p class="fw-medium">' . $row['organisation'] . ' </p>
                                <p class="mb-0"><a class="text-primary text-decoration-none" href="https://' . $row['website'] . '" target="_blank"><img src="assets/images/icons/web.png" width="20 class="me-2"> ' . $row['website'] . '</a> </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) . '"><i class="fas fa-angle-left"></i></a>';
}
for ($i = 1; $i <= $total_pages; $i++) {
    $active_class = ($i == $page) ? 'btn-secondary' : 'btn-outline-primary';
    $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) . '"><i class="fas fa-angle-right"></i></a>';
}

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

?>
