<?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/grade-engine.php';
$pdo=db();requireAdmin();$admin=currentAdmin($pdo);$error='';$success=flash('success')?:'';
if(isPost()){requireCsrf();$action=(string)($_POST['action']??'');try{
 if($action==='create'){$studentId=(int)($_POST['student_id']??0);$courseId=(int)($_POST['course_id']??0);$status=(string)($_POST['status']??'pending');if(!in_array($status,['pending','issued','blocked'],true))throw new RuntimeException('Invalid certificate status.');$enrollment=safeFetch($pdo,"SELECT cs.id,s.full_name,c.title 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 cs.student_id=? AND cs.course_id=? AND cs.status IN ('active','approved','completed') LIMIT 1",[$studentId,$courseId]);if(!$enrollment)throw new RuntimeException('Select a valid enrolled student and course.');if(safeFetch($pdo,'SELECT id FROM core_certificates WHERE student_id=? AND course_id=? LIMIT 1',[$studentId,$courseId]))throw new RuntimeException('A certificate record already exists for this student and course.');$grade=recalculateFinalGrade($pdo,$studentId,$courseId);if($status==='issued'&&(float)$grade['final_percentage']<60)throw new RuntimeException('The final grade is below 60%; create it as pending or blocked.');$number='SMI-CERT-'.date('Y').'-'.str_pad((string)$courseId,3,'0',STR_PAD_LEFT).'-'.str_pad((string)$studentId,5,'0',STR_PAD_LEFT).'-'.strtoupper(substr(generateToken(6),0,6));mustExecute($pdo,'INSERT INTO core_certificates (student_id,course_id,certificate_number,status,issued_at,created_at) VALUES (?,?,?,?,?,NOW())',[$studentId,$courseId,$number,$status,$status==='issued'?now():null]);flash('success','Certificate record created.');}
 elseif(in_array($action,['issue','block','pending'],true)){$id=(int)($_POST['certificate_id']??0);$cert=safeFetch($pdo,'SELECT * FROM core_certificates WHERE id=?',[$id]);if(!$cert)throw new RuntimeException('Certificate not found.');if($action==='issue'){$grade=recalculateFinalGrade($pdo,(int)$cert['student_id'],(int)$cert['course_id']);if((float)$grade['final_percentage']<60)throw new RuntimeException('Certificate cannot be issued because the final grade is below 60%.');mustExecute($pdo,"UPDATE core_certificates SET status='issued',issued_at=NOW() WHERE id=?",[$id]);}elseif($action==='block'){mustExecute($pdo,"UPDATE core_certificates SET status='blocked',issued_at=NULL WHERE id=?",[$id]);}else{mustExecute($pdo,"UPDATE core_certificates SET status='pending',issued_at=NULL WHERE id=?",[$id]);}flash('success','Certificate status updated.');}
 logActivity($pdo,'admin',(int)($admin['id']??0),'Certificate updated','Action '.$action);redirect('admin/certificates.php');
 }catch(Throwable $e){error_log('[SMI certificates] '.$e->getMessage());$error=APP_DEBUG?$e->getMessage():$e->getMessage();}}
$enrollments=safeFetchAll($pdo,"SELECT cs.student_id,cs.course_id,s.full_name,s.student_code,c.title course_title 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 cs.status IN ('active','approved','completed') ORDER BY s.full_name,c.title");
$certificates=safeFetchAll($pdo,"SELECT cert.*,s.full_name,s.student_code,c.title course_title,fg.final_percentage,fg.grade_letter FROM core_certificates cert LEFT JOIN students s ON s.id=cert.student_id LEFT JOIN core_courses c ON c.id=cert.course_id LEFT JOIN core_final_grades fg ON fg.student_id=cert.student_id AND fg.course_id=cert.course_id ORDER BY cert.id DESC");
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Certificates · SMI</title><style>:root{font-family:Inter,Arial,sans-serif;background:#f4f7fb;color:#0f172a}*{box-sizing:border-box}body{margin:0}.page{max-width:1500px;margin:auto;padding:30px}.top{display:flex;justify-content:space-between;align-items:center;gap:14px}.top h1{font-size:42px;margin:0}.grid{display:grid;grid-template-columns:400px 1fr;gap:22px;margin-top:24px}.card{background:#fff;border-radius:24px;padding:22px;box-shadow:0 16px 44px rgba(15,23,42,.07)}label{display:block;font-size:13px;font-weight:850;margin-top:12px}select,input{width:100%;padding:11px;border:1px solid #dbe3ef;border-radius:12px;margin-top:6px;font:inherit}.btn{border:0;border-radius:12px;padding:10px 14px;background:#2563eb;color:#fff;font-weight:850;text-decoration:none;cursor:pointer}.muted{background:#e2e8f0;color:#0f172a}.red{background:#dc2626}.amber{background:#d97706}.table{overflow:auto}table{width:100%;border-collapse:collapse}th,td{padding:13px;text-align:left;border-bottom:1px solid #e2e8f0;vertical-align:top}th{font-size:12px;text-transform:uppercase;color:#64748b}.badge{display:inline-block;padding:5px 9px;border-radius:999px;font-size:12px;font-weight:850}.issued{background:#dcfce7;color:#166534}.pending{background:#fef3c7;color:#92400e}.blocked{background:#fee2e2;color:#991b1b}.actions{display:flex;gap:5px;flex-wrap:wrap}.alert{padding:14px 18px;border-radius:14px;margin-top:18px;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.meta{color:#64748b;font-size:13px}@media(max-width:1000px){.grid{grid-template-columns:1fr}.page{padding:18px}.top h1{font-size:32px}}</style></head><body><main class="page"><div class="top"><div><h1>Certificates</h1><p class="meta">Issue course-specific certificates only after enrollment and grade validation.</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;?><div class="grid"><section class="card"><h2>Create certificate record</h2><form method="post"><?=csrfField()?><input type="hidden" name="action" value="create"><label>Student and course<select name="student_id" id="studentSelect" required><option value="">Select enrollment</option><?php foreach($enrollments as $x):?><option value="<?=$x['student_id']?>" data-course="<?=$x['course_id']?>"><?=e($x['full_name'].' · '.$x['student_code'].' — '.$x['course_title'])?></option><?php endforeach;?></select></label><input type="hidden" name="course_id" id="courseId"><label>Initial status<select name="status"><option value="pending">Pending</option><option value="issued">Issued (grade ≥ 60%)</option><option value="blocked">Blocked</option></select></label><button class="btn" style="width:100%;margin-top:15px">Create record</button></form></section><section class="card table"><table><thead><tr><th>Certificate</th><th>Student</th><th>Course</th><th>Grade</th><th>Status</th><th>Actions</th></tr></thead><tbody><?php foreach($certificates as $c):?><tr><td><strong><?=e($c['certificate_number'])?></strong><div class="meta"><?=e($c['issued_at']?:$c['created_at'])?></div></td><td><?=e($c['full_name'])?><div class="meta"><?=e($c['student_code'])?></div></td><td><?=e($c['course_title']?:'—')?></td><td><?=number_format((float)($c['final_percentage']??0),1)?>% · <?=e($c['grade_letter']??'—')?></td><td><span class="badge <?=e($c['status'])?>"><?=e(ucfirst($c['status']))?></span></td><td><div class="actions"><?php foreach(['issue'=>'Issue','pending'=>'Pending','block'=>'Block'] as $a=>$label):?><form method="post"><?=csrfField()?><input type="hidden" name="action" value="<?=$a?>"><input type="hidden" name="certificate_id" value="<?=$c['id']?>"><button class="btn <?=$a==='block'?'red':($a==='pending'?'amber':'')?>"><?=$label?></button></form><?php endforeach;?></div></td></tr><?php endforeach;?><?php if(!$certificates):?><tr><td colspan="6">No certificate records yet.</td></tr><?php endif;?></tbody></table></section></div></main><script>const s=document.getElementById('studentSelect'),c=document.getElementById('courseId');function sync(){const o=s.options[s.selectedIndex];c.value=o?o.dataset.course||'':'';}s.addEventListener('change',sync);sync();</script></body></html>
