<?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';
$pdo=db();requireAdmin();
$requiredTables=['students','core_admins','core_teachers','core_courses','core_course_students','core_sessions','core_attendance','core_attendance_codes','core_attendance_sessions','core_exams','core_exam_questions','core_exam_options','core_exam_attempts','core_exam_answers','core_exam_autosaves','core_homework','core_homework_submissions','core_materials','core_shadowing','core_shadowing_submissions','core_obstacles','core_obstacle_steps','core_obstacle_submissions','core_vocabulary','core_participation','core_grade_items','core_grades','core_final_grades','core_certificates','core_notifications','core_activity_logs'];
$checks=[];
$add=function(string $group,string $label,bool $ok,string $detail='')use(&$checks){$checks[]=['group'=>$group,'label'=>$label,'ok'=>$ok,'detail'=>$detail];};
$add('Runtime','PHP 8.1 or newer',version_compare(PHP_VERSION,'8.1.0','>='),PHP_VERSION);
foreach(['pdo','fileinfo','json','openssl'] as $ext){$add('Runtime','Extension: '.$ext,extension_loaded($ext),extension_loaded($ext)?'Loaded':'Missing');}
$add('Runtime','PDO MySQL extension',extension_loaded('pdo_mysql'),extension_loaded('pdo_mysql')?'Loaded':'Missing — required on hosting');
$add('Configuration','Production debug disabled',APP_DEBUG===false,APP_DEBUG?'Debug is ON':'Debug is OFF');
$add('Configuration','HTTPS base URL',str_starts_with(BASE_URL,'https://'),BASE_URL);
$add('Configuration','Database credentials configured',DB_NAME!==''&&DB_USER!==''&&DB_PASS!==''&&DB_PASS!=='CHANGE_ME','Database: '.(DB_NAME?:'not set'));
$add('Storage','Uploads directory exists',is_dir(UPLOADS_PATH),UPLOADS_PATH);
$add('Storage','Uploads directory writable',is_dir(UPLOADS_PATH)&&is_writable(UPLOADS_PATH),is_writable(UPLOADS_PATH)?'Writable':'Not writable');
foreach(['materials','homework','shadowing','profile-images','course-images','exam-attachments'] as $dir){$path=UPLOADS_PATH.'/'.$dir;$ok=is_dir($path)||@mkdir($path,0755,true);$add('Storage','uploads/'.$dir,$ok&&is_writable($path),$ok?(is_writable($path)?'Ready':'Not writable'):'Could not create');}
foreach($requiredTables as $table){$add('Database','Table: '.$table,tableExists($pdo,$table),tableExists($pdo,$table)?'Present':'Missing');}
$requiredColumns=['students'=>['student_code','student_card','student_card_number','status'],'core_homework'=>['max_points','max_score','points','weight'],'core_grade_items'=>['item_type','item_id','weight','max_score'],'core_attendance'=>['attendance_minutes','minutes_attended'],'core_exam_attempts'=>['result_released'],'core_notifications'=>['notification_type']];
foreach($requiredColumns as $table=>$columns){foreach($columns as $column){$add('Database upgrade',$table.'.'.$column,columnExists($pdo,$table,$column),columnExists($pdo,$table,$column)?'Present':'Run database/01_upgrade_core_periods.sql');}}
$phpInUploads=[];$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator(UPLOADS_PATH,FilesystemIterator::SKIP_DOTS));foreach($it as $f){if($f->isFile()&&preg_match('/\.(?:php\d*|phtml|phar)$/i',$f->getFilename()))$phpInUploads[]=$f->getPathname();}$add('Security','No executable PHP in uploads',$phpInUploads===[],$phpInUploads===[]?'Clean':implode(', ',$phpInUploads));
$groups=[];foreach($checks as $c)$groups[$c['group']][]=$c;$passed=count(array_filter($checks,fn($x)=>$x['ok']));$total=count($checks);$score=$total?round($passed/$total*100):0;
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>System Health · SMI</title><style>:root{font-family:Inter,Arial,sans-serif;background:#f4f7fb;color:#0f172a}*{box-sizing:border-box}body{margin:0}.page{max-width:1250px;margin:auto;padding:30px}.top{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap}.top h1{font-size:42px;margin:0}.btn{background:#e2e8f0;color:#0f172a;text-decoration:none;font-weight:850;padding:11px 15px;border-radius:13px}.score{background:white;border-radius:24px;padding:22px;margin:22px 0;box-shadow:0 15px 40px rgba(15,23,42,.07);display:flex;align-items:center;gap:18px}.ring{width:92px;height:92px;border-radius:50%;display:grid;place-items:center;background:conic-gradient(#16a34a calc(var(--score)*1%),#e2e8f0 0);position:relative}.ring:after{content:'';position:absolute;inset:10px;background:white;border-radius:50%}.ring strong{z-index:1;font-size:23px}.group{background:white;border-radius:22px;padding:20px;margin-bottom:17px;box-shadow:0 14px 38px rgba(15,23,42,.06)}.group h2{margin:0 0 12px}.row{display:grid;grid-template-columns:28px minmax(220px,1fr) 1fr;gap:10px;padding:11px 0;border-top:1px solid #eef2f7;align-items:start}.icon{width:24px;height:24px;border-radius:50%;display:grid;place-items:center;font-size:13px;font-weight:900}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.detail{color:#64748b;font-size:13px;word-break:break-word}@media(max-width:700px){.page{padding:18px}.top h1{font-size:32px}.row{grid-template-columns:28px 1fr}.detail{grid-column:2}}</style></head><body><main class="page"><div class="top"><div><h1>System health</h1><p>Read-only deployment and database diagnostics.</p></div><a class="btn" href="dashboard.php">Dashboard</a></div><section class="score"><div class="ring" style="--score:<?=$score?>"><strong><?=$score?>%</strong></div><div><h2><?=$passed?> of <?=$total?> checks passed</h2><p>Resolve every red item before opening the platform to students.</p></div></section><?php foreach($groups as $name=>$rows):?><section class="group"><h2><?=e($name)?></h2><?php foreach($rows as $c):?><div class="row"><span class="icon <?=$c['ok']?'ok':'bad'?>"><?=$c['ok']?'✓':'!'?></span><strong><?=e($c['label'])?></strong><span class="detail"><?=e($c['detail'])?></span></div><?php endforeach;?></section><?php endforeach;?></main></body></html>
