<?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/student-auth.php';require_once __DIR__ . '/../includes/student-course-context.php';
$pdo=db();if(!isStudentLoggedIn())redirect('login.php');if(!isPost()||!verifyCsrf()){flash('error','Invalid or expired request token.');redirect('student/obstacles.php');}$student=currentStudent($pdo);if(!$student){studentLogout();redirect('login.php');}
$stepId=(int)($_POST['step_id']??0);$note=trim((string)($_POST['student_note']??''));$url=trim((string)($_POST['submission_url']??''));
$step=safeFetch($pdo,'SELECT s.*,o.course_id,o.is_active AS obstacle_active FROM core_obstacle_steps s INNER JOIN core_obstacles o ON o.id=s.obstacle_id WHERE s.id=? LIMIT 1',[$stepId]);$courseId=(int)($step['course_id']??0);$back='student/obstacles.php'.($courseId>0?'?course_id='.$courseId:'');
if(!$step||!(int)$step['is_active']||!(int)$step['obstacle_active']||!isStudentActiveInCourse($pdo,(int)$student['id'],$courseId)){flash('error','Obstacle step is unavailable.');redirect($back);}if($note===''&&$url===''){flash('error','Write what you learned or provide a proof link.');redirect($back);}if($url!==''&&!filter_var($url,FILTER_VALIDATE_URL)){flash('error','Enter a valid submission link.');redirect($back);}
$previousOrder=(int)$step['step_order']-1;if($previousOrder>0){$done=safeCount($pdo,"SELECT COUNT(*) FROM core_obstacle_submissions os INNER JOIN core_obstacle_steps ps ON ps.id=os.step_id WHERE os.student_id=? AND ps.obstacle_id=? AND ps.step_order=? AND os.status IN ('submitted','approved')",[(int)$student['id'],(int)$step['obstacle_id'],$previousOrder]);if($done===0){flash('error','Complete the previous step first.');redirect($back);}}
try{$existing=safeFetch($pdo,'SELECT id FROM core_obstacle_submissions WHERE step_id=? AND student_id=? LIMIT 1',[$stepId,(int)$student['id']]);if($existing){$stmt=$pdo->prepare("UPDATE core_obstacle_submissions SET submission_url=?,student_note=?,status='submitted',score=0,teacher_note=NULL,submitted_at=NOW(),reviewed_at=NULL,reviewed_by=NULL WHERE id=?");$stmt->execute([$url?:null,$note?:null,(int)$existing['id']]);}else{$stmt=$pdo->prepare("INSERT INTO core_obstacle_submissions (step_id,student_id,submission_url,student_note,status,score,submitted_at) VALUES (?,?,?,?,'submitted',0,NOW())");$stmt->execute([$stepId,(int)$student['id'],$url?:null,$note?:null]);}logActivity($pdo,'student',(int)$student['id'],'Obstacle step submitted','Step ID '.$stepId,null,$courseId);flash('success','Obstacle step submitted successfully.');redirect($back);}catch(Throwable $e){error_log('[SMI obstacle submission] '.$e->getMessage());flash('error',APP_DEBUG?$e->getMessage():'Obstacle submission failed.');redirect($back);}
