<?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/homework.php');}
$student=currentStudent($pdo);if(!$student){studentLogout();redirect('login.php');}
$id=(int)($_POST['homework_id']??0);
$homework=safeFetch($pdo,"SELECT * FROM core_homework WHERE id=? AND status='active' LIMIT 1",[$id]);
$courseId=(int)($homework['course_id']??0);
$back='student/homework.php'.($courseId>0?'?course_id='.$courseId:'');
if(!$homework||!isStudentActiveInCourse($pdo,(int)$student['id'],$courseId)){flash('error','Homework is unavailable for your course.');redirect($back);}
if(!empty($homework['due_date'])&&strtotime((string)$homework['due_date'].' 23:59:59')<time()){$late=true;}else{$late=false;}
$existing=safeFetch($pdo,'SELECT * FROM core_homework_submissions WHERE homework_id=? AND student_id=? LIMIT 1',[$id,(int)$student['id']]);
$text=trim((string)($_POST['submission_text']??''));$url=trim((string)($_POST['submission_url']??''));$filePath=$existing['file_path']??null;
if($url!==''&&(!filter_var($url,FILTER_VALIDATE_URL)||!in_array(strtolower((string)parse_url($url,PHP_URL_SCHEME)),['http','https'],true))){flash('error','Enter a valid HTTP or HTTPS submission link.');redirect($back);}
if(isset($_FILES['homework_file'])&&($_FILES['homework_file']['error']??UPLOAD_ERR_NO_FILE)!==UPLOAD_ERR_NO_FILE){$uploaded=uploadFile($_FILES['homework_file'],'homework');if(!$uploaded){flash('error','The uploaded file type or size is not allowed.');redirect($back);}$filePath=$uploaded;}
if(!$filePath&&$text===''&&$url===''){flash('error','Upload a file, paste a link, or write your answer.');redirect($back);}
try{$pdo->beginTransaction();
 if($existing){$stmt=$pdo->prepare("UPDATE core_homework_submissions SET submission_text=?,submission_url=?,file_path=?,status=?,submitted_at=NOW(),score=0,teacher_note=NULL,reviewed_at=NULL,reviewed_by=NULL WHERE id=?");$stmt->execute([$text?:null,$url?:null,$filePath,$late?'late':'submitted',(int)$existing['id']]);}
 else{$stmt=$pdo->prepare("INSERT INTO core_homework_submissions (homework_id,student_id,submission_text,submission_url,file_path,score,status,submitted_at) VALUES (?,?,?,?,?,0,?,NOW())");$stmt->execute([$id,(int)$student['id'],$text?:null,$url?:null,$filePath,$late?'late':'submitted']);}
 if(tableExists($pdo,'core_notifications')){$stmt=$pdo->prepare('INSERT INTO core_notifications (student_id,title,message,is_read,created_at) VALUES (?,?,?,0,NOW())');$stmt->execute([(int)$student['id'],'Homework submitted','Your homework “'.substr((string)$homework['title'],0,120).'” was received and is awaiting review.']);}
 logActivity($pdo,'student',(int)$student['id'],'Homework submitted','Homework ID '.$id,null,$courseId);$pdo->commit();flash('success','Homework submitted successfully and is awaiting teacher review.');redirect($back);
}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();error_log('[SMI homework submission] '.$e->getMessage());flash('error',APP_DEBUG?$e->getMessage():'Homework submission failed.');redirect($back);}
