<?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/student-auth.php';require_once __DIR__ . '/../includes/student-course-context.php';
$pdo=db();requireStudent();$student=currentStudent($pdo);if(!$student){studentLogout();redirect('login.php');}$error='';$success=flash('success')?:'';
if(isPost()){requireCsrf();$code=strtoupper(trim((string)($_POST['course_code']??'')));$reason=trim((string)($_POST['join_reason']??''));$course=safeFetch($pdo,"SELECT c.*,COALESCE(t.full_name,t.name) AS teacher_name FROM core_courses c LEFT JOIN core_teachers t ON t.id=c.teacher_id WHERE UPPER(c.course_code)=? LIMIT 1",[$code]);if(!$course)$error='The course code was not found.';elseif(!in_array((string)$course['status'],['open','active'],true))$error='This course is not currently open for enrollment.';elseif(isStudentEnrolledInCourse($pdo,(int)$student['id'],(int)$course['id']))$error='You are already enrolled in this course.';else{try{$existing=safeFetch($pdo,'SELECT * FROM core_course_join_requests WHERE student_id=? AND course_id=? ORDER BY id DESC LIMIT 1',[(int)$student['id'],(int)$course['id']]);if($existing&&$existing['status']==='pending')$error='Your request is already awaiting review.';elseif($existing&&$existing['status']==='approved')$error='Your request was already approved.';else{if($existing){$stmt=$pdo->prepare("UPDATE core_course_join_requests SET student_code=?,course_code=?,teacher_id=?,request_message=?,join_reason=?,status='pending',admin_notes=NULL,approved_by=NULL,requested_at=NOW(),reviewed_at=NULL,updated_at=NOW(),approved_at=NULL,rejected_at=NULL WHERE id=?");$stmt->execute([$student['student_code'],$course['course_code'],$course['teacher_id'],$reason?:null,$reason?:null,(int)$existing['id']]);}else{$stmt=$pdo->prepare("INSERT INTO core_course_join_requests (student_id,student_code,course_id,course_code,teacher_id,request_message,join_reason,status,requested_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,'pending',NOW(),NOW(),NOW())");$stmt->execute([(int)$student['id'],$student['student_code'],(int)$course['id'],$course['course_code'],$course['teacher_id'],$reason?:null,$reason?:null]);}logActivity($pdo,'student',(int)$student['id'],'Course join requested','Course '.$course['course_code'],null,(int)$course['id']);flash('success','Your request was sent to administration for review.');redirect('student/join-course.php');}}catch(Throwable $e){error_log('[SMI join request] '.$e->getMessage());$error=APP_DEBUG?$e->getMessage():'The request could not be submitted.';}}}
$openCourses=safeFetchAll($pdo,"SELECT c.*,COALESCE(t.full_name,t.name) AS teacher_name,(SELECT COUNT(*) FROM core_course_students cs WHERE cs.course_id=c.id AND cs.status='active') AS student_count FROM core_courses c LEFT JOIN core_teachers t ON t.id=c.teacher_id WHERE c.status IN ('open','active') ORDER BY c.start_date DESC,c.id DESC");
$myRequests=safeFetchAll($pdo,"SELECT r.*,c.title,c.level FROM core_course_join_requests r LEFT JOIN core_courses c ON c.id=r.course_id WHERE r.student_id=? ORDER BY COALESCE(r.requested_at,r.created_at) DESC",[(int)$student['id']]);
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Join Course · SMI</title><style>:root{font-family:Inter,Arial,sans-serif;background:#f3f6fb;color:#0f172a}*{box-sizing:border-box}body{margin:0}.page{max-width:1250px;margin:auto;padding:30px}.top{display:flex;justify-content:space-between;align-items:center}.top h1{font-size:44px;margin:0}.btn{border:0;border-radius:13px;padding:11px 15px;background:#2563eb;color:#fff;text-decoration:none;font-weight:850;cursor:pointer}.layout{display:grid;grid-template-columns:380px 1fr;gap:20px;margin-top:24px}.card{background:white;border-radius:25px;padding:23px;box-shadow:0 15px 42px rgba(15,23,42,.07)}label{display:block;font-weight:850;font-size:13px;margin-top:12px}input,textarea{width:100%;padding:12px;border:1px solid #dbe3ef;border-radius:12px;margin-top:6px;font:inherit}textarea{min-height:90px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(270px,1fr));gap:14px}.course{border:1px solid #e2e8f0;border-radius:18px;padding:17px}.meta{color:#64748b;font-size:13px;line-height:1.8}.pill{display:inline-block;padding:5px 9px;background:#eff6ff;color:#1d4ed8;border-radius:999px;font-size:12px;font-weight:850}.alert{padding:14px 18px;border-radius:14px;margin-top:16px;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.requests{margin-top:20px}.request{display:flex;justify-content:space-between;border-top:1px solid #e2e8f0;padding:12px 0}@media(max-width:850px){.layout{grid-template-columns:1fr}.page{padding:18px}.top h1{font-size:34px}}</style></head><body><main class="page"><div class="top"><div><h1>Join a core course</h1><p>Enter the exact course code or copy one from the open-course list.</p></div><a class="btn" 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>Send request</h2><form method="post"><?=csrfField()?><label>Course code</label><input name="course_code" required placeholder="CORE-AB12CD"><label>Why do you want to join?</label><textarea name="join_reason" maxlength="2000"></textarea><button class="btn" style="width:100%;margin-top:14px">Submit request</button></form><div class="requests"><h3>My requests</h3><?php foreach($myRequests as $r):?><div class="request"><span><?=e($r['title']?:$r['course_code'])?></span><span class="pill"><?=e($r['status'])?></span></div><?php endforeach;?><?php if(!$myRequests):?><p class="meta">No requests yet.</p><?php endif;?></div></section><section class="card"><h2>Open courses</h2><div class="grid"><?php foreach($openCourses as $c):?><article class="course"><span class="pill"><?=e($c['level'])?></span><h3><?=e($c['title'])?></h3><div class="meta">Code: <strong><?=e($c['course_code'])?></strong><br>Teacher: <?=e($c['teacher_name']?:'-')?><br><?=e(formatDateNice($c['start_date']))?> — <?=e(formatDateNice($c['end_date']))?><br><?=e($c['student_count'])?> enrolled</div><p><?=e($c['description'])?></p></article><?php endforeach;?><?php if(!$openCourses):?><p class="meta">No courses are open right now.</p><?php endif;?></div></section></div></main></body></html>
