<?php
header('Content-Type: application/json');
require_once '../../config/config.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid JSON input'
        ]);
        exit;
    }
    
    $timetable_id = $input['timetable_id'] ?? null;
    $attendance_data = $input['attendance_data'] ?? [];
    $marked_by = $input['marked_by'] ?? null;
    $default_status = $input['default_status'] ?? 'Present';
    
    if (!$timetable_id || empty($attendance_data)) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Timetable ID and attendance data are required'
        ]);
        exit;
    }
    
    // Check if timetable exists
    $checkTimetable = $pdo->prepare("SELECT et.timetable_id, et.exam_date, et.session, s.subject_name 
                                   FROM exam_timetable et 
                                   JOIN exam_subjects es ON et.exam_subject_id = es.exam_subject_id
                                   JOIN subjects s ON es.subject_id = s.subject_id
                                   WHERE et.timetable_id = ?");
    $checkTimetable->execute([$timetable_id]);
    $timetable = $checkTimetable->fetch(PDO::FETCH_ASSOC);
    
    if (!$timetable) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Exam timetable not found'
        ]);
        exit;
    }
    
    // Get all registrations for this timetable
    $getRegistrations = $pdo->prepare("SELECT sr.registration_id, s.first_name, s.last_name, s.university_rollno
                                      FROM student_registrations sr
                                      JOIN students s ON sr.student_id = s.student_id
                                      JOIN exam_subjects es ON sr.exam_subject_id = es.exam_subject_id
                                      JOIN exam_timetable et ON es.exam_subject_id = et.exam_subject_id
                                      WHERE et.timetable_id = ?");
    $getRegistrations->execute([$timetable_id]);
    $allRegistrations = $getRegistrations->fetchAll(PDO::FETCH_ASSOC);
    
    $results = [
        'updated' => 0,
        'created' => 0,
        'skipped' => 0,
        'errors' => []
    ];
    
    // Process each attendance record
    foreach ($attendance_data as $attendance) {
        $registration_id = $attendance['registration_id'] ?? null;
        $status = $attendance['attendance_status'] ?? $default_status;
        $remarks = $attendance['remarks'] ?? null;
        $is_late = $attendance['is_late'] ?? 0;
        $late_minutes = $attendance['late_minutes'] ?? null;
        
        if (!$registration_id) {
            $results['errors'][] = 'Missing registration_id in attendance data';
            continue;
        }
        
        if (!in_array($status, ['Present', 'Absent'])) {
            $results['errors'][] = "Invalid attendance status for registration_id: $registration_id";
            continue;
        }
        
        try {
            // Check if attendance already exists
            $existing = $pdo->prepare("SELECT attendance_id FROM tbl_exam_attendance WHERE registration_id = ?");
            $existing->execute([$registration_id]);
            $existingRecord = $existing->fetch(PDO::FETCH_ASSOC);
            
            if ($existingRecord) {
                // Update existing record
                $update = $pdo->prepare("UPDATE tbl_exam_attendance 
                                        SET attendance_status = ?, marked_by = ?, remarks = ?, is_late = ?, late_minutes = ?, marked_at = CURRENT_TIMESTAMP 
                                        WHERE registration_id = ?");
                $update->execute([$status, $marked_by, $remarks, $is_late, $late_minutes, $registration_id]);
                $results['updated']++;
            } else {
                // Create new record
                $insert = $pdo->prepare("INSERT INTO tbl_exam_attendance 
                                         (registration_id, timetable_id, attendance_status, marked_by, remarks, is_late, late_minutes) 
                                         VALUES (?, ?, ?, ?, ?, ?, ?)");
                $insert->execute([$registration_id, $timetable_id, $status, $marked_by, $remarks, $is_late, $late_minutes]);
                $results['created']++;
            }
            
        } catch (Exception $e) {
            $results['errors'][] = "Error processing registration_id $registration_id: " . $e->getMessage();
        }
    }
    
    // Mark remaining students as default status if not specified
    $specifiedRegistrations = array_column($attendance_data, 'registration_id');
    foreach ($allRegistrations as $reg) {
        if (!in_array($reg['registration_id'], $specifiedRegistrations)) {
            try {
                $existing = $pdo->prepare("SELECT attendance_id FROM tbl_exam_attendance WHERE registration_id = ?");
                $existing->execute([$reg['registration_id']]);
                $existingRecord = $existing->fetch(PDO::FETCH_ASSOC);
                
                if (!$existingRecord) {
                    $insert = $pdo->prepare("INSERT INTO tbl_exam_attendance 
                                             (registration_id, timetable_id, attendance_status, marked_by) 
                                             VALUES (?, ?, ?, ?)");
                    $insert->execute([$reg['registration_id'], $timetable_id, $default_status, $marked_by]);
                    $results['created']++;
                } else {
                    $results['skipped']++;
                }
            } catch (Exception $e) {
                $results['errors'][] = "Error processing default status for registration_id {$reg['registration_id']}: " . $e->getMessage();
            }
        }
    }
    
    $message = "Bulk attendance marking completed. Created: {$results['created']}, Updated: {$results['updated']}, Skipped: {$results['skipped']}";
    if (!empty($results['errors'])) {
        $message .= ". Errors: " . count($results['errors']);
    }
    
    echo json_encode([
        'status' => 'success',
        'message' => $message,
        'data' => $results
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
