<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/security.php';
require_once __DIR__ . '/../includes/admin-auth.php';
require_once __DIR__ . '/../includes/admin-helpers.php';
$pdo=db();requireAdmin();
$success=flash('success')??'';$error=flash('error')??'';
$courseId=(int)($_GET['course_id']??$_POST['course_id']??0);
if(isPost()){
 requireCsrf();$action=(string)($_POST['action']??'');$studentId=(int)($_POST['student_id']??0);$course=(int)($_POST['course_id']??0);
 try{
  if($action==='enroll'){
   if(!enrollStudentInCourse($pdo,$studentId,$course)) throw new RuntimeException('Could not enroll the student.');
   logActivity($pdo,'admin',currentAdminId(),'student_enrolled',"Student {$studentId} enrolled in course {$course}");flash('success','Student enrolled successfully.');
  }elseif(in_array($action,['complete','remove','restore'],true)){
   $status=$action==='complete'?'completed':($action==='remove'?'removed':'active');$archive=$action==='remove'?'archived':'active';
   $stmt=$pdo->prepare('UPDATE core_course_students SET status=?,archive_status=?,archived_at='.($archive==='archived'?'NOW()':'NULL').',updated_at=NOW() WHERE student_id=? AND course_id=?');$stmt->execute([$status,$archive,$studentId,$course]);
   flash('success','Enrollment updated.');
  }
 }catch(Throwable $e){flash('error',APP_DEBUG?$e->getMessage():'The operation failed.');}
 redirect('admin/enrollments.php'.($courseId>0?'?course_id='.$courseId:''));
}
$courses=safeFetchAll($pdo,"SELECT c.*,COALESCE(t.full_name,t.name) teacher_name FROM core_courses c LEFT JOIN core_teachers t ON t.id=c.teacher_id ORDER BY c.id DESC");
$students=safeFetchAll($pdo,"SELECT id,full_name,student_code FROM students WHERE status='approved' ORDER BY full_name");
$where=$courseId>0?'WHERE cs.course_id=?':'';$params=$courseId>0?[$courseId]:[];
$rows=safeFetchAll($pdo,"SELECT cs.*,s.full_name,s.student_code,c.title course_title,c.course_code FROM core_course_students cs INNER JOIN students s ON s.id=cs.student_id INNER JOIN core_courses c ON c.id=cs.course_id {$where} ORDER BY cs.id DESC",$params);
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Enrollments</title><style>
*{box-sizing:border-box}body{margin:0;background:#f3f6fb;color:#0f172a;font-family:Inter,Arial,sans-serif}.page{max-width:1450px;margin:auto;padding:32px}.top{display:flex;justify-content:space-between;align-items:center;margin-bottom:26px}.top h1{font-size:46px;margin:0}.back{padding:13px 18px;border-radius:14px;background:#e0e7ff;color:#3730a3;text-decoration:none;font-weight:900}.layout{display:grid;grid-template-columns:390px 1fr;gap:24px}.card{background:#fff;border-radius:28px;padding:25px;box-shadow:0 18px 45px rgba(15,23,42,.07)}label{display:block;font-weight:800;margin:14px 0 8px}select{width:100%;padding:14px;border:1px solid #dbe3ef;border-radius:14px}.btn{border:0;padding:12px 15px;border-radius:13px;background:#2563eb;color:#fff;font-weight:900;cursor:pointer}.full{width:100%;margin-top:18px}.alert{padding:14px 18px;border-radius:14px;margin-bottom:18px;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.table{overflow:auto}table{width:100%;border-collapse:collapse;min-width:850px}th,td{padding:14px;border-top:1px solid #e2e8f0;text-align:left}th{background:#f8fafc}.pill{padding:6px 10px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-weight:800;font-size:12px}.actions{display:flex;gap:7px}.actions form{display:inline}.actions .btn{padding:8px 10px}.red{background:#dc2626}.green{background:#16a34a}.filter{display:flex;gap:10px;margin-bottom:16px}.filter select{max-width:350px}@media(max-width:950px){.layout{grid-template-columns:1fr}.page{padding:20px}.top h1{font-size:36px}}
</style></head><body><main class="page"><div class="top"><div><h1>Course Enrollments</h1><p>Assign, archive and restore students safely.</p></div><a class="back" href="dashboard.php">Dashboard</a></div><?php if($success):?><div class="alert ok"><?=e($success)?></div><?php endif;?><?php if($error):?><div class="alert bad"><?=e($error)?></div><?php endif;?><div class="layout"><section class="card"><h2>Enroll student</h2><form method="post"><?=csrfField()?><input type="hidden" name="action" value="enroll"><label>Student</label><select name="student_id" required><option value="">Choose student</option><?php foreach($students as $s):?><option value="<?=$s['id']?>"><?=e($s['full_name'].' — '.$s['student_code'])?></option><?php endforeach;?></select><label>Course</label><select name="course_id" required><option value="">Choose course</option><?php foreach($courses as $c):?><option value="<?=$c['id']?>" <?=selected($courseId,$c['id'])?>><?=e($c['title'].' — '.$c['course_code'])?></option><?php endforeach;?></select><button class="btn full">Enroll student</button></form></section><section class="card"><form class="filter" method="get"><select name="course_id"><option value="0">All courses</option><?php foreach($courses as $c):?><option value="<?=$c['id']?>" <?=selected($courseId,$c['id'])?>><?=e($c['title'])?></option><?php endforeach;?></select><button class="btn">Filter</button></form><div class="table"><table><thead><tr><th>Student</th><th>Course</th><th>Status</th><th>Joined</th><th>Actions</th></tr></thead><tbody><?php foreach($rows as $r):?><tr><td><strong><?=e($r['full_name'])?></strong><br><small><?=e($r['student_code'])?></small></td><td><?=e($r['course_title'])?><br><small><?=e($r['course_code'])?></small></td><td><span class="pill"><?=e($r['status'])?> / <?=e($r['archive_status']??'active')?></span></td><td><?=e(formatDateNice($r['joined_at']??$r['created_at']))?></td><td><div class="actions"><?php foreach([['complete','Complete','green'],['remove','Archive','red'],['restore','Restore','']] as [$action,$label,$class]):?><form method="post"><?=csrfField()?><input type="hidden" name="action" value="<?=$action?>"><input type="hidden" name="student_id" value="<?=$r['student_id']?>"><input type="hidden" name="course_id" value="<?=$r['course_id']?>"><button class="btn <?=$class?>"><?=$label?></button></form><?php endforeach;?></div></td></tr><?php endforeach;?><?php if(!$rows):?><tr><td colspan="5">No enrollments found.</td></tr><?php endif;?></tbody></table></div></section></div></main></body></html>
