<?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();
$isAjax=strtolower((string)($_SERVER['HTTP_X_REQUESTED_WITH']??''))==='xmlhttprequest';
$respond=function(bool $success,string $message,int $courseId=0) use($isAjax): never{
 if($isAjax) jsonResponse(['success'=>$success,'message'=>$message],$success?200:422);
 flash($success?'success':'error',$message);
 redirect('student/shadowing.php'.($courseId>0?'?course_id='.$courseId:''));
};
if(!isStudentLoggedIn()) $respond(false,'Unauthorized.');
if(!isPost()||!verifyCsrf()) $respond(false,'Invalid request token.');
$student=currentStudent($pdo); if(!$student) $respond(false,'Student not found.');
$lessonId=(int)($_POST['lesson_id']??0);$recordingLink=trim((string)($_POST['recording_link']??''));$studentNote=trim((string)($_POST['student_note']??''));
$lesson=safeFetch($pdo,'SELECT * FROM core_shadowing WHERE id=? LIMIT 1',[$lessonId]);
$courseId=(int)($lesson['course_id']??0);
if(!$lesson||!isStudentActiveInCourse($pdo,(int)$student['id'],$courseId)) $respond(false,'Shadowing lesson is unavailable.',$courseId);
if(!filter_var($recordingLink,FILTER_VALIDATE_URL)||!in_array(strtolower((string)parse_url($recordingLink,PHP_URL_SCHEME)),['http','https'],true)) $respond(false,'Enter a valid HTTPS recording link.',$courseId);
$currentLevel=(int)($lesson['shadowing_level']??1);
if($currentLevel>1){
 $previous=safeCount($pdo,"SELECT COUNT(*) FROM core_shadowing_submissions ss INNER JOIN core_shadowing sh ON sh.id=COALESCE(NULLIF(ss.lesson_id,0),NULLIF(ss.task_id,0)) WHERE ss.student_id=? AND sh.course_id=? AND sh.shadowing_level=? AND ss.status IN ('approved','submitted','reviewed')",[(int)$student['id'],$courseId,$currentLevel-1]);
 if($previous===0) $respond(false,'Complete the previous shadowing level first.',$courseId);
}
try{
 $existing=safeFetch($pdo,'SELECT id FROM core_shadowing_submissions WHERE student_id=? AND (lesson_id=? OR task_id=?) ORDER BY id DESC LIMIT 1',[(int)$student['id'],$lessonId,$lessonId]);
 if($existing){$stmt=$pdo->prepare("UPDATE core_shadowing_submissions SET lesson_id=?,task_id=?,recording_url=?,recording_link=?,student_note=?,status='submitted',score=0,teacher_note=NULL,submitted_at=NOW(),reviewed_at=NULL,reviewed_by=NULL WHERE id=?");$stmt->execute([$lessonId,$lessonId,$recordingLink,$recordingLink,$studentNote,(int)$existing['id']]);}
 else{$stmt=$pdo->prepare("INSERT INTO core_shadowing_submissions (lesson_id,task_id,student_id,recording_url,recording_link,student_note,status,submitted_at) VALUES (?,?,?,?,?,?,'submitted',NOW())");$stmt->execute([$lessonId,$lessonId,(int)$student['id'],$recordingLink,$recordingLink,$studentNote]);}
 logActivity($pdo,'student',(int)$student['id'],'shadowing_submitted','Submitted shadowing task #'.$lessonId,null,$courseId);
 $respond(true,'Shadowing recording submitted successfully.',$courseId);
}catch(Throwable $e){error_log('[SMI shadowing] '.$e->getMessage());$respond(false,APP_DEBUG?$e->getMessage():'Submission failed.',$courseId);}
