<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Validate input
if (!isset($input['exam_id']) || !isset($input['student_id']) || !isset($input['is_absent'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$exam_id = (int)$input['exam_id'];
$student_id = (int)$input['student_id'];
$is_absent = (bool)$input['is_absent'];

try {
    // Get all subjects for this exam
    $stmt = $pdo->prepare("
        SELECT es.subject_id, es.exam_date
        FROM exam_subjects es
        WHERE es.exam_id = ?
    ");
    $stmt->execute([$exam_id]);
    $subjects = $stmt->fetchAll();
    
    if (empty($subjects)) {
        echo json_encode(['success' => false, 'message' => 'No subjects found for this exam']);
        exit();
    }
    
    // Begin transaction
    $pdo->beginTransaction();
    
    // Update attendance status for all subjects
    foreach ($subjects as $subject) {
        $subject_id = $subject['subject_id'];
        $exam_date = $subject['exam_date'];
        $attendance_status = $is_absent ? 'absent' : 'present';
        
        // Insert or update exam attendance record
        $stmt = $pdo->prepare("
            INSERT INTO exam_attendance 
            (exam_id, subject_id, student_id, attendance_status, exam_date)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
            attendance_status = VALUES(attendance_status),
            updated_at = CURRENT_TIMESTAMP
        ");
        $stmt->execute([
            $exam_id, 
            $subject_id, 
            $student_id, 
            $attendance_status, 
            $exam_date
        ]);
    }
    
    // Commit transaction
    $pdo->commit();
    
    echo json_encode(['success' => true, 'message' => 'Attendance updated successfully']);
    
} catch (Exception $e) {
    // Rollback transaction
    $pdo->rollBack();
    
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>