<?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/admin-auth.php';require_once __DIR__ . '/../includes/admin-helpers.php';
$pdo=db();requireAdmin();$admin=currentAdmin($pdo);$error='';$success=flash('success')?:'';
if(isPost()){requireCsrf();$id=(int)($_POST['request_id']??0);$action=(string)($_POST['action']??'');$note=trim((string)($_POST['admin_notes']??''));if($id<=0||!in_array($action,['approve','reject'],true))$error='Invalid request action.';else{$ok=$action==='approve'?approveJoinRequest($pdo,$id,(int)($admin['id']??0)):rejectJoinRequest($pdo,$id,(int)($admin['id']??0),$note);if($ok){logActivity($pdo,'admin',(int)($admin['id']??0),'Join request '.($action==='approve'?'approved':'rejected'),'Request ID '.$id);flash('success','Join request '.($action==='approve'?'approved and enrolled':'rejected').'.');redirect('admin/join-requests.php');}$error='The request could not be updated.';}}
$status=(string)($_GET['status']??'');$params=[];$where='';if(in_array($status,['pending','approved','rejected'],true)){$where=' WHERE r.status=?';$params[]=$status;}
$requests=safeFetchAll($pdo,"SELECT r.*,s.full_name,s.student_code,s.student_card_number,c.title AS course_title,c.level AS course_level,c.course_code AS current_course_code,t.full_name AS teacher_full_name,t.name AS teacher_name FROM core_course_join_requests r LEFT JOIN students s ON s.id=r.student_id LEFT JOIN core_courses c ON c.id=r.course_id LEFT JOIN core_teachers t ON t.id=c.teacher_id {$where} ORDER BY CASE r.status WHEN 'pending' THEN 0 ELSE 1 END,COALESCE(r.requested_at,r.created_at) DESC,r.id DESC",$params);
$counts=['pending'=>safeCount($pdo,"SELECT COUNT(*) FROM core_course_join_requests WHERE status='pending'"),'approved'=>safeCount($pdo,"SELECT COUNT(*) FROM core_course_join_requests WHERE status='approved'"),'rejected'=>safeCount($pdo,"SELECT COUNT(*) FROM core_course_join_requests WHERE status='rejected'")];
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Join Requests · SMI</title><style>:root{font-family:Inter,Arial,sans-serif;background:#f3f6fb;color:#0f172a}*{box-sizing:border-box}body{margin:0}.page{max-width:1450px;margin:auto;padding:30px}.top,.filters{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap}.top h1{font-size:44px;margin:0}.btn{border:0;border-radius:13px;padding:10px 14px;background:#2563eb;color:#fff;text-decoration:none;font-weight:850;cursor:pointer}.red{background:#dc2626}.muted{background:#e2e8f0;color:#0f172a}.filters{margin:22px 0}.filter{background:white;padding:11px 15px;border-radius:14px;text-decoration:none;color:#334155;font-weight:850}.filter.active{background:#2563eb;color:white}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(360px,1fr));gap:18px}.card{background:white;border-radius:24px;padding:21px;box-shadow:0 15px 42px rgba(15,23,42,.07)}.meta{color:#64748b;font-size:13px;line-height:1.8}.pill{display:inline-block;padding:5px 9px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:12px;font-weight:850}.actions{display:flex;gap:8px;margin-top:15px}.actions form{flex:1}.actions button{width:100%}.actions textarea{width:100%;min-height:58px;border:1px solid #dbe3ef;border-radius:11px;padding:9px;margin-bottom:7px}.alert{padding:14px 18px;border-radius:14px;margin:16px 0;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.empty{background:white;padding:45px;border-radius:24px;text-align:center;color:#64748b}@media(max-width:650px){.page{padding:18px}.top h1{font-size:34px}}</style></head><body><main class="page"><div class="top"><div><h1>Course join requests</h1><p>Approve a request to enroll the student in both compatible enrollment tables.</p></div><a class="btn muted" 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;?><nav class="filters"><div><?php foreach([''=>'All','pending'=>'Pending ('.$counts['pending'].')','approved'=>'Approved ('.$counts['approved'].')','rejected'=>'Rejected ('.$counts['rejected'].')'] as $k=>$label):?><a class="filter <?=$status===$k?'active':''?>" href="?status=<?=$k?>"><?=e($label)?></a><?php endforeach;?></div></nav><?php if($requests):?><section class="grid"><?php foreach($requests as $r):?><article class="card"><span class="pill"><?=e($r['status'])?></span><h3><?=e($r['full_name']?:'Unknown student')?></h3><div class="meta">Student: <?=e($r['student_code']?:'-')?> · <?=e($r['student_card_number']?:'-')?><br>Course: <?=e($r['course_title']?:$r['course_code'])?> · <?=e($r['course_level']?:'-')?><br>Teacher: <?=e($r['teacher_full_name']?:$r['teacher_name']?:'-')?><br>Requested: <?=e(formatDateTimeNice($r['requested_at']?:$r['created_at']))?></div><?php if(!empty($r['join_reason'])||!empty($r['request_message'])):?><p><?=nl2br(e($r['join_reason']?:$r['request_message']))?></p><?php endif;?><?php if($r['status']==='pending'):?><div class="actions"><form method="post"><?=csrfField()?><input type="hidden" name="request_id" value="<?=$r['id']?>"><input type="hidden" name="action" value="approve"><button class="btn">Approve & enroll</button></form><form method="post"><?=csrfField()?><input type="hidden" name="request_id" value="<?=$r['id']?>"><input type="hidden" name="action" value="reject"><textarea name="admin_notes" placeholder="Optional rejection reason"></textarea><button class="btn red">Reject</button></form></div><?php else:?><p class="meta">Reviewed: <?=e(formatDateTimeNice($r['reviewed_at']))?><br><?=e($r['admin_notes']?:'')?></p><?php endif;?></article><?php endforeach;?></section><?php else:?><div class="empty">No requests match this filter.</div><?php endif;?></main></body></html>
