<?php
require_once '../auth/auth.php';
require_once '../models/db_connection.php';
require_once '../models/student_model.php';
$student =  new Student($conn);

// Pagination settings
$perPage = isset($_GET['per_page']) ? max(1, min((int) $_GET['per_page'], 100)) : 20;
$currentPage = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
$offset = ($currentPage - 1) * $perPage;

// Total count for pagination
$totalResult = mysqli_query($conn, "SELECT COUNT(*) AS total FROM students");
$totalRow = $totalResult ? mysqli_fetch_assoc($totalResult) : ['total' => 0];
$totalStudents = (int) $totalRow['total'];
$totalPages = max(1, (int) ceil($totalStudents / $perPage));

// Guard against asking for a page past the end
if ($currentPage > $totalPages) {
	$currentPage = $totalPages;
	$offset = ($currentPage - 1) * $perPage;
}

// Fetch students for the current page
$stmt = $conn->prepare("SELECT students.*, student_course.course_id, courses.name AS course_name
                         FROM students 
                         LEFT JOIN student_course ON students.en_id = student_course.s_id 
                         LEFT JOIN courses ON courses.course_id = student_course.course_id
						 ORDER BY students.student_id DESC
                         LIMIT ? OFFSET ?");
$stmt->bind_param("ii", $perPage, $offset);
$stmt->execute();
$studentsData = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">

<head>
	<title>Student | Add Student </title>
	<?php include("../templates/header.php"); ?>
	<script type='text/javascript'>
		function ConfirmDelete() {
			if (confirm("Are you sure you want to delete this student and its associated details?"))
				return true;
			else
				return false;
		}
	</script>
</head>

<body>
	<?php
	if (isset($_GET["message"])) {
		$message = $_GET["message"];
		echo "<script>alert('" . $message . "')</script>";
	}
	?>
	<div class="container-scroller">
		<!-- partial:partials/_navbar.html -->
		<?php include("../templates/nav.php"); ?>
		<!-- partial -->
		<div class="container-fluid page-body-wrapper">
			<!-- partial:partials/_sidebar.html -->
			<?php include("../templates/sidenav.php"); ?>
			<!-- partial -->
			<div class="main-panel">
				<div class="content-wrapper">

					<div class="col-lg-12 grid-margin stretch-card">
						<div class="card">
							<div class="card-body">
								<h4 class="card-title">View All Students</h4>
								<p class="card-description">
									Students Table <code></code>
								</p>
								<div class="table-responsive pt-3">
									<table class="table table-bordered display" id="example" style="width:100%">
										<thead>
											<tr>
												<th> # </th>
												<th>Student Details</th>
												<th>Course enrolled</th>
												<th>Enrollment</th>
												<th> Reg By</th>
												<th>Actions</th>
											</tr>
										</thead>
										<tbody>
											<?php
											$x = $offset + 1;
											while ($studentValue = $studentsData->fetch_assoc()) {

												//$isEnrolled = $student->isStudentEnrolled($studentValue['student_id']);
											?>
												<tr>
													<td> <?= $x ?></td>
													<td>Enrollment ID: <?= $studentValue['en_id'] ?>,Full name: <?= $studentValue['fullname'] ?>,
														ID NO: <?= $studentValue['ident_number'] ?>, Street: <?= $studentValue['street'] ?>,
														Work: <?= $studentValue['work'] ?>, Address: <?= $studentValue['address'] ?>,
														Education: <?= $studentValue['education'] ?></td>
													<td>
														<?= isset($studentValue['course_name']) && $studentValue['course_name'] !== null ? $studentValue['course_name'] : 'No course assigned' ?>
													</td>
													<td><label class="badge <?php if ($studentValue['status'] == 'enrolled') {
																				echo 'badge-success';
																			} else {
																				echo 'badge-danger';
																			} ?>"><?= $studentValue['status'] ?></label></td>
													<td><?= $studentValue['reg_by'] ?></td>

													<td>
														<?php
														if ($studentValue['status'] == 'enrolled') {
														?>
															<a href="single_student.php?id=<?= $studentValue['student_id'] ?>">
																<button type="button" class="btn btn-outline-primary btn-icon-text">
																	<i class="fa fa-eye"></i> </button></a>
														<?php
														}
														?>
														<a href="edit_student.php?id=<?= $studentValue['student_id'] ?>">
															<button  type="button" class="btn btn-outline-secondary btn-icon-text">
																<i class=" fa fa-pencil"></i> </button></a>

														<a onclick='return ConfirmDelete()' href="../controllers/delete_student.php?id=<?= $studentValue['student_id'] ?>">
															<button <?php if ($_SESSION['role'] != 'admin') {
																		echo "disabled";
																	} ?> type="button" class="btn btn-primary btn-icon-text">
																<i class="fa fa-trash"></i> </button></a>


													</td>
												</tr>
											<?php $x++;} ?>


										</tbody>
									</table>
									<?php
									$startRecord = $totalStudents > 0 ? $offset + 1 : 0;
									$endRecord = min($offset + $perPage, $totalStudents);
									$pagesToShow = [1, $totalPages];
									for ($i = $currentPage - 2; $i <= $currentPage + 2; $i++) {
										if ($i > 1 && $i < $totalPages) {
											$pagesToShow[] = $i;
										}
									}
									$pagesToShow = array_unique($pagesToShow);
									sort($pagesToShow);
									$baseQuery = http_build_query(['per_page' => $perPage]);
									?>
									<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center pt-3 gap-2">
										<div class="text-muted">Showing <?= $startRecord ?>-<?= $endRecord ?> of <?= $totalStudents ?> students</div>
										<div class="d-flex gap-3 align-items-center">
											<form class="d-flex align-items-center" method="get">
												<label class="me-2 mb-0" for="per_page">Per page</label>
												<select id="per_page" name="per_page" class="form-select form-select-sm" onchange="this.form.submit()">
													<?php foreach ([10, 20, 50, 100] as $option) { ?>
														<option value="<?= $option ?>" <?= $perPage === $option ? 'selected' : '' ?>><?= $option ?></option>
													<?php } ?>
												</select>
												<input type="hidden" name="page" value="1" />
											</form>
											<nav aria-label="Student pagination">
												<ul class="pagination mb-0">
													<li class="page-item <?= $currentPage <= 1 ? 'disabled' : '' ?>">
														<a class="page-link" href="?<?= $baseQuery ?>&page=<?= max(1, $currentPage - 1) ?>" aria-label="Previous">
															<span aria-hidden="true">&laquo;</span>
														</a>
													</li>
													<?php
													$previousPage = 0;
													foreach ($pagesToShow as $page) {
														if ($previousPage && $page !== $previousPage + 1) {
															echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
														}
														$isActive = $page === $currentPage ? 'active' : '';
														echo '<li class="page-item ' . $isActive . '"><a class="page-link" href="?' . $baseQuery . '&page=' . $page . '">' . $page . '</a></li>';
														$previousPage = $page;
													}
													?>
													<li class="page-item <?= $currentPage >= $totalPages ? 'disabled' : '' ?>">
														<a class="page-link" href="?<?= $baseQuery ?>&page=<?= min($totalPages, $currentPage + 1) ?>" aria-label="Next">
															<span aria-hidden="true">&raquo;</span>
														</a>
													</li>
												</ul>
											</nav>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<!-- content-wrapper ends -->
				<!-- partial:partials/_footer.html -->
				<?php include("../templates/footer.php"); ?>

