<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');
try {
    $id=(int)($_POST['id']??0);
    $exam_id=(int)($_POST['exam_id']??0);
    $subject_id=(int)($_POST['subject_id']??0);
    $max_marks=(int)($_POST['max_marks']??0);
    $pass_marks=(int)($_POST['pass_marks']??0);
    $exam_date=trim($_POST['exam_date']??'');
    $session=trim($_POST['session']??'');
    $errors=[]; if($id<=0)$errors[]='Invalid ID.'; if($exam_id<=0)$errors[]='Exam required.'; if($subject_id<=0)$errors[]='Subject required.'; if($max_marks<=0)$errors[]='Max marks required.'; if($pass_marks<0)$errors[]='Pass marks required.'; if($errors){ echo json_encode(['status'=>'error','message'=>$errors]); exit; }
    $before=null; try{ $b=$pdo->prepare('SELECT * FROM exam_subjects WHERE exam_subject_id=?'); $b->execute([$id]); $before=$b->fetch(PDO::FETCH_ASSOC);}catch(Throwable $e){}
    
    // Update exam_subjects table
    $stmt=$pdo->prepare('UPDATE exam_subjects SET exam_id=?, subject_id=?, max_marks=?, pass_marks=?, exam_date=?, session=? WHERE exam_subject_id=?');
    $stmt->execute([$exam_id,$subject_id,$max_marks,$pass_marks,empty($exam_date)?null:$exam_date,empty($session)?null:$session,$id]);
    
    // Also update exam_timetable table if exam_date or session is provided
    if (!empty($exam_date) || !empty($session)) {
        // Check if exam_timetable entry exists
        $checkStmt = $pdo->prepare('SELECT timetable_id FROM exam_timetable WHERE exam_subject_id = ? LIMIT 1');
        $checkStmt->execute([$id]);
        $timetableId = $checkStmt->fetchColumn();
        
        if ($timetableId) {
            // Update existing exam_timetable entry
            $updateTtStmt = $pdo->prepare('UPDATE exam_timetable SET exam_date=?, session=? WHERE exam_subject_id=?');
            $updateTtStmt->execute([empty($exam_date)?null:$exam_date, empty($session)?null:$session, $id]);
        } else {
            // Create new exam_timetable entry
            $insertTtStmt = $pdo->prepare('INSERT INTO exam_timetable (exam_subject_id, exam_date, session, start_time, end_time) VALUES (?, ?, ?, ?, ?)');
            $insertTtStmt->execute([$id, empty($exam_date)?null:$exam_date, empty($session)?null:$session, '10:00:00', '13:00:00']);
        }
    }
    
    write_audit_log($pdo, ['module'=>'Exam','action'=>'update','entity_table'=>'exam_subjects','entity_id'=>$id,'before_data'=>$before,'after_data'=>compact('exam_id','subject_id','max_marks','pass_marks','exam_date','session'),'message'=>'Exam subject updated']);
    echo json_encode(['status'=>'success','message'=>'Exam Subject updated successfully.']);
} catch (Throwable $e){ http_response_code(500); echo json_encode(['status'=>'error','message'=>$e->getMessage()]); }
?>


