<?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(); $admin=currentAdmin($pdo);
$error=''; $success=flash('success')?:'';

function createUniqueStudentCode(PDO $pdo): string {
    do { $code='SMI-'.random_int(10000,99999); } while ((int)safeCount($pdo,'SELECT COUNT(*) FROM students WHERE student_code=?',[$code])>0);
    return $code;
}
function createUniqueStudentCard(PDO $pdo): string {
    do { $card='SMI-ELD-'.date('ym').'-'.random_int(1000,9999); } while ((int)safeCount($pdo,'SELECT COUNT(*) FROM students WHERE student_card_number=? OR student_card=?',[$card,$card])>0);
    return $card;
}
if(isPost()){
    requireCsrf();
    $action=(string)($_POST['action']??'');
    if($action==='delete'){
        $id=(int)($_POST['student_id']??0);
        if($id<=0){$error='Invalid student.';}
        elseif((int)safeCount($pdo,'SELECT COUNT(*) FROM core_course_students WHERE student_id=?',[$id])>0){$error='This student has academic records. Archive or suspend the account instead of deleting it.';}
        else{
            try{$stmt=$pdo->prepare('DELETE FROM students WHERE id=?');$stmt->execute([$id]);logActivity($pdo,'admin',(int)($admin['id']??0),'Student deleted','Deleted student ID '.$id);flash('success','Student deleted successfully.');redirect('admin/students.php');}
            catch(Throwable $e){error_log('[SMI delete student] '.$e->getMessage());$error='Student could not be deleted.';}
        }
    }
    if($action==='add'){
        $name=trim((string)($_POST['full_name']??''));
        $email=trim((string)($_POST['email']??''));
        $phone=trim((string)($_POST['phone']??$_POST['whatsapp']??''));
        $country=trim((string)($_POST['country']??''));
        $city=trim((string)($_POST['city']??''));
        $gender=(string)($_POST['gender']??'male');
        $level=(string)($_POST['final_level']??'beginner');
        $status=(string)($_POST['status']??'approved');
        $code=trim((string)($_POST['student_code']??'')) ?: createUniqueStudentCode($pdo);
        $card=trim((string)($_POST['student_card_number']??$_POST['student_card']??'')) ?: createUniqueStudentCard($pdo);
        if($name===''||$phone===''||!in_array($gender,['male','female'],true)||!in_array($level,['beginner','intermediate','advanced'],true)||!in_array($status,['pending','approved','rejected'],true)){$error='Complete the required fields with valid values.';}
        elseif($email!==''&&!filter_var($email,FILTER_VALIDATE_EMAIL)){$error='Enter a valid email address.';}
        else{
            try{
                $stmt=$pdo->prepare("INSERT INTO students (full_name,whatsapp,whatsapp_number,email,phone,country,city,nationality,gender,selected_level,final_level,registration_type,status,core_status,student_code,student_card,student_card_number,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())");
                $stmt->execute([$name,$phone,$phone,$email?:null,$phone,$country?:null,$city?:null,$country?:null,$gender,$level,$level,'core',$status,$status==='approved'?'active':'not_enrolled',$code,$card,$card]);
                $id=(int)$pdo->lastInsertId(); logActivity($pdo,'admin',(int)($admin['id']??0),'Student created','Created student ID '.$id);
                flash('success','Student created. Code: '.$code.' · Card: '.$card); redirect('admin/students.php');
            }catch(Throwable $e){error_log('[SMI add student] '.$e->getMessage());$error=str_contains(strtolower($e->getMessage()),'duplicate')?'Student code, card number, phone, or email already exists.':'Student could not be created.';}
        }
    }
}
$search=trim((string)($_GET['search']??'')); $statusFilter=trim((string)($_GET['status']??'')); $levelFilter=trim((string)($_GET['level']??''));
$where=[];$params=[];
if($search!==''){$where[]='(full_name LIKE ? OR student_code LIKE ? OR student_card_number LIKE ? OR email LIKE ? OR phone LIKE ? OR whatsapp LIKE ?)';for($i=0;$i<6;$i++)$params[]='%'.$search.'%';}
if(in_array($statusFilter,['pending','approved','rejected'],true)){$where[]='status=?';$params[]=$statusFilter;}
if(in_array($levelFilter,['beginner','intermediate','advanced'],true)){$where[]='final_level=?';$params[]=$levelFilter;}
$sql='SELECT s.*,(SELECT COUNT(*) FROM core_course_students cs WHERE cs.student_id=s.id AND cs.status IN (\'active\',\'completed\')) AS course_count FROM students s'.($where?' WHERE '.implode(' AND ',$where):'').' ORDER BY s.id DESC LIMIT 500';
$students=safeFetchAll($pdo,$sql,$params);
$counts=['all'=>safeCount($pdo,'SELECT COUNT(*) FROM students'),'approved'=>safeCount($pdo,"SELECT COUNT(*) FROM students WHERE status='approved'"),'pending'=>safeCount($pdo,"SELECT COUNT(*) FROM students WHERE status='pending'")];
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Students · SMI</title><style>
:root{font-family:Inter,Arial,sans-serif;background:#f3f6fb;color:#0f172a}*{box-sizing:border-box}body{margin:0}.page{max-width:1500px;margin:auto;padding:30px}.top,.filters,.stats{display:flex;justify-content:space-between;align-items:center;gap:15px;flex-wrap:wrap}.top h1{font-size:46px;margin:0}.top p{color:#64748b}.btn{border:0;border-radius:13px;padding:11px 15px;background:#2563eb;color:white;text-decoration:none;font-weight:850;cursor:pointer}.danger{background:#dc2626}.muted{background:#e2e8f0;color:#0f172a}.stats{margin:22px 0}.stat{flex:1;min-width:180px;background:white;border-radius:20px;padding:18px;box-shadow:0 14px 38px rgba(15,23,42,.06)}.stat strong{font-size:28px}.layout{display:grid;grid-template-columns:360px 1fr;gap:20px}.card{background:white;border-radius:25px;padding:22px;box-shadow:0 14px 40px rgba(15,23,42,.06)}label{display:block;font-size:13px;font-weight:800;margin-top:12px}input,select{width:100%;border:1px solid #dbe3ef;border-radius:12px;padding:11px;margin-top:6px;font:inherit}.two{display:grid;grid-template-columns:1fr 1fr;gap:9px}.filters{margin-bottom:16px}.filters input,.filters select{width:auto;min-width:150px;margin:0}.table{overflow:auto}table{width:100%;border-collapse:collapse;min-width:1050px}th,td{padding:13px;border-top:1px solid #e2e8f0;text-align:left}th{background:#f8fafc}.pill{display:inline-block;padding:5px 9px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:12px;font-weight:850}.alert{padding:14px 18px;border-radius:14px;margin:16px 0;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.actions{display:flex;gap:6px}.actions form{display:inline}.actions .btn{padding:8px 10px}@media(max-width:1000px){.layout{grid-template-columns:1fr}.page{padding:18px}.top h1{font-size:36px}}
</style></head><body><main class="page"><div class="top"><div><h1>Students</h1><p>Create, search, edit and safely manage core-period student accounts.</p></div><a class="btn muted" href="dashboard.php">Dashboard</a></div>
<div class="stats"><div class="stat"><small>All students</small><br><strong><?=e($counts['all'])?></strong></div><div class="stat"><small>Approved</small><br><strong><?=e($counts['approved'])?></strong></div><div class="stat"><small>Pending</small><br><strong><?=e($counts['pending'])?></strong></div></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>Add student</h2><form method="post"><?=csrfField()?><input type="hidden" name="action" value="add"><label>Full name *</label><input name="full_name" required><label>WhatsApp / phone *</label><input name="phone" required><label>Email</label><input type="email" name="email"><div class="two"><label>Country<input name="country"></label><label>City<input name="city"></label></div><div class="two"><label>Gender<select name="gender"><option value="male">Male</option><option value="female">Female</option></select></label><label>Level<select name="final_level"><option>beginner</option><option>intermediate</option><option>advanced</option></select></label></div><label>Status</label><select name="status"><option value="approved">Approved</option><option value="pending">Pending</option><option value="rejected">Rejected</option></select><label>Student code <small>(automatic when blank)</small></label><input name="student_code" placeholder="SMI-12345"><label>Student card <small>(automatic when blank)</small></label><input name="student_card_number" placeholder="SMI-ELD-2607-1234"><button class="btn" style="width:100%;margin-top:16px">Create student</button></form></section>
<section class="card"><form class="filters" method="get"><input name="search" value="<?=e($search)?>" placeholder="Name, code, card, phone or email"><select name="status"><option value="">All statuses</option><?php foreach(['approved','pending','rejected'] as $v):?><option value="<?=$v?>" <?=selected($statusFilter,$v)?>><?=ucfirst($v)?></option><?php endforeach;?></select><select name="level"><option value="">All levels</option><?php foreach(['beginner','intermediate','advanced'] as $v):?><option value="<?=$v?>" <?=selected($levelFilter,$v)?>><?=ucfirst($v)?></option><?php endforeach;?></select><button class="btn">Filter</button></form><div class="table"><table><thead><tr><th>Student</th><th>Access</th><th>Contact</th><th>Level</th><th>Status</th><th>Courses</th><th>Actions</th></tr></thead><tbody><?php foreach($students as $s):?><tr><td><strong><?=e($s['full_name'])?></strong><br><small>#<?=e($s['id'])?></small></td><td><code><?=e($s['student_code']?:'-')?></code><br><small><?=e($s['student_card_number']?:$s['student_card']?:'-')?></small></td><td><?=e($s['phone']?:$s['whatsapp'])?><br><small><?=e($s['email']?:'-')?></small></td><td><span class="pill"><?=e($s['final_level']?:$s['selected_level'])?></span></td><td><?=e($s['status'])?> / <?=e($s['core_status'])?></td><td><?=e($s['course_count'])?></td><td><div class="actions"><a class="btn" href="edit-student.php?id=<?=$s['id']?>">Edit</a><?php if((int)$s['course_count']===0):?><form method="post" onsubmit="return confirm('Delete this student permanently?')"><?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="student_id" value="<?=$s['id']?>"><button class="btn danger">Delete</button></form><?php endif;?></div></td></tr><?php endforeach;?><?php if(!$students):?><tr><td colspan="7">No matching students.</td></tr><?php endif;?></tbody></table></div></section></div></main></body></html>
