<?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/security.php';
require_once __DIR__ . '/../includes/admin-auth.php';
require_once __DIR__ . '/../includes/grade-engine.php';
$pdo=db(); requireAdmin();
$success=flash('success') ?? ''; $error=flash('error') ?? '';
$courseId=(int)($_GET['course_id'] ?? $_POST['course_id'] ?? 0);
if(isPost()){
    requireCsrf();
    $action=(string)($_POST['action'] ?? '');
    try{
        if($action==='create'){
            $courseId=(int)($_POST['course_id']??0); $title=clean($_POST['title']??'');
            $type=clean($_POST['item_type']??'extra'); $max=max(.01,(float)($_POST['max_score']??100));
            $weight=max(0,min(100,(float)($_POST['weight']??0)));
            if($courseId<=0||$title==='') throw new RuntimeException('Choose a course and enter a title.');
            $id=ensureGradeItemDefinition($pdo,$courseId,$type,0,$title,$max,$weight,null,currentAdminId());
            if($id<=0) throw new RuntimeException('Could not create the grade item.');
            logActivity($pdo,'admin',currentAdminId(),'grade_item_created','Created grade item #'.$id);
            flash('success','Grade item created successfully.');
        }elseif($action==='delete'){
            $id=(int)($_POST['id']??0); if($id<=0) throw new RuntimeException('Invalid grade item.');
            beginTransaction($pdo);
            mustExecute($pdo,'DELETE FROM core_grades WHERE grade_item_id=?',[$id]);
            $stmt=$pdo->prepare('DELETE FROM core_grade_items WHERE id=?'); $stmt->execute([$id]);
            commitTransaction($pdo); flash('success','Grade item deleted.');
        }
    }catch(Throwable $e){ rollbackTransaction($pdo); flash('error',APP_DEBUG?$e->getMessage():'The operation could not be completed.'); }
    redirect('admin/grade-items.php'.($courseId>0?'?course_id='.$courseId:''));
}
$courses=safeFetchAll($pdo,"SELECT c.*,COALESCE(t.full_name,t.name) teacher_name FROM core_courses c LEFT JOIN core_teachers t ON t.id=c.teacher_id ORDER BY c.id DESC");
$where=$courseId>0?'WHERE gi.course_id=?':''; $params=$courseId>0?[$courseId]:[];
$items=safeFetchAll($pdo,"SELECT gi.*,c.title course_title,COUNT(g.id) graded_students FROM core_grade_items gi INNER JOIN core_courses c ON c.id=gi.course_id LEFT JOIN core_grades g ON g.grade_item_id=gi.id {$where} GROUP BY gi.id ORDER BY gi.id DESC",$params);
$types=['exam','homework','participation','attendance','stars','vocabulary','shadowing','obstacle','project','quiz','extra'];
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Grade Items</title><style>
*{box-sizing:border-box}body{margin:0;background:#f3f6fb;color:#0f172a;font-family:Inter,Arial,sans-serif}.page{max-width:1450px;margin:auto;padding:32px}.top{display:flex;justify-content:space-between;align-items:center;gap:18px;margin-bottom:28px}.top h1{margin:0;font-size:clamp(32px,5vw,48px)}.back{background:#e0e7ff;color:#3730a3;padding:13px 18px;border-radius:14px;text-decoration:none;font-weight:900}.grid{display:grid;grid-template-columns:minmax(300px,430px) 1fr;gap:24px}.card{background:#fff;border-radius:28px;padding:26px;box-shadow:0 18px 45px rgba(15,23,42,.07)}label{display:block;font-weight:800;margin:14px 0 8px}input,select{width:100%;padding:14px;border:1px solid #dbe3ef;border-radius:14px;font:inherit}.btn{border:0;border-radius:14px;padding:14px 18px;background:#2563eb;color:#fff;font-weight:900;cursor:pointer;width:100%;margin-top:18px}.alert{padding:14px 18px;border-radius:14px;margin-bottom:18px;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.filter{display:flex;gap:12px;margin-bottom:18px}.filter select{max-width:380px}.filter .btn{width:auto;margin:0}.table{overflow:auto}table{width:100%;border-collapse:collapse;min-width:850px}th,td{padding:14px;border-top:1px solid #e2e8f0;text-align:left}th{background:#f8fafc}.pill{padding:6px 10px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-weight:800;font-size:12px}.danger{background:#dc2626}.inline{display:inline}.inline .btn{width:auto;margin:0;padding:9px 12px}@media(max-width:950px){.grid{grid-template-columns:1fr}.page{padding:20px}}
</style></head><body><main class="page"><div class="top"><div><h1>Gradebook Structure</h1><p>Define weighted assessment items for each course.</p></div><a class="back" 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 grade item</h2><form method="post"><?=csrfField()?><input type="hidden" name="action" value="create"><label>Course</label><select name="course_id" required><option value="">Choose course</option><?php foreach($courses as $c):?><option value="<?=$c['id']?>" <?=selected($courseId,$c['id'])?>><?=e($c['title'].' — '.$c['course_code'])?></option><?php endforeach;?></select><label>Title</label><input name="title" required placeholder="Midterm exam"><label>Type</label><select name="item_type"><?php foreach($types as $type):?><option value="<?=e($type)?>"><?=e(ucwords(str_replace('_',' ',$type)))?></option><?php endforeach;?></select><label>Maximum score</label><input type="number" step="0.01" min="0.01" name="max_score" value="100"><label>Weight %</label><input type="number" step="0.01" min="0" max="100" name="weight" value="0"><button class="btn">Create item</button></form></section><section class="card"><form class="filter" method="get"><select name="course_id"><option value="0">All courses</option><?php foreach($courses as $c):?><option value="<?=$c['id']?>" <?=selected($courseId,$c['id'])?>><?=e($c['title'])?></option><?php endforeach;?></select><button class="btn">Filter</button></form><div class="table"><table><thead><tr><th>Course</th><th>Item</th><th>Type</th><th>Max</th><th>Weight</th><th>Students</th><th></th></tr></thead><tbody><?php foreach($items as $item):?><tr><td><?=e($item['course_title'])?></td><td><strong><?=e($item['title'])?></strong></td><td><span class="pill"><?=e($item['item_type']??$item['type'])?></span></td><td><?=e($item['max_score']??$item['max_points']??100)?></td><td><?=e($item['weight']??$item['weight_percent']??0)?>%</td><td><?=e($item['graded_students'])?></td><td><form class="inline" method="post" onsubmit="return confirm('Delete this item and its grades?')"><?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$item['id']?>"><input type="hidden" name="course_id" value="<?=$courseId?>"><button class="btn danger">Delete</button></form></td></tr><?php endforeach;?><?php if(!$items):?><tr><td colspan="7">No grade items found.</td></tr><?php endif;?></tbody></table></div></section></div></main></body></html>
