<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
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';require_once __DIR__ . '/../includes/grade-engine.php';
$pdo=db();if(!isPost())jsonResponse(['success'=>false,'message'=>'Method not allowed.'],405);if(!isTeacherLoggedIn())jsonResponse(['success'=>false,'message'=>'Unauthorized.'],401);if(!verifyCsrf())jsonResponse(['success'=>false,'message'=>'Invalid request token.'],419);$teacher=currentTeacher($pdo);if(!$teacher)jsonResponse(['success'=>false,'message'=>'Teacher not found.'],401);
$sessionId=(int)($_POST['session_id']??$_POST['core_session_id']??0);$studentId=(int)($_POST['student_id']??0);$minutes=max(0,min(ATTENDANCE_SESSION_DURATION,(int)($_POST['attendance_minutes']??$_POST['minutes_attended']??0)));$manual=trim((string)($_POST['status']??''));$notes=trim((string)($_POST['notes']??$_POST['note']??''));
$session=safeFetch($pdo,'SELECT * FROM core_sessions WHERE id=? AND teacher_id=? LIMIT 1',[$sessionId,(int)$teacher['id']]);if(!$session||!teacherCanAccessStudentCourse($pdo,(int)$teacher['id'],$studentId,(int)$session['course_id']))jsonResponse(['success'=>false,'message'=>'Invalid session or student.'],403);$status=attendanceStatusByMinutes($minutes);if($manual==='excused')$status='excused';$points=$status==='present'||$status==='excused'?.5:($status==='late'?.25:0);
try{$existing=safeFetch($pdo,'SELECT id,attendance_session_id FROM core_attendance WHERE student_id=? AND (core_session_id=? OR session_id=?) ORDER BY id DESC LIMIT 1',[$studentId,$sessionId,$sessionId]);if($existing){$stmt=$pdo->prepare('UPDATE core_attendance SET course_id=?,core_session_id=?,session_id=?,status=?,points_awarded=?,attendance_minutes=?,minutes_attended=?,note=?,notes=?,marked_by=?,updated_at=NOW() WHERE id=?');$stmt->execute([(int)$session['course_id'],$sessionId,$sessionId,$status,$points,$minutes,$minutes,$notes?:null,$notes?:null,(int)$teacher['id'],(int)$existing['id']]);}else{$stmt=$pdo->prepare('INSERT INTO core_attendance (session_id,student_id,course_id,core_session_id,status,points_awarded,marked_by,note,notes,attendance_minutes,minutes_attended,submitted_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW(),NOW())');$stmt->execute([$sessionId,$studentId,(int)$session['course_id'],$sessionId,$status,$points,(int)$teacher['id'],$notes?:null,$notes?:null,$minutes,$minutes]);}saveStudentGrade($pdo,$studentId,(int)$session['course_id'],'attendance',$sessionId,'Attendance — '.(string)$session['title'],$points,.5,0,$notes?:null,(int)$teacher['id'],null);logActivity($pdo,'teacher',(int)$teacher['id'],'Attendance saved','Student '.$studentId.'; session '.$sessionId.'; '.$minutes.' minutes',null,(int)$session['course_id']);jsonResponse(['success'=>true,'message'=>'Attendance saved successfully.','status'=>$status,'attendance_minutes'=>$minutes,'points'=>$points]);}catch(Throwable $e){error_log('[SMI save attendance] '.$e->getMessage());jsonResponse(['success'=>false,'message'=>APP_DEBUG?$e->getMessage():'Failed to save attendance.'],500);}
