<?php 
include('includes/config.php');
include('includes/user_data.php');

// Pagination setup
$limit = 10; // records per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Filters
$filters = [];
$params = [];

if (!empty($_GET['admission_num'])) {
    $filters[] = "s.Admission_num LIKE :admission_num";
    $params[':admission_num'] = "%" . $_GET['admission_num'] . "%";
}
if (!empty($_GET['name'])) {
    $filters[] = "s.name LIKE :name";
    $params[':name'] = "%" . $_GET['name'] . "%";
}
if (!empty($_GET['class_id'])) {
    $filters[] = "s.class_id = :class_id";
    $params[':class_id'] = $_GET['class_id'];
}
if (!empty($_GET['status'])) {
    $filters[] = "s.status = :status";
    $params[':status'] = $_GET['status'];
}

$where = $filters ? "WHERE " . implode(" AND ", $filters) : "";

// Count total records
$countStmt = $dbh->prepare("SELECT COUNT(*) 
    FROM students s 
    LEFT JOIN classes c ON s.class_id = c.id 
    $where");
$countStmt->execute($params);
$total_records = $countStmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// Fetch filtered students with pagination
$sql = "SELECT s.*, c.name AS class_name 
        FROM students s 
        LEFT JOIN classes c ON s.class_id = c.id 
        $where 
        ORDER BY s.id DESC 
        LIMIT :limit OFFSET :offset";
$stmt = $dbh->prepare($sql);
foreach ($params as $key => $val) {
    $stmt->bindValue($key, $val);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch classes for filter dropdown
$classStmt = $dbh->query("SELECT id, name FROM classes ORDER BY name ASC");
$classes = $classStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!doctype html>
<html lang="en">
<head>
		<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<!--favicon-->
	<link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
	<!--plugins-->
	<link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
	<link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
	<link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
	<!-- loader-->
	<link href="assets/css/pace.min.css" rel="stylesheet" />
	<script src="assets/js/pace.min.js"></script>
	<!-- Bootstrap CSS -->
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/bootstrap-extended.css" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&amp;display=swap" rel="stylesheet">
	<link href="assets/css/app.css" rel="stylesheet">
	<link href="assets/css/icons.css" rel="stylesheet">
	<!-- Theme Style CSS -->
	<link rel="stylesheet" href="assets/css/dark-theme.css" />
	<link rel="stylesheet" href="assets/css/semi-dark.css" />
	<link rel="stylesheet" href="assets/css/header-colors.css" />
	<link href="assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="assets/css/app.css" rel="stylesheet">
	<title>Students</title>
	<script src="https://cdn.tailwindcss.com"></script>
</head>

<body>
<div class="wrapper">
	<?php include 'includes/side.php'; ?>
	<?php include 'includes/head.php'; ?>

	<div class="page-wrapper">
		<div class="page-content">
			<div class="container">
				<div class="main-body">
					<div class="max-w-6xl mx-auto">
						<h1 class="text-3xl font-bold mb-6 text-center">Student Records</h1>

						<!-- Filter Form -->
						<form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-4 mb-6 bg-white p-4 rounded shadow">
							<input type="text" name="admission_num" placeholder="Admission No" value="<?= htmlspecialchars($_GET['admission_num'] ?? '') ?>" class="border p-2 rounded w-full">
							<input type="text" name="name" placeholder="Name" value="<?= htmlspecialchars($_GET['name'] ?? '') ?>" class="border p-2 rounded w-full">
							
							<!-- Class dropdown -->
							<select name="class_id" class="border p-2 rounded w-full">
								<option value="">-- Class --</option>
								<?php foreach($classes as $class): ?>
									<option value="<?= $class['id'] ?>" 
										<?= (($_GET['class_id'] ?? '') == $class['id']) ? 'selected' : '' ?>>
										<?= htmlspecialchars($class['name']) ?>
									</option>
								<?php endforeach; ?>
							</select>

							<!-- Status dropdown -->
							<select name="status" class="border p-2 rounded w-full">
								<option value="">-- Status --</option>
								<option value="active" <?= (($_GET['status'] ?? '') == 'active') ? 'selected' : '' ?>>Active</option>
								<option value="suspended" <?= (($_GET['status'] ?? '') == 'suspended') ? 'selected' : '' ?>>Suspended</option>
								<option value="withdrawn" <?= (($_GET['status'] ?? '') == 'withdrawn') ? 'selected' : '' ?>>Withdrawn</option>
							</select>

							<button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">Filter</button>
						</form>

						<!-- Students Table -->
						<div class="overflow-x-auto shadow rounded-lg bg-white">
							<table class="w-full text-sm text-left border-collapse">
								<thead class="bg-gray-200 text-gray-700 uppercase text-xs">
									<tr>
										<th class="px-4 py-3">ID</th>
										<th class="px-4 py-3">Admission No.</th>
										<th class="px-4 py-3">Name</th>
										<th class="px-4 py-3">Class</th>
										<th class="px-4 py-3">Sex</th>
										<th class="px-4 py-3">Parent</th>
										<th class="px-4 py-3">Status</th>
										<th class="px-4 py-3">Actions</th>
									</tr>
								</thead>
								<tbody>
									<?php if ($students): ?>
										<?php foreach($students as $s): ?>
										<tr class="border-b hover:bg-gray-50">
											<td class="px-4 py-3"><?= htmlspecialchars($s['id']) ?></td>
											<td class="px-4 py-3"><?= htmlspecialchars($s['Admission_num']) ?></td>
											<td class="px-4 py-3 flex items-center space-x-2">
												<img src="<?= htmlspecialchars($s['image']) ?>" alt="pic" class="w-8 h-8 rounded-full object-cover">
												<span><?= htmlspecialchars($s['name']) ?></span>
											</td>
											<td class="px-4 py-3"><?= htmlspecialchars($s['class_name']) ?></td>
											<td class="px-4 py-3"><?= htmlspecialchars($s['sex']) ?></td>
											<td class="px-4 py-3"><?= htmlspecialchars($s['parent_name']) ?><br>
												<small class="text-gray-500"><?= htmlspecialchars($s['parent_phone']) ?></small>
											</td>
											<td class="px-4 py-3">
												<?php if($s['status'] === 'active'): ?>
													<span class="px-2 py-1 text-xs font-medium bg-green-100 text-green-700 rounded">Active</span>
												<?php elseif($s['status'] === 'suspended'): ?>
													<span class="px-2 py-1 text-xs font-medium bg-yellow-100 text-yellow-700 rounded">Suspended</span>
												<?php else: ?>
													<span class="px-2 py-1 text-xs font-medium bg-red-100 text-red-700 rounded">Withdrawn</span>
												<?php endif; ?>
											</td>
											<td class="px-4 py-3 space-x-2"> 
												<?php if($s['status'] === 'active'): ?>
													<button onclick="updateStatus(<?= $s['id'] ?>,'suspended')" class="px-3 py-1 text-xs rounded bg-yellow-500 text-white hover:bg-yellow-600">Suspend</button>
													<button onclick="updateStatus(<?= $s['id'] ?>,'withdrawn')" class="px-3 py-1 text-xs rounded bg-red-500 text-white hover:bg-red-600">Withdraw</button>
												<?php else: ?>
													<button onclick="updateStatus(<?= $s['id'] ?>,'active')" class="px-3 py-1 text-xs rounded bg-green-500 text-white hover:bg-green-600">Set Active</button>
												<?php endif; ?>
											</td>
										</tr>
										<?php endforeach; ?>
									<?php else: ?>
										<tr><td colspan="8" class="text-center py-4">No records found</td></tr>
									<?php endif; ?>
								</tbody>
							</table>
						</div>

						<!-- Pagination -->
						<div class="flex justify-center mt-6 space-x-2">
							<?php for ($i = 1; $i <= $total_pages; $i++): ?>
								<a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" 
								   class="px-3 py-1 rounded border <?= $i == $page ? 'bg-blue-500 text-white' : 'bg-white hover:bg-gray-100' ?>">
									<?= $i ?>
								</a>
							<?php endfor; ?>
						</div>

					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
function updateStatus(id, status) {
	if(!confirm(`Are you sure you want to mark this student as ${status}?`)) return;

	fetch('update_status.php', {
		method: 'POST',
		headers: {'Content-Type':'application/x-www-form-urlencoded'},
		body: `id=${id}&status=${status}`
	})
	.then(res => res.text())
	.then(data => {
		alert(data);
		location.reload();
	})
	.catch(err => alert('Error: ' + err));
}
</script>
	<!-- Bootstrap JS -->
	<script src="assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<script src="assets/js/jquery.min.js"></script>
	<script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
	<script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
	<script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
	<!--app JS-->
	<script src="assets/js/app.js"></script>
</body>
</html>
