<?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/teacher-auth.php';require_once __DIR__ . '/../includes/teacher-course-context.php';
$pdo=db();requireTeacher();$teacher=currentTeacher($pdo);if(!$teacher){teacherLogout();redirect('teacher/login.php');}$courses=getTeacherCourses($pdo,(int)$teacher['id']);$courseId=(int)($_GET['course_id']??$_POST['course_id']??($courses[0]['id']??0));$error='';$success=flash('success')?:'';
if(isPost()){requireCsrf();$action=(string)($_POST['action']??'');try{
 if($action==='create_program'){$courseId=(int)$_POST['course_id'];if(!teacherOwnsCourse($pdo,(int)$teacher['id'],$courseId))throw new RuntimeException('Invalid course.');$title=trim((string)$_POST['title']);$description=trim((string)($_POST['description']??''));$level=(string)($_POST['level']??'beginner');$days=max(1,min(60,(int)($_POST['duration_days']??7)));if($title===''||!in_array($level,['beginner','intermediate','advanced'],true))throw new RuntimeException('Program title and level are required.');$stmt=$pdo->prepare('INSERT INTO core_obstacles (course_id,teacher_id,level,title,description,duration_days,is_active,created_at,step_number,points) VALUES (?,?,?,?,?,?,1,NOW(),1,0)');$stmt->execute([$courseId,(int)$teacher['id'],$level,$title,$description?:null,$days]);flash('success','Obstacle-removal program created.');}
 elseif($action==='add_step'){$programId=(int)($_POST['program_id']??0);$program=safeFetch($pdo,'SELECT o.* FROM core_obstacles o INNER JOIN core_courses c ON c.id=o.course_id WHERE o.id=? AND c.teacher_id=? LIMIT 1',[$programId,(int)$teacher['id']]);if(!$program)throw new RuntimeException('Program not found.');$title=trim((string)$_POST['step_title']);$instructions=trim((string)($_POST['instructions']??''));$resource=trim((string)($_POST['resource_url']??''));$points=max(0,(float)($_POST['points']??5));if($title==='')throw new RuntimeException('Step title is required.');if($resource!==''&&!filter_var($resource,FILTER_VALIDATE_URL))throw new RuntimeException('Resource URL is invalid.');$order=(int)safeCount($pdo,'SELECT COALESCE(MAX(step_order),0)+1 FROM core_obstacle_steps WHERE obstacle_id=?',[$programId]);$stmt=$pdo->prepare('INSERT INTO core_obstacle_steps (obstacle_id,step_order,title,instructions,resource_url,requires_submission,points,is_active,created_at) VALUES (?,?,?,?,?,1,?,1,NOW())');$stmt->execute([$programId,$order,$title,$instructions?:null,$resource?:null,$points]);flash('success','Program step added.');$courseId=(int)$program['course_id'];}
 elseif($action==='delete_step'){$id=(int)($_POST['step_id']??0);$owned=safeFetch($pdo,'SELECT s.id,o.course_id FROM core_obstacle_steps s INNER JOIN core_obstacles o ON o.id=s.obstacle_id INNER JOIN core_courses c ON c.id=o.course_id WHERE s.id=? AND c.teacher_id=?',[$id,(int)$teacher['id']]);if(!$owned)throw new RuntimeException('Step not found.');mustExecute($pdo,'DELETE FROM core_obstacle_steps WHERE id=?',[$id]);flash('success','Step deleted.');$courseId=(int)$owned['course_id'];}
 elseif($action==='toggle_program'){$id=(int)($_POST['program_id']??0);$program=safeFetch($pdo,'SELECT o.id,o.course_id,o.is_active FROM core_obstacles o INNER JOIN core_courses c ON c.id=o.course_id WHERE o.id=? AND c.teacher_id=?',[$id,(int)$teacher['id']]);if(!$program)throw new RuntimeException('Program not found.');mustExecute($pdo,'UPDATE core_obstacles SET is_active=? WHERE id=?',[(int)!$program['is_active'],$id]);flash('success','Program status updated.');$courseId=(int)$program['course_id'];}
 logActivity($pdo,'teacher',(int)$teacher['id'],'Obstacle system updated','Action '.$action,null,$courseId);redirect('teacher/obstacles.php?course_id='.$courseId);
}catch(Throwable $e){error_log('[SMI teacher obstacles] '.$e->getMessage());$error=APP_DEBUG?$e->getMessage():'The requested obstacle action failed.';}}
$programs=$courseId&&teacherOwnsCourse($pdo,(int)$teacher['id'],$courseId)?safeFetchAll($pdo,"SELECT o.*,(SELECT COUNT(*) FROM core_obstacle_steps s WHERE s.obstacle_id=o.id) AS step_count FROM core_obstacles o WHERE o.course_id=? ORDER BY o.id DESC",[$courseId]):[];$steps=[];foreach($programs as $p){$steps[(int)$p['id']]=safeFetchAll($pdo,'SELECT * FROM core_obstacle_steps WHERE obstacle_id=? ORDER BY step_order,id',[(int)$p['id']]);}
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Obstacle Programs · SMI</title><style>:root{font-family:Inter,Arial,sans-serif;background:#f3f6fb;color:#0f172a}*{box-sizing:border-box}body{margin:0}.page{max-width:1450px;margin:auto;padding:30px}.top,.bar{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap}.top h1{font-size:44px;margin:0}.btn{border:0;border-radius:13px;padding:10px 14px;background:#2563eb;color:#fff;text-decoration:none;font-weight:850;cursor:pointer}.red{background:#dc2626}.muted{background:#e2e8f0;color:#0f172a}.bar{background:white;padding:16px;border-radius:20px;margin:22px 0}.bar select,input,textarea{border:1px solid #dbe3ef;border-radius:11px;padding:10px;font:inherit}.layout{display:grid;grid-template-columns:380px 1fr;gap:20px}.card{background:white;border-radius:24px;padding:21px;box-shadow:0 15px 42px rgba(15,23,42,.07)}label{display:block;font-size:13px;font-weight:850;margin-top:11px}input,select,textarea{width:100%;border:1px solid #dbe3ef;border-radius:11px;padding:10px;margin-top:5px;font:inherit}textarea{min-height:78px}.program{background:white;border-radius:24px;padding:22px;margin-bottom:17px;box-shadow:0 15px 42px rgba(15,23,42,.07)}.program-head{display:flex;justify-content:space-between;gap:12px}.pill{padding:5px 9px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:12px;font-weight:850}.step{border-top:1px solid #e2e8f0;padding:14px 0;display:grid;grid-template-columns:42px 1fr auto;gap:12px}.order{width:36px;height:36px;display:grid;place-items:center;border-radius:11px;background:#f1f5f9;font-weight:900}.meta{color:#64748b;font-size:13px;line-height:1.7}.alert{padding:14px 18px;border-radius:14px;margin:16px 0;font-weight:800}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}@media(max-width:950px){.layout{grid-template-columns:1fr}.page{padding:18px}.top h1{font-size:34px}}</style></head><body><main class="page"><div class="top"><div><h1>Obstacle-removal programs</h1><p>Build a structured program, then add ordered steps for students.</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;?><form class="bar" method="get"><label style="margin:0">Course<select name="course_id" onchange="this.form.submit()"><?php foreach($courses as $c):?><option value="<?=$c['id']?>" <?=selected($courseId,$c['id'])?>><?=e($c['title'].' — '.$c['course_code'])?></option><?php endforeach;?></select></label></form><div class="layout"><section class="card"><h2>New program</h2><form method="post"><?=csrfField()?><input type="hidden" name="action" value="create_program"><input type="hidden" name="course_id" value="<?=$courseId?>"><label>Program title<input name="title" required></label><label>Description<textarea name="description"></textarea></label><label>Level<select name="level"><option>beginner</option><option>intermediate</option><option>advanced</option></select></label><label>Duration days<input type="number" name="duration_days" min="1" max="60" value="7"></label><button class="btn" style="width:100%;margin-top:14px">Create program</button></form></section><section><?php foreach($programs as $p):?><article class="program"><div class="program-head"><div><span class="pill"><?=e($p['level'])?></span><h2><?=e($p['title'])?></h2><p class="meta"><?=e($p['description'])?><br><?=e($p['step_count'])?> steps · <?=e($p['duration_days'])?> days · <?= $p['is_active']?'Active':'Paused' ?></p></div><form method="post"><?=csrfField()?><input type="hidden" name="action" value="toggle_program"><input type="hidden" name="program_id" value="<?=$p['id']?>"><button class="btn muted"><?= $p['is_active']?'Pause':'Activate' ?></button></form></div><?php foreach($steps[(int)$p['id']] as $st):?><div class="step"><div class="order"><?=e($st['step_order'])?></div><div><strong><?=e($st['title'])?></strong><div class="meta"><?=e($st['instructions'])?> · <?=e($st['points'])?> points</div><?php if($st['resource_url']):?><a target="_blank" rel="noopener" href="<?=e($st['resource_url'])?>">Resource</a><?php endif;?></div><form method="post" onsubmit="return confirm('Delete this step?')"><?=csrfField()?><input type="hidden" name="action" value="delete_step"><input type="hidden" name="step_id" value="<?=$st['id']?>"><button class="btn red">Delete</button></form></div><?php endforeach;?><form method="post" class="card" style="box-shadow:none;border:1px dashed #cbd5e1;margin-top:12px"><?=csrfField()?><input type="hidden" name="action" value="add_step"><input type="hidden" name="program_id" value="<?=$p['id']?>"><h3>Add next step</h3><label>Step title<input name="step_title" required></label><label>Instructions<textarea name="instructions"></textarea></label><label>Resource URL<input type="url" name="resource_url"></label><label>Points<input type="number" name="points" min="0" step="0.5" value="5"></label><button class="btn" style="margin-top:12px">Add step</button></form></article><?php endforeach;?><?php if(!$programs):?><div class="card"><p class="meta">No programs have been created for this course.</p></div><?php endif;?></section></div></main></body></html>
