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

// Function to check and fix attendance table structure
function ensureAttendanceTableStructure($pdo) {
    try {
        // Check current structure of attendance table
        $columnsStmt = $pdo->query("SHOW COLUMNS FROM attendance");
        $columns = $columnsStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Build a map of current column definitions
        $columnMap = [];
        foreach ($columns as $col) {
            $columnMap[$col['Field']] = $col;
        }
        
        // Ensure student_id column allows NULL for teacher attendance
        if (isset($columnMap['student_id']) && $columnMap['student_id']['Null'] === 'NO') {
            $pdo->exec("ALTER TABLE attendance MODIFY COLUMN student_id INT NULL DEFAULT NULL");
            error_log('Modified student_id column to allow NULL');
        }
        
        // Ensure teacher_id column allows NULL
        if (isset($columnMap['teacher_id']) && $columnMap['teacher_id']['Null'] === 'NO') {
            $pdo->exec("ALTER TABLE attendance MODIFY COLUMN teacher_id INT NULL DEFAULT NULL");
            error_log('Modified teacher_id column to allow NULL');
        }
        
        // Ensure class_id column allows NULL
        if (isset($columnMap['class_id']) && $columnMap['class_id']['Null'] === 'NO') {
            $pdo->exec("ALTER TABLE attendance MODIFY COLUMN class_id INT NULL DEFAULT NULL");
            error_log('Modified class_id column to allow NULL');
        }
        
        // Check if the indexes exist and create them if needed
        $indexesStmt = $pdo->query("SHOW INDEX FROM attendance");
        $indexes = $indexesStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $indexNames = [];
        foreach ($indexes as $idx) {
            $indexNames[$idx['Key_name']] = true;
        }
        
        // Add unique index for teacher attendance if it doesn't exist
        if (!isset($indexNames['unique_teacher_date'])) {
            try {
                $pdo->exec("ALTER TABLE attendance ADD UNIQUE KEY unique_teacher_date (teacher_id, date)");
                error_log('Added unique_teacher_date index');
            } catch (PDOException $e) {
                // Index may conflict, try alternative
                error_log('Could not add unique_teacher_date index: ' . $e->getMessage());
            }
        }
        
        // Add unique index for student attendance if it doesn't exist
        if (!isset($indexNames['unique_student_date'])) {
            try {
                $pdo->exec("ALTER TABLE attendance ADD UNIQUE KEY unique_student_date (student_id, date)");
                error_log('Added unique_student_date index');
            } catch (PDOException $e) {
                // Index may conflict, try alternative
                error_log('Could not add unique_student_date index: ' . $e->getMessage());
            }
        }
        
    } catch (PDOException $e) {
        // Log the error but don't show to user
        error_log('Attendance table structure check error: ' . $e->getMessage());
    }
}

// Ensure attendance table has correct structure
ensureAttendanceTableStructure($pdo);

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

// Get system name for branding
$system_name = get_system_name($pdo);

// Handle auto attendance AJAX requests
if (isset($_POST['action']) && $_POST['action'] === 'mark_attendance' && isset($_POST['teacher_id'])) {
    $teacher_id = (int)$_POST['teacher_id'];
    $date = $_POST['date'] ?? date('Y-m-d');
    
    // Check if user is teacher and trying to mark attendance for themselves
    if ($_SESSION['user_role'] === 'teacher') {
        // Get the teacher ID linked to this user account
        $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user_teacher = $stmt->fetch();
        
        if (!$user_teacher || $user_teacher['id'] != $teacher_id) {
            echo json_encode(['success' => false, 'message' => 'You can only mark attendance for yourself']);
            exit;
        }
    }
    
    try {
        // Check if attendance already exists for this teacher on this date
        $check_stmt = $pdo->prepare("SELECT id, created_at, status, remarks FROM attendance WHERE teacher_id = ? AND date = ?");
        $check_stmt->execute([$teacher_id, $date]);
        $existing_attendance = $check_stmt->fetch();
        
        // Check if attendance already exists for this teacher on this date
        $check_stmt = $pdo->prepare("SELECT id, created_at, status, remarks FROM attendance WHERE teacher_id = ? AND date = ?");
        $check_stmt->execute([$teacher_id, $date]);
        $existing_attendance = $check_stmt->fetch();
                
        $status = 'present';
        $remarks = 'শিক্ষক রেজিস্ট্রেশন ক্যামেরা - Auto-marked via camera';
                
        // Check if there's already an out-time record for today
        $check_out_time_stmt = $pdo->prepare("SELECT id FROM attendance WHERE teacher_id = ? AND date = ? AND remarks LIKE '%প্রস্থান%'");
        $check_out_time_stmt->execute([$teacher_id, $date]);
        $has_out_time = $check_out_time_stmt->fetch();
        
        if ($existing_attendance) {
            // Calculate time difference between first scan and current scan
            $first_scan_time = $existing_attendance['created_at'];
            $time_diff = strtotime(date('Y-m-d H:i:s')) - strtotime($first_scan_time);
            $minutes_diff = floor(abs($time_diff) / 60);
            
            // If we already have an out-time, this should be treated as a new in-time for the next session
            if ($has_out_time) {
                // This is likely the start of a new session after leaving
                $status = 'present';
                $remarks = 'প্রবেশ - ক্যামেরা স্ক্যান (' . date('H:i:s') . ') | নতুন সেশন';
                
                // Insert a new record instead of updating
                $stmt = $pdo->prepare(
                    "INSERT INTO attendance (student_id, teacher_id, class_id, date, status, remarks, marked_by, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
                );
                $stmt->execute([NULL, $teacher_id, NULL, $date, $status, $remarks, $_SESSION['user_id']]);
            } else {
                // Determine if this is within the first 30 minutes of the first scan
                if ($minutes_diff <= 30) {
                    // Within 30 minutes, update the existing in-time record
                    $status = 'present';
                    $remarks = 'প্রবেশ - ক্যামেরা স্ক্যান (' . date('H:i:s') . ') | ৩০ মিনিটের মধ্যে পুনঃস্ক্যান';
                } else {
                    // More than 30 minutes, update as out-time
                    $status = 'late';
                    $remarks = 'প্রস্থান - ক্যামেরা স্ক্যান (' . date('H:i:s') . ') | ৩০ মিনিট পরে স্ক্যান';
                }
                
                // Update the existing attendance record
                $stmt = $pdo->prepare(
                    "UPDATE attendance SET status = ?, remarks = ?, marked_by = ?, updated_at = CURRENT_TIMESTAMP 
                    WHERE teacher_id = ? AND date = ?"
                );
                $stmt->execute([$status, $remarks, $_SESSION['user_id'], $teacher_id, $date]);
            }
        } else {
            // First scan of the day, insert new record as in-time
            $status = 'present';
            $remarks = 'প্রবেশ - ক্যামেরা স্ক্যান (' . date('H:i:s') . ') | প্রথম উপস্থিতি';
            
            $stmt = $pdo->prepare(
                "INSERT INTO attendance (student_id, teacher_id, class_id, date, status, remarks, marked_by, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
            );
            $stmt->execute([NULL, $teacher_id, NULL, $date, $status, $remarks, $_SESSION['user_id']]);
        }
                
        $response_message = ($status === 'present') ? 'Check-in marked successfully' : 'Check-out marked successfully';
        echo json_encode(['success' => true, 'message' => $response_message, 'status' => $status]);
    } catch (PDOException $e) {
        error_log('Database error in attendance marking: ' . $e->getMessage());
        error_log('SQL State: ' . $e->getCode());
        echo json_encode(['success' => false, 'message' => 'Database error: Error marking attendance: ' . $e->getMessage()]);
    } catch (Exception $e) {
        error_log('General error in attendance marking: ' . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Error marking attendance: ' . $e->getMessage()]);
    }
    exit;
}

// Handle getting attendance data
if (isset($_POST['action']) && $_POST['action'] === 'get_attendance_data' && isset($_POST['attendance_id'])) {
    $attendance_id = (int)$_POST['attendance_id'];
    
    try {
        $stmt = $pdo->prepare(
            "SELECT a.*, CONCAT(t.first_name, ' ', t.last_name) AS teacher_name 
            FROM attendance a 
            LEFT JOIN teachers t ON a.teacher_id = t.id 
            WHERE a.id = ?"
        );
        $stmt->execute([$attendance_id]);
        $attendance = $stmt->fetch();
        
        if ($attendance) {
            echo json_encode(['success' => true, 'attendance' => $attendance]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Attendance record not found']);
        }
    } catch (PDOException $e) {
        error_log('Error fetching attendance data: ' . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// Handle updating full attendance record
if (isset($_POST['action']) && $_POST['action'] === 'update_full_attendance') {
    // Prevent teachers from editing attendance records
    if ($_SESSION['user_role'] === 'teacher') {
        echo json_encode(['success' => false, 'message' => 'Teachers cannot edit attendance records']);
        exit;
    }
    
    $attendance_id = (int)$_POST['attendance_id'];
    $date = $_POST['date'];
    $status = $_POST['status'];
    $in_time = $_POST['in_time'];
    $out_time = $_POST['out_time'];
    $remarks = $_POST['remarks'];
    
    // Validate inputs
    if (empty($date) || empty($status) || empty($in_time)) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit;
    }
    
    try {
        // If out_time is provided and different from in_time, we may need to handle this differently
        // For now, we'll update the main record with in_time
        $stmt = $pdo->prepare(
            "UPDATE attendance 
            SET date = ?, status = ?, created_at = ?, remarks = ?, updated_at = CURRENT_TIMESTAMP 
            WHERE id = ?"
        );
        $result = $stmt->execute([$date, $status, $in_time, $remarks, $attendance_id]);
        
        if ($result) {
            // If out_time is provided, we might need to create or update a separate record
            // For now, we'll just update the main record
            echo json_encode(['success' => true, 'message' => 'Attendance record updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update attendance record']);
        }
    } catch (PDOException $e) {
        error_log('Error updating attendance record: ' . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// Handle resetting today's attendance records
if (isset($_POST['action']) && $_POST['action'] === 'reset_today_attendance') {
    // Prevent teachers from resetting attendance records
    if ($_SESSION['user_role'] === 'teacher') {
        echo json_encode(['success' => false, 'message' => 'Teachers cannot reset attendance records']);
        exit;
    }
    
    $date = date('Y-m-d'); // Today's date
    
    try {
        // Delete all attendance records for today
        $stmt = $pdo->prepare("DELETE FROM attendance WHERE date = ? AND teacher_id IS NOT NULL");
        $result = $stmt->execute([$date]);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Today\'s attendance records reset successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to reset attendance records']);
        }
    } catch (PDOException $e) {
        error_log('Error resetting today\'s attendance: ' . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// Handle attendance reset
if (isset($_POST['action']) && $_POST['action'] === 'reset_attendance_time' && isset($_POST['attendance_id'])) {
    $attendance_id = (int)$_POST['attendance_id'];
    
    try {
        // Get the original attendance record to restore defaults
        $stmt = $pdo->prepare("SELECT * FROM attendance WHERE id = ?");
        $stmt->execute([$attendance_id]);
        $attendance_record = $stmt->fetch();
        
        if (!$attendance_record) {
            echo json_encode(['success' => false, 'message' => 'Attendance record not found']);
            exit;
        }
        
        // Reset to original time (you might want to define what "original" means)
        // For now, we'll reset to current time
        $current_time = date('Y-m-d H:i:s');
        
        $update_stmt = $pdo->prepare("UPDATE attendance SET created_at = ? WHERE id = ?");
        $update_result = $update_stmt->execute([$current_time, $attendance_id]);
        
        if ($update_result) {
            echo json_encode(['success' => true, 'message' => 'Attendance record reset successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to reset attendance record']);
        }
    } catch (PDOException $e) {
        error_log('Error resetting attendance record: ' . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// Handle attendance time update
if (isset($_POST['action']) && $_POST['action'] === 'update_attendance_time' && isset($_POST['attendance_id'])) {
    // Prevent teachers from updating attendance times
    if ($_SESSION['user_role'] === 'teacher') {
        echo json_encode(['success' => false, 'message' => 'Teachers cannot update attendance times']);
        exit;
    }
    
    $attendance_id = (int)$_POST['attendance_id'];
    $field = $_POST['field'];
    $new_time = $_POST['new_time'];
    
    // Validate inputs
    if (!in_array($field, ['in_time', 'out_time']) || empty($new_time)) {
        echo json_encode(['success' => false, 'message' => 'Invalid field or time']);
        exit;
    }
    
    try {
        // Get the existing attendance record
        $stmt = $pdo->prepare("SELECT * FROM attendance WHERE id = ?");
        $stmt->execute([$attendance_id]);
        $attendance_record = $stmt->fetch();
        
        if (!$attendance_record) {
            echo json_encode(['success' => false, 'message' => 'Attendance record not found']);
            exit;
        }
        
        // Update the attendance record
        $current_date = $attendance_record['date'];
        $new_datetime = $current_date . ' ' . $new_time . ':00';
        
        $update_stmt = $pdo->prepare("UPDATE attendance SET created_at = ? WHERE id = ?");
        $update_result = $update_stmt->execute([$new_datetime, $attendance_id]);
        
        if ($update_result) {
            echo json_encode(['success' => true, 'message' => 'Attendance time updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update attendance time']);
        }
    } catch (PDOException $e) {
        error_log('Error updating attendance time: ' . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    exit;
}

// Handle photo upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['teacher_id']) && isset($_POST['photo_data'])) {
    $teacher_id = (int)$_POST['teacher_id'];
    $photo_data = $_POST['photo_data'];
    
    // Decode base64 image data
    $photo_data = str_replace('data:image/jpeg;base64,', '', $photo_data);
    $photo_data = str_replace(' ', '+', $photo_data);
    $binary_data = base64_decode($photo_data);
    
    if ($binary_data !== false) {
        // Create filename
        $filename = 'uploads/teachers/' . $teacher_id . '_' . time() . '.jpg';
        $full_path = __DIR__ . '/../' . $filename;
        
        // Ensure directory exists
        $dir = dirname($full_path);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        
        // Save image
        if (file_put_contents($full_path, $binary_data)) {
            // Update teacher record with photo path
            $stmt = $pdo->prepare("UPDATE teachers SET photo = ? WHERE id = ?");
            $stmt->execute([$filename, $teacher_id]);
            
            $message = 'ছবি সফলভাবে রেজিস্টার করা হয়েছে!';
            $message_type = 'success';
        } else {
            $message = 'ছবি সংরক্ষণে সমস্যা হয়েছে।';
            $message_type = 'error';
        }
    } else {
        $message = 'ছবি ডিকোড করতে সমস্যা হয়েছে।';
        $message_type = 'error';
    }
}

// Get all teachers for selection
$stmt = $pdo->query("SELECT id, employee_id, first_name, last_name FROM teachers WHERE status = 'active' ORDER BY first_name, last_name");
$teachers = $stmt->fetchAll();

// Get teachers with registered photos
$stmt = $pdo->query("SELECT t.id, t.employee_id, t.first_name, t.last_name, t.photo FROM teachers t WHERE t.status = 'active' AND t.photo IS NOT NULL AND t.photo != '' ORDER BY t.first_name, t.last_name");
$registered_teachers = $stmt->fetchAll();

// Get user info for sidebar
$user_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'User';
if (isset($_SESSION['user_id'])) {
    if ($_SESSION['user_role'] == 'teacher') {
        $stmt = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) as name FROM teachers WHERE user_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $result = $stmt->fetch();
        if ($result) {
            $user_name = $result['name'];
        }
    }
}

$current_page = basename($_SERVER['PHP_SELF']);
$sidebar_html = renderSidebar($current_page, $_SESSION['user_role'], $user_name);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষক ফটো রেজিস্ট্রেশন - <?php echo htmlspecialchars($system_name); ?></title>
    <script>
        // Global error handling for debugging
        window.onerror = function(message, source, lineno, colno, error) {
            console.error('=== GLOBAL ERROR ===');
            console.error('Message:', message);
            console.error('Source:', source);
            console.error('Line:', lineno);
            console.error('Column:', colno);
            console.error('Error object:', error);
            console.error('==================');
            return false;
        };
        
        window.addEventListener('unhandledrejection', function(event) {
            console.error('=== UNHANDLED PROMISE REJECTION ===');
            console.error('Reason:', event.reason);
            console.error('=====================================');
            event.preventDefault();
        });
        
        // System health check
        console.log('=== SYSTEM HEALTH CHECK ===');
        console.log('User Agent:', navigator.userAgent);
        console.log('Secure Context:', window.isSecureContext);
        console.log('Media Devices Support:', !!navigator.mediaDevices);
        console.log('getUserMedia Support:', !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia));
        console.log('==========================');
    </script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .registered-teachers-table img {
            transition: transform 0.2s ease-in-out;
        }
        
        .registered-teachers-table img:hover {
            transform: scale(1.1);
        }
        
        .camera-container {
            width: 100%;
            max-width: 640px;
            margin: 0 auto;
            border: 2px solid #dee2e6;
            border-radius: 0.375rem;
            overflow: hidden;
        }
        
        .camera-feed {
            width: 100%;
            height: 480px;
            background-color: #000;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2em;
        }
        
        .photo-preview {
            max-width: 100%;
            max-height: 300px;
            border-radius: 0.375rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        
        .preview-container {
            width: 100%;
            max-width: 200px;
            height: 200px;
            border: 2px dashed #dee2e6;
            border-radius: 0.375rem;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
            background-color: #f8f9fa;
        }
        
        .selected-teacher {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 0.375rem;
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="sidebar-container">
        <?php echo $sidebar_html; ?>
        
        <div class="main-content">
            <!-- Diagnostic Panel -->
            <div class="alert alert-warning alert-dismissible fade show mb-3" id="diagnosticPanel" style="display: none;">
                <h5><i class="fas fa-exclamation-triangle"></i> Auto Attendance Diagnostic</h5>
                <div id="diagnosticContent"></div>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            
            <!-- Troubleshooting Alert -->
            <div class="alert alert-info alert-dismissible fade show mb-3" id="troubleshootingAlert" style="display: none;">
                <h5><i class="fas fa-tools"></i> Camera Troubleshooting</h5>
                <div id="troubleshootingContent"></div>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-camera me-2"></i>
                    শিক্ষক ফটো রেজিস্ট্রেশন ও অটো উপস্থিতি
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / শিক্ষক ফটো রেজিস্ট্রেশন ও অটো উপস্থিতি
                    <span class="ms-3 text-muted">
                        <i class="fas fa-clock me-1"></i>
                        <?php echo date('d F Y, l'); ?>
                    </span>
                </p>
            </div>
            
            <!-- Floating Sidebar Toggle Button -->
            <button class="sidebar-toggle-float" onclick="toggleSidebar()" title="সাইডবার টগল করুন">
                <i class="fas fa-bars"></i>
            </button>
            
            <!-- Content Body -->
            <div class="content-body">
                <div class="container-fluid mt-4">
                <!-- Localhost Requirement Alert -->
                <div class="alert alert-info alert-dismissible fade show" id="localhostAlert" style="display: none;">
                    <h5><i class="fas fa-info-circle"></i> ক্যামেরা ব্যবহারের নিরাপত্তা সতর্কতা</h5>
                    <p>ক্যামেরা ব্যবহার করতে হলে আপনাকে <strong>localhost</strong> বা <strong>HTTPS</strong> এ থাকতে হবে। নিরাপত্তার কারণে সাধারণ HTTP সাইটে ক্যামেরা ব্যবহার করা যায় না।</p>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                    <?php if (isset($message)): ?>
                        <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                            <?php echo htmlspecialchars($message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <!-- Registered Teachers List -->
                            <div class="card mb-4">
                                <div class="card-header bg-success text-white">
                                    <h5 class="mb-0"><i class="fas fa-images"></i> রেজিস্টারকৃত শিক্ষকদের তালিকা</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped registered-teachers-table">
                                            <thead>
                                                <tr>
                                                    <th>ছবি</th>
                                                    <th>কর্মচারী আইডি</th>
                                                    <th>নাম</th>
                                                    <th>রেজিস্টারেশন স্ট্যাটাস</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (count($registered_teachers) > 0): ?>
                                                    <?php foreach ($registered_teachers as $teacher): ?>
                                                        <tr>
                                                            <td>
                                                                <?php if ($teacher['photo'] && file_exists(__DIR__ . '/../' . $teacher['photo'])): ?>
                                                                    <img src="../<?php echo $teacher['photo']; ?>"
                                                                         alt="<?php echo $teacher['first_name']; ?>"
                                                                         class="rounded-circle" 
                                                                         style="width: 50px; height: 50px; object-fit: cover; border: 2px solid #28a745;">
                                                                <?php else: ?>
                                                                    <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center"
                                                                         style="width: 50px; height: 50px;">
                                                                        <i class="fas fa-user text-white"></i>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-info"><?php echo $teacher['employee_id']; ?></span>
                                                            </td>
                                                            <td>
                                                                <strong><?php echo $teacher['first_name'] . ' ' . $teacher['last_name']; ?></strong>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-success"><i class="fas fa-check"></i> রেজিস্টারকৃত</span>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center text-muted">
                                                            <i class="fas fa-info-circle"></i> এখনও কোনও শিক্ষকের ছবি রেজিস্টার করা হয়নি
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-3">
                                        <small class="text-muted">
                                            <i class="fas fa-info-circle"></i> মোট রেজিস্টারকৃত শিক্ষক: <strong><?php echo count($registered_teachers); ?></strong> জন
                                        </small>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Main Registration Card -->
                            <div class="card">
                                <div class="card-header bg-primary text-white">
                                    <h5 class="mb-0"><i class="fas fa-camera"></i> নতুন শিক্ষক ফটো রেজিস্ট্রেশন ও অটো উপস্থিতি</h5>
                                </div>
                                <div class="card-body">
                                    <!-- Mode Selection -->
                                    <div class="row mb-4">
                                        <div class="col-md-12">
                                            <div class="card mb-4">
                                                <div class="card-body">
                                                    <h6 class="card-title"><i class="fas fa-sliders-h"></i> মোড নির্বাচন করুন:</h6>
                                                    <div class="btn-group w-100" role="group">
                                                        <input type="radio" class="btn-check" name="mode" id="photo_mode" autocomplete="off" checked>
                                                        <label class="btn btn-outline-primary" for="photo_mode">
                                                            <i class="fas fa-camera"></i> ফটো রেজিস্ট্রেশন
                                                        </label>
                                                        
                                                        <input type="radio" class="btn-check" name="mode" id="attendance_mode" autocomplete="off">
                                                        <label class="btn btn-outline-success" for="attendance_mode">
                                                            <i class="fas fa-user-check"></i> অটো উপস্থিতি
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Teacher Selection -->
                                    <div class="row mb-4">
                                        <div class="col-md-12">
                                            <label for="teacher_select" class="form-label">শিক্ষক নির্বাচন করুন:</label>
                                            <select class="form-select" id="teacher_select" onchange="selectTeacher()">
                                                <option value="">-- শিক্ষক নির্বাচন করুন --</option>
                                                <?php foreach ($teachers as $teacher): ?>
                                                    <option value="<?php echo $teacher['id']; ?>" 
                                                        data-first-name="<?php echo htmlspecialchars($teacher['first_name']); ?>"
                                                        data-last-name="<?php echo htmlspecialchars($teacher['last_name']); ?>"
                                                        data-employee-id="<?php echo htmlspecialchars($teacher['employee_id']); ?>">
                                                        <?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name'] . ' (' . $teacher['employee_id'] . ')'); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <!-- Selected Teacher Info -->
                                    <div id="selected_teacher_info" class="selected-teacher" style="display: none;">
                                        <h6><i class="fas fa-user-check"></i> নির্বাচিত শিক্ষক:</h6>
                                        <p class="mb-0">
                                            <strong>নাম:</strong> <span id="selected_teacher_name"></span><br>
                                            <strong>কর্মচারী আইডি:</strong> <span id="selected_employee_id"></span>
                                        </p>
                                    </div>
                                    
                                    <!-- Camera Section (Dynamic based on mode) -->
                                    <div id="camera_section" style="display: none;">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <h6 id="camera_title">ক্যামেরা ফিড:</h6>
                                                <div class="camera-container">
                                                    <div class="camera-feed">
                                                        <video id="camera_feed" autoplay playsinline style="display: none; width: 100%; height: 100%; object-fit: cover;"></video>
                                                        <canvas id="camera_canvas" style="display: none;"></canvas>
                                                        <div id="camera_placeholder" style="width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center;">
                                                            <i class="fas fa-camera fa-3x mb-2"></i>
                                                            <p>ক্যামেরা ফিড এখানে প্রদর্শিত হবে</p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="text-center mt-2">
                                                    <button type="button" id="start_camera_btn" class="btn btn-primary me-2" onclick="startCamera()">
                                                        <i class="fas fa-camera"></i> ক্যামেরা চালু করুন
                                                    </button>
                                                    <button type="button" id="capture_photo_btn" class="btn btn-success" onclick="capturePhoto()" disabled>
                                                        <i class="fas fa-camera-retro"></i> ছবি তুলুন
                                                    </button>
                                                    <button type="button" class="btn btn-info ms-2" onclick="testAttendanceNow()">
                                                        <i class="fas fa-bolt"></i> এখনই উপস্থিতি নিন
                                                    </button>

                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <h6 id="preview_title">ছবি প্রিভিউ:</h6>
                                                <div class="preview-container" id="preview_placeholder">
                                                    <i class="fas fa-image fa-3x mb-2"></i>
                                                    <p>ছবি প্রিভিউ এখানে দেখানো হবে</p>
                                                </div>
                                                <img id="photo_preview" class="photo-preview" style="display: none;" alt="Photo Preview">
                                                
                                                <div class="mt-3">
                                                    <form id="photo_registration_form" method="POST" style="display: none;">
                                                        <input type="hidden" id="selected_teacher_id" name="teacher_id" value="">
                                                        <input type="hidden" id="photo_data_input" name="photo_data" value="">
                                                        
                                                        <button type="button" id="register_photo_btn" class="btn btn-success" onclick="registerPhoto()" disabled>
                                                            <i class="fas fa-save"></i> ছবি রেজিস্টার করুন
                                                        </button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Attendance Records Table -->
                                    <div class="row mt-4">
                                        <div class="col-md-12">
                                            <div class="card">
                                                <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                                                    <h5 class="mb-0"><i class="fas fa-table"></i> উপস্থিতির তালিকা</h5>
                                                    <button class="btn btn-warning btn-sm" onclick="resetTodayAttendance()" title="আজকের উপস্থিতি রিসেট করুন">
                                                        <i class="fas fa-sync-alt"></i> রিসেট
                                                    </button>
                                                </div>
                                                <div class="card-body">
                                                    <div class="table-responsive">
                                                        <table class="table table-striped" id="attendance_records_table">
                                                            <thead>
                                                                <tr>
                                                                    <th>ক্রমিক নং</th>
                                                                    <th>শিক্ষকের নাম</th>
                                                                    <th>তারিখ</th>
                                                                    <th>ইন-টাইম</th>
                                                                    <th>আউট-টাইম</th>
                                                                    <th>অবস্থান</th>
                                                                    <th>মন্তব্য</th>
                                                                    <th>এডিট</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <?php
                                                                // Check if this is an AJAX request for table update
                                                                if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' || isset($_GET['ajax'])) {
                                                                    // Return only the table content for AJAX requests
                                                                    $is_ajax_request = true;
                                                                } else {
                                                                    $is_ajax_request = false;
                                                                }
                                                                                                        
                                                                // Fetch attendance records for the current date - camera only
                                                                $today = date('Y-m-d');
                                                                $stmt = $pdo->prepare("SELECT a.id, a.student_id, a.teacher_id, a.class_id, a.date, a.status, a.remarks, a.created_at, a.updated_at, a.marked_by, t.first_name, t.last_name, u.username as marked_by_name 
                                                                                     FROM attendance a 
                                                                                     LEFT JOIN teachers t ON a.teacher_id = t.id 
                                                                                     LEFT JOIN users u ON a.marked_by = u.id 
                                                                                     WHERE a.date = ? AND a.teacher_id IS NOT NULL 
                                                                                     AND (a.remarks LIKE '%ক্যামেরা%' OR a.remarks LIKE '%স্ক্যান%' OR a.remarks LIKE '%Camera%')
                                                                                     ORDER BY a.teacher_id, a.created_at ASC");
                                                                $stmt->execute([$today]);
                                                                $attendance_records = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                                                                                        
                                                                // Debug: Log raw attendance records to see what we're getting
                                                                error_log('Raw attendance records: ' . print_r($attendance_records, true));
                                                                                                        
                                                                // Group records by teacher
                                                                $grouped_records = [];
                                                                foreach ($attendance_records as $record) {
                                                                    error_log('Processing record: ' . print_r($record, true)); // Debug log
                                                                    $teacher_id = $record['teacher_id'];
                                                                    if (!isset($grouped_records[$teacher_id])) {
                                                                        $grouped_records[$teacher_id] = [
                                                                            'teacher_name' => $record['first_name'] . ' ' . $record['last_name'],
                                                                            'date' => !empty($record['date']) ? date('d/m/Y', strtotime($record['date'])) : date('d/m/Y'),
                                                                            'location' => 'শিক্ষক রেজিস্ট্রেশন ক্যামেরা',
                                                                            'in_time' => null,
                                                                            'out_time' => null,
                                                                            'first_scan_time' => null, // Track the very first scan time
                                                                            'all_scans' => [], // Store all scans to determine in/out times
                                                                            'in_remarks' => null,
                                                                            'out_remarks' => null
                                                                        ];
                                                                    }
                                                                                                            
                                                                    $time_str = $record['created_at']; // Use full datetime for comparison
                                                                    // Extract time properly from the datetime field
                                                                    $time_display = !empty($record['created_at']) ? date('h:i A', strtotime($record['created_at'])) : date('h:i A');
                                                                    $remarks = $record['remarks'] ?: 'স্বযংক্রিয় চিহ্নিত';
                                                                                                            
                                                                    error_log('Time extracted: ' . $time_str . ' -> ' . $time_display); // Debug log
                                                                                                            
                                                                    // Add scan to all scans array
                                                                    $grouped_records[$teacher_id]['all_scans'][] = [
                                                                        'id' => $record['id'], // Include the attendance ID
                                                                        'time_str' => $time_str,
                                                                        'time_display' => $time_display,
                                                                        'status' => $record['status'],
                                                                        'remarks' => $remarks,
                                                                        'created_at' => $record['created_at'] // Preserve original timestamp
                                                                    ];
                                                                }
                                                                                                        
                                                                // Process all scans for each teacher to determine in/out times
                                                                foreach ($grouped_records as &$group) {
                                                                    if (!empty($group['all_scans'])) {
                                                                        // Sort scans by time to find the first scan
                                                                        usort($group['all_scans'], function($a, $b) {
                                                                            return strtotime($a['time_str']) - strtotime($b['time_str']);
                                                                        });
                                                                                                                
                                                                        // First scan is always IN time
                                                                        $first_scan = $group['all_scans'][0];
                                                                        $group['in_time'] = $first_scan['time_display'];
                                                                        $group['in_remarks'] = $first_scan['remarks'];
                                                                                                                
                                                                        // Find ALL scans and determine IN and OUT times
                                                                        $first_scan_time = strtotime($first_scan['time_str']);
                                                                        $earliest_out_scan = null;
                                                                        $latest_scan = null;
                                                                                                                                                
                                                                        foreach ($group['all_scans'] as $scan) {
                                                                            $current_scan_time = strtotime($scan['time_str']);
                                                                            $time_diff_minutes = ($current_scan_time - $first_scan_time) / 60;
                                                                                                                                                    
                                                                            // Update latest scan to find the last scan of the day
                                                                            if (!$latest_scan || $current_scan_time > strtotime($latest_scan['time_str'])) {
                                                                                $latest_scan = $scan;
                                                                            }
                                                                                                                                                    
                                                                            // If this scan is more than 30 minutes after first scan, consider it as potential OUT time
                                                                            if ($time_diff_minutes > 30) {
                                                                                if (!$earliest_out_scan || strtotime($scan['time_str']) < strtotime($earliest_out_scan['time_str'])) {
                                                                                    $earliest_out_scan = $scan; // Earliest scan after 30 minutes becomes OUT time
                                                                                }
                                                                            }
                                                                        }
                                                                                                                                                
                                                                        // If no out-time found based on 30 minute rule, use the last scan as out-time (if different from first)
                                                                        if (!$earliest_out_scan && $latest_scan && $latest_scan !== $first_scan) {
                                                                            $earliest_out_scan = $latest_scan;
                                                                        }
                                                                                                                                                
                                                                        // Debug: Output the times to understand the issue
                                                                        error_log('First scan time: ' . $first_scan['time_str'] . ', Time display: ' . $first_scan['time_display']);
                                                                        if ($earliest_out_scan) {
                                                                            error_log('Earliest out scan time: ' . $earliest_out_scan['time_str'] . ', Time display: ' . $earliest_out_scan['time_display']);
                                                                        }
                                                                                                                                                
                                                                        // Set OUT time if found (using earliest out-time)
                                                                        if ($earliest_out_scan) {
                                                                            $group['out_time'] = $earliest_out_scan['time_display'];
                                                                            $group['out_remarks'] = $earliest_out_scan['remarks'];
                                                                        }
                                                                    }
                                                                }
                                                                                                        
                                                                // Debug: Log the final grouped records to ensure data is correct
                                                                error_log('Final grouped records: ' . print_r($grouped_records, true));
                                                                                                        
                                                                if (count($grouped_records) > 0):
                                                                    $index = 0;
                                                                    foreach ($grouped_records as $group):
                                                                        $in_time = $group['in_time'] ? $group['in_time'] : '-';
                                                                        $out_time = $group['out_time'] ? $group['out_time'] : '-';
                                                                        $remarks = $group['in_remarks'] ? $group['in_remarks'] : ($group['out_remarks'] ? $group['out_remarks'] : 'কোন মন্তব্য নেই');
                                                                ?>
                                                                <tr>
                                                                    <td><?php echo ++$index; ?></td>
                                                                    <td><?php echo htmlspecialchars($group['teacher_name']); ?></td>
                                                                    <td><?php echo htmlspecialchars($group['date']); ?></td>
                                                                    <td>
                                                                        <span class="time-display" data-field="in_time" data-attendance-id="<?php echo $group['all_scans'][0]['id'] ?? ''; ?>" onclick="editTime(this, 'in_time')">
                                                                            <?php echo htmlspecialchars($in_time); ?>
                                                                        </span>
                                                                        <input type="time" class="time-input" style="display:none;" value="<?php echo date('H:i', strtotime($group['all_scans'][0]['created_at'] ?? date('Y-m-d H:i:s'))); ?>" onchange="updateTime(this, 'in_time')">
                                                                    </td>
                                                                    <td>
                                                                        <span class="time-display" data-field="out_time" data-attendance-id="<?php echo ($earliest_out_scan ?? null) ? $earliest_out_scan['id'] : ($group['all_scans'][0]['id'] ?? ''); ?>" onclick="editTime(this, 'out_time')">
                                                                            <?php echo htmlspecialchars($out_time); ?>
                                                                        </span>
                                                                        <input type="time" class="time-input" style="display:none;" value="<?php echo ($earliest_out_scan ?? null) ? date('H:i', strtotime($earliest_out_scan['created_at'])) : ''; ?>" onchange="updateTime(this, 'out_time')">
                                                                    </td>
                                                                    <td><?php echo htmlspecialchars($group['location']); ?></td>
                                                                    <td><?php echo htmlspecialchars($remarks); ?></td>
                                                                    <td>
                                                                        <?php if ($_SESSION['user_role'] !== 'teacher'): ?>
                                                                        <button class="btn btn-sm btn-outline-primary" onclick="editRecord(<?php echo $group['all_scans'][0]['id'] ?? 0; ?>)" title="Edit" <?php echo ($group['all_scans'][0]['id'] ?? 0) == 0 ? 'disabled' : ''; ?>>
                                                                            <i class="fas fa-edit"></i>
                                                                        </button>
                                                                        <button class="btn btn-sm btn-outline-secondary" onclick="resetRecord(<?php echo $group['all_scans'][0]['id'] ?? 0; ?>)" title="Reset" <?php echo ($group['all_scans'][0]['id'] ?? 0) == 0 ? 'disabled' : ''; ?>>
                                                                            <i class="fas fa-redo"></i>
                                                                        </button>
                                                                        <?php endif; ?>
                                                                    </td>
                                                                </tr>
                                                                <?php 
                                                                    endforeach;
                                                                else:
                                                                ?>
                                                                <tr>
                                                                    <td colspan="7" class="text-center text-muted">আজকের উপস্থিতি রেকর্ড পাওয়া যায়নি</td>
                                                                </tr>
                                                                <?php endif; ?>
                                                            </tbody>
                                                                                                    
                                                            <?php
                                                            // If this is an AJAX request, terminate here with just the table content
                                                            if ($is_ajax_request) {
                                                                exit();
                                                            }
                                                            ?>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Edit Attendance Modal -->
    <div class="modal fade" id="editAttendanceModal" tabindex="-1" aria-labelledby="editAttendanceModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editAttendanceModalLabel">উপস্থিতি এডিট করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editAttendanceForm">
                        <input type="hidden" id="edit_attendance_id" name="attendance_id">
                        
                        <div class="mb-3">
                            <label for="edit_teacher_name" class="form-label">শিক্ষকের নাম</label>
                            <input type="text" class="form-control" id="edit_teacher_name" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_date" class="form-label">তারিখ</label>
                            <input type="date" class="form-control" id="edit_date" name="date" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_status" class="form-label">অবস্থা</label>
                            <select class="form-select" id="edit_status" name="status" required>
                                <option value="present">উপস্থিত</option>
                                <option value="absent">অনুপস্থিত</option>
                                <option value="late">বিলম্বে আগমন</option>
                                <option value="excused">অনুমোদিত অনুপস্থিতি</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_in_time" class="form-label">ইন-টাইম (YYYY-MM-DD HH:MM:SS)</label>
                            <input type="datetime-local" class="form-control" id="edit_in_time" name="in_time" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit_out_time" class="form-label">আউট-টাইম (YYYY-MM-DD HH:MM:SS)</label>
                            <input type="datetime-local" class="form-control" id="edit_out_time" name="out_time">
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit_remarks" class="form-label">মন্তব্য</label>
                            <textarea class="form-control" id="edit_remarks" name="remarks" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                    <button type="button" class="btn btn-primary" onclick="saveAttendanceChanges()">পরিবর্তন সংরক্ষণ করুন</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@vladmandic/face-api@0.22.2/dist/face-api.min.js"></script>
    <script src="../assets/js/script.js"></script>
    <script>
        let videoStream = null;
        let selectedTeacher = null;
        let currentMode = 'photo'; // 'photo' or 'attendance'
        let isAutoAttendanceActive = false;
        let recognitionInterval = null;
        let presentCount = 0;
        
        // Get teachers data for auto attendance
        const teachersData = <?php 
            $teachersArray = [];
            foreach ($teachers as $teacher) {
                $teachersArray[] = [
                    'id' => (int)$teacher['id'],
                    'firstName' => $teacher['first_name'],
                    'lastName' => $teacher['last_name'],
                    'employeeId' => $teacher['employee_id']
                ];
            }
            echo json_encode($teachersArray);
        ?>;
        
        // Debug teachers data
        console.log('Teachers data loaded:', teachersData);
        console.log('Number of teachers:', teachersData ? teachersData.length : 0);
        
        // Validate teachers data
        if (!teachersData || teachersData.length === 0) {
            console.error('No teachers data available!');
        } else {
            console.log('First teacher data:', teachersData[0]);
        }
        
        // Mode switching
        function switchMode(mode) {
            console.log('switchMode called with:', mode);
            console.log('Current mode before switch:', currentMode);
            
            currentMode = mode;
            console.log('Current mode after switch:', currentMode);
            
            // Update UI based on mode
            if (mode === 'photo') {
                console.log('Switching to photo mode');
                
                const cameraTitle = document.getElementById('camera_title');
                const previewTitle = document.getElementById('preview_title');
                const startBtn = document.getElementById('start_camera_btn');
                const captureBtn = document.getElementById('capture_photo_btn');
                
                if (cameraTitle) cameraTitle.innerHTML = '<i class="fas fa-camera"></i> ক্যামেরা ফিড:';
                if (previewTitle) previewTitle.innerHTML = '<i class="fas fa-image"></i> ছবি প্রিভিউ:';
                if (startBtn) startBtn.innerHTML = '<i class="fas fa-camera"></i> ক্যামেরা চালু করুন';
                if (captureBtn) {
                    captureBtn.innerHTML = '<i class="fas fa-camera-retro"></i> ছবি তুলুন';
                    captureBtn.style.display = 'inline-block';
                }
                
                // Stop auto attendance if running
                if (isAutoAttendanceActive) {
                    console.log('Stopping auto attendance');
                    stopAutoAttendance();
                }
            } else {
                console.log('Switching to attendance mode');
                
                const cameraTitle = document.getElementById('camera_title');
                const previewTitle = document.getElementById('preview_title');
                const startBtn = document.getElementById('start_camera_btn');
                const captureBtn = document.getElementById('capture_photo_btn');
                const previewPlaceholder = document.getElementById('preview_placeholder');
                
                if (cameraTitle) cameraTitle.innerHTML = '<i class="fas fa-video"></i> অটো উপস্থিতি ক্যামেরা:';
                if (previewTitle) previewTitle.innerHTML = '<i class="fas fa-users"></i> উপস্থিতি সারসংক্ষেপ:';
                if (startBtn) {
                    startBtn.innerHTML = '<i class="fas fa-play"></i> অটো উপস্থিতি শুরু করুন';
                    startBtn.className = 'btn btn-success me-2';
                }
                if (captureBtn) captureBtn.style.display = 'none';
                
                // Update preview section for attendance mode
                if (previewPlaceholder) {
                    previewPlaceholder.innerHTML = '';
                    previewPlaceholder.innerHTML = `
                        <div class="text-center">
                            <h5><i class="fas fa-chart-bar"></i> উপস্থিতি সারসংক্ষেপ</h5>
                            <div class="mt-3">
                                <div class="mb-2">
                                    <span class="badge bg-success fs-5" id="present_count_badge">0</span>
                                    <span class="ms-2">উপস্থিত শিক্ষক</span>
                                </div>
                                <div>
                                    <span class="badge bg-secondary fs-5" id="total_count_badge"><?php echo count($teachers); ?></span>
                                    <span class="ms-2">মোট শিক্ষক</span>
                                </div>
                            </div>
                            <div class="mt-3" id="recognized_teachers_list">
                                <small class="text-muted">কোনও শিক্ষক স্বীকৃতি দেওয়া হয়নি</small>
                            </div>
                            <div class="mt-3">
                                <button class="btn btn-sm btn-outline-primary" onclick="manualFaceRecognition()">
                                    <i class="fas fa-eye"></i> ম্যানুয়াল ফেস রিকগনিশন
                                </button>
                            </div>
                        </div>
                    `;
                    console.log('Preview section updated for attendance mode');
                }
            }
        }
        
        // Select teacher from dropdown
        function selectTeacher() {
            const selectElement = document.getElementById('teacher_select');
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            
            if (selectedOption.value) {
                selectedTeacher = {
                    id: selectedOption.value,
                    firstName: selectedOption.getAttribute('data-first-name'),
                    lastName: selectedOption.getAttribute('data-last-name'),
                    employeeId: selectedOption.getAttribute('data-employee-id')
                };
                
                // Display selected teacher info
                document.getElementById('selected_teacher_name').textContent = 
                    selectedTeacher.firstName + ' ' + selectedTeacher.lastName;
                document.getElementById('selected_employee_id').textContent = selectedTeacher.employeeId;
                document.getElementById('selected_teacher_info').style.display = 'block';
                
                // Show camera section
                document.getElementById('camera_section').style.display = 'block';
                
                // Reset camera if it was already started
                if (videoStream) {
                    stopCamera();
                }
                
                // Reset photo preview and form
                document.getElementById('photo_preview').style.display = 'none';
                document.getElementById('preview_placeholder').style.display = 'flex';
                document.getElementById('register_photo_btn').disabled = true;
                document.getElementById('photo_registration_form').style.display = 'none';
            } else {
                document.getElementById('selected_teacher_info').style.display = 'none';
                document.getElementById('camera_section').style.display = 'none';
                selectedTeacher = null;
            }
        }
        
        // Start camera based on current mode
        async function startCamera() {
            console.log('startCamera called');
            console.log('Current mode:', currentMode);
            console.log('isAutoAttendanceActive:', isAutoAttendanceActive);
            
            if (currentMode === 'attendance') {
                console.log('Calling startAutoAttendance for attendance mode');
                await startAutoAttendance();
                return;
            }
            
            console.log('Starting camera in photo mode');
            
            // Check if we're on localhost or HTTPS
            const isSecureContext = window.isSecureContext;
            const isLocalhost = location.hostname === 'localhost' || location.hostname === '127.0.0.1' || location.hostname === '[::1]';
            
            if (!isSecureContext && !isLocalhost) {
                alert('ক্যামেরা ব্যবহারের জন্য আপনাকে HTTPS অথবা localhost এ থাকতে হবে। নিরাপত্তার কারণে সাধারণ HTTP এ ক্যামেরা চালানো যায় না।');
                return;
            }
            
            // Original photo mode camera start with fallbacks
            try {
                // Stop any existing stream
                if (videoStream) {
                    console.log('Stopping existing camera stream');
                    stopCamera();
                }
                
                console.log('Requesting camera access for photo mode');
                
                // Define multiple fallback constraints for photo mode with improved settings
                const constraintOptions = [
                    { 
                        video: { 
                            facingMode: 'user', 
                            width: { ideal: 640, max: 1280 }, 
                            height: { ideal: 480, max: 720 }, 
                            frameRate: { ideal: 15, max: 30 },
                            resizeMode: 'crop-and-scale'
                        } 
                    },
                    { 
                        video: { 
                            facingMode: 'user', 
                            width: { max: 640 }, 
                            height: { max: 480 }, 
                            frameRate: { max: 15 }
                        } 
                    },
                    { video: { facingMode: 'user' } },
                    { video: true }
                ];
                
                let stream = null;
                let usedConstraints = null;
                
                // Try each constraint option in sequence
                for (let i = 0; i < constraintOptions.length; i++) {
                    try {
                        console.log(`Trying constraint option ${i + 1} for photo mode:`, constraintOptions[i]);
                        stream = await navigator.mediaDevices.getUserMedia(constraintOptions[i]);
                        usedConstraints = constraintOptions[i];
                        console.log(`Successfully got stream with constraint option ${i + 1} for photo mode`);
                        break; // Success, exit the loop
                    } catch (constraintError) {
                        console.warn(`Constraint option ${i + 1} failed for photo mode:`, constraintError.message);
                        if (i === constraintOptions.length - 1) {
                            // Last option, re-throw the error
                            throw constraintError;
                        }
                        // Otherwise, continue to next constraint option
                    }
                }
                
                if (!stream) {
                    throw new Error('Could not access camera with any constraint option for photo mode');
                }
                
                console.log('Camera stream obtained for photo mode:', stream);
                console.log('Used constraints:', usedConstraints);
                
                videoStream = stream;
                
                // Display video feed
                const videoElement = document.getElementById('camera_feed');
                if (videoElement) {
                    videoElement.srcObject = stream;
                    videoElement.style.display = 'block';
                    videoElement.play().catch(e => console.log('Video play error:', e));
                    console.log('Video feed displayed for photo mode');
                }
                
                // Hide placeholder
                const placeholder = document.getElementById('camera_placeholder');
                if (placeholder) {
                    placeholder.style.display = 'none';
                }
                
                // Enable capture button
                const captureBtn = document.getElementById('capture_photo_btn');
                if (captureBtn) {
                    captureBtn.disabled = false;
                }
                
                console.log('Camera started successfully in photo mode');
            } catch (err) {
                console.error('Error accessing camera in photo mode:', err);
                console.error('Error name:', err.name);
                console.error('Error message:', err.message);
                
                let errorMessage = 'ক্যামেরা ব্যবহার করতে অসুবিধা হচ্ছে: ';
                
                switch(err.name) {
                    case 'NotAllowedError':
                        errorMessage += 'ব্রাউজারে ক্যামেরা ব্যবহারের অনুমতি দিন। ঠিকানা বারে 🔒 আইকনে ক্লিক করে অনুমতি দিন।';
                        break;
                    case 'NotFoundError':
                        errorMessage += 'ক্যামেরা পাওয়া যায়নি। ক্যামেরা সংযুক্ত আছে কিনা পরীক্ষা করুন।';
                        break;
                    case 'NotReadableError':
                        errorMessage += 'ক্যামেরা ব্যবহার করা যাচ্ছে না। অন্য কোনো প্রোগ্রাম ক্যামেরা ব্যবহার করছে কিনা দেখুন।';
                        break;
                    case 'OverconstrainedError':
                        errorMessage += 'ক্যামেরা কনফিগারেশন সমস্যা। কমপ্যাটিবিল ক্যামেরা সেটিংস ব্যবহার করুন।';
                        break;
                    case 'SecurityError':
                        errorMessage += 'HTTPS এবং localhost ছাড়া ক্যামেরা ব্যবহার করা যাবে না। নিরাপত্তার কারণে।';
                        break;
                    default:
                        errorMessage += err.message;
                }
                
                alert(errorMessage);
            }
        }
        
        // Start auto attendance system
        async function startAutoAttendance() {
            console.log('startAutoAttendance called');
            console.log('teachersData available:', teachersData);
            console.log('teachersData length:', teachersData ? teachersData.length : 'undefined');
            
            // Check if we're on localhost or HTTPS
            const isSecureContext = window.isSecureContext;
            const isLocalhost = location.hostname === 'localhost' || location.hostname === '127.0.0.1' || location.hostname === '[::1]';
            
            if (!isSecureContext && !isLocalhost) {
                alert('ক্যামেরা ব্যবহারের জন্য আপনাকে HTTPS অথবা localhost এ থাকতে হবে। নিরাপত্তার কারণে সাধারণ HTTP এ ক্যামেরা চালানো যায় না।');
                return;
            }
            
            try {
                // Check if mediaDevices is supported
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    console.error('Camera access not supported');
                    throw new Error('Camera access is not supported in this browser.');
                }
                
                console.log('Requesting camera access...');
                
                // Define multiple fallback constraints for auto attendance with improved settings
                const constraintOptions = [
                    { 
                        video: { 
                            facingMode: 'user', 
                            width: { ideal: 640, max: 1280 }, 
                            height: { ideal: 480, max: 720 }, 
                            frameRate: { ideal: 15, max: 30 },
                            resizeMode: 'crop-and-scale'
                        } 
                    },
                    { 
                        video: { 
                            facingMode: 'user', 
                            width: { max: 640 }, 
                            height: { max: 480 }, 
                            frameRate: { max: 15 }
                        } 
                    },
                    { video: { facingMode: 'user' } },
                    { video: true }
                ];
                
                let stream = null;
                let usedConstraints = null;
                
                // Try each constraint option in sequence
                for (let i = 0; i < constraintOptions.length; i++) {
                    try {
                        console.log(`Trying constraint option ${i + 1} for auto attendance:`, constraintOptions[i]);
                        stream = await navigator.mediaDevices.getUserMedia(constraintOptions[i]);
                        usedConstraints = constraintOptions[i];
                        console.log(`Successfully got stream with constraint option ${i + 1} for auto attendance`);
                        break; // Success, exit the loop
                    } catch (constraintError) {
                        console.warn(`Constraint option ${i + 1} failed for auto attendance:`, constraintError.message);
                        if (i === constraintOptions.length - 1) {
                            // Last option, re-throw the error
                            throw constraintError;
                        }
                        // Otherwise, continue to next constraint option
                    }
                }
                
                if (!stream) {
                    throw new Error('Could not access camera with any constraint option for auto attendance');
                }
                
                console.log('Camera stream obtained:', stream);
                console.log('Used constraints:', usedConstraints);
                
                videoStream = stream;
                
                // Display video feed
                const videoElement = document.getElementById('camera_feed');
                if (videoElement) {
                    videoElement.srcObject = stream;
                    videoElement.style.display = 'block';
                    videoElement.play().catch(e => console.log('Video play error:', e));
                    console.log('Video feed displayed');
                } else {
                    console.error('Video element not found');
                }
                
                // Hide placeholder
                const placeholder = document.getElementById('camera_placeholder');
                if (placeholder) {
                    placeholder.style.display = 'none';
                }
                
                // Update button
                const startBtn = document.getElementById('start_camera_btn');
                if (startBtn) {
                    startBtn.innerHTML = '<i class="fas fa-stop"></i> অটো উপস্থিতি বন্ধ করুন';
                    startBtn.className = 'btn btn-danger me-2';
                }
                
                // Start auto attendance
                isAutoAttendanceActive = true;
                console.log('Setting up recognition interval...');
                recognitionInterval = setInterval(recognizeTeacher, 1500); // Check every 1.5 seconds for better real-time detection
                
                console.log('Auto attendance started successfully');
                console.log('Recognition interval ID:', recognitionInterval);
                
                // Test immediate recognition
                setTimeout(() => {
                    console.log('Testing immediate recognition...');
                    recognizeTeacher();
                }, 1000);
                
            } catch (err) {
                console.error('Error accessing camera:', err);
                console.error('Error name:', err.name);
                console.error('Error message:', err.message);
                
                let errorMessage = 'ক্যামেরা ব্যবহার করতে অসুবিধা হচ্ছে: ';
                
                switch(err.name) {
                    case 'NotAllowedError':
                        errorMessage += 'ব্রাউজারে ক্যামেরা ব্যবহারের অনুমতি দিন। ঠিকানা বারে 🔒 আইকনে ক্লিক করে অনুমতি দিন।';
                        break;
                    case 'NotFoundError':
                        errorMessage += 'ক্যামেরা পাওয়া যায়নি। ক্যামেরা সংযুক্ত আছে কিনা পরীক্ষা করুন।';
                        break;
                    case 'NotReadableError':
                        errorMessage += 'ক্যামেরা ব্যবহার করা যাচ্ছে না। অন্য কোনো প্রোগ্রাম ক্যামেরা ব্যবহার করছে কিনা দেখুন।';
                        break;
                    case 'OverconstrainedError':
                        errorMessage += 'ক্যামেরা কনফিগারেশন সমস্যা। কমপ্যাটিবিল ক্যামেরা সেটিংস ব্যবহার করুন।';
                        break;
                    case 'SecurityError':
                        errorMessage += 'HTTPS এবং localhost ছাড়া ক্যামেরা ব্যবহার করা যাবে না। নিরাপত্তার কারণে।';
                        break;
                    default:
                        errorMessage += err.message;
                }
                
                alert(errorMessage);
            }
        }
        
        // Stop camera or auto attendance
        function stopCamera() {
            console.log('stopCamera called');
            console.log('Current mode:', currentMode);
            console.log('isAutoAttendanceActive:', isAutoAttendanceActive);
            console.log('videoStream exists:', !!videoStream);
            
            // Handle auto attendance stop
            if (currentMode === 'attendance' && isAutoAttendanceActive) {
                console.log('Stopping auto attendance');
                stopAutoAttendance();
                return;
            }
            
            // Handle photo mode stop
            if (videoStream) {
                console.log('Stopping video stream');
                const tracks = videoStream.getTracks();
                tracks.forEach(track => {
                    console.log('Stopping track:', track.kind);
                    track.stop();
                });
                videoStream = null;
                
                // Hide video feed
                const cameraFeed = document.getElementById('camera_feed');
                if (cameraFeed) {
                    cameraFeed.style.display = 'none';
                    cameraFeed.srcObject = null;
                    // Pause the video element to ensure it stops
                    cameraFeed.pause();
                }
                
                // Show placeholder
                const placeholder = document.getElementById('camera_placeholder');
                if (placeholder) {
                    placeholder.style.display = 'flex';
                }
                
                // Disable capture button
                const captureBtn = document.getElementById('capture_photo_btn');
                if (captureBtn) {
                    captureBtn.disabled = true;
                }
                
                console.log('Camera stopped successfully');
            } else {
                console.log('No video stream to stop');
            }
        }
        
        // Stop auto attendance system
        function stopAutoAttendance() {
            console.log('stopAutoAttendance called');
            console.log('videoStream exists:', !!videoStream);
            console.log('recognitionInterval exists:', !!recognitionInterval);
            
            // Stop video stream
            if (videoStream) {
                console.log('Stopping auto attendance video stream');
                const tracks = videoStream.getTracks();
                tracks.forEach(track => {
                    console.log('Stopping track:', track.kind);
                    track.stop();
                });
                videoStream = null;
                
                // Hide video feed
                const cameraFeed = document.getElementById('camera_feed');
                const placeholder = document.getElementById('camera_placeholder');
                
                if (cameraFeed) {
                    cameraFeed.style.display = 'none';
                    cameraFeed.srcObject = null;
                    // Pause the video element to ensure it stops
                    cameraFeed.pause();
                }
                
                if (placeholder) {
                    placeholder.style.display = 'flex';
                }
            }
            
            // Clear recognition interval
            if (recognitionInterval) {
                console.log('Clearing recognition interval');
                clearInterval(recognitionInterval);
                recognitionInterval = null;
            }
            
            // Update button
            const startBtn = document.getElementById('start_camera_btn');
            if (startBtn) {
                startBtn.innerHTML = '<i class="fas fa-play"></i> অটো উপস্থিতি শুরু করুন';
                startBtn.className = 'btn btn-success me-2';
            }
            
            isAutoAttendanceActive = false;
            console.log('Auto attendance stopped successfully');
        }
        
        // Real face recognition for auto attendance
        async function recognizeTeacher() {
            console.log('recognizeTeacher called, isAutoAttendanceActive:', isAutoAttendanceActive);
            
            if (!isAutoAttendanceActive) {
                console.log('Auto attendance not active, skipping recognition');
                return;
            }
            
            // Check if teachersData is loaded
            console.log('teachersData length:', teachersData.length);
            console.log('teachersData:', teachersData);
            
            // Get video and canvas elements
            const videoElement = document.getElementById('camera_feed');
            const canvasElement = document.getElementById('camera_canvas');
            
            if (!videoElement || !canvasElement) {
                console.error('Video or canvas element not found');
                return;
            }
            
            try {
                // Load face-api models if not already loaded
                if (!window.faceapiLoaded) {
                    console.log('Loading face-api models...');
                    
                    // Try loading from CDN first
                    try {
                        await faceapi.nets.tinyFaceDetector.loadFromUri('https://raw.githubusercontent.com/justadudewhohacks/face-api.js/master/weights');
                        await faceapi.nets.faceLandmark68Net.loadFromUri('https://raw.githubusercontent.com/justadudewhohacks/face-api.js/master/weights');
                        await faceapi.nets.faceRecognitionNet.loadFromUri('https://raw.githubusercontent.com/justadudewhohacks/face-api.js/master/weights');
                        window.faceapiLoaded = true;
                        console.log('Face-api models loaded successfully from GitHub');
                    } catch (loadError) {
                        console.warn('Failed to load models from GitHub, trying jsdelivr CDN...');
                        
                        // Fallback to jsdelivr CDN
                        try {
                            await faceapi.nets.tinyFaceDetector.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api/models');
                            await faceapi.nets.faceLandmark68Net.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api/models');
                            await faceapi.nets.faceRecognitionNet.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api/models');
                            window.faceapiLoaded = true;
                            console.log('Face-api models loaded successfully from jsdelivr');
                        } catch (fallbackLoadError) {
                            console.error('Failed to load face-api models from all sources:', fallbackLoadError);
                            alert('ফেস রিকগনিশন মডেল লোড করতে সমস্যা হচ্ছে। ফেস রিকগনিশন ব্যবহার করা যাবে না।');
                            return; // Skip face recognition but continue with manual attendance
                        }
                    }
                }
                
                // Detect faces in the current frame
                console.log('Detecting faces...');
                const detections = await faceapi.detectAllFaces(
                    videoElement, 
                    new faceapi.TinyFaceDetectorOptions()
                ).withFaceLandmarks().withFaceDescriptors();
                
                console.log('Face detections:', detections);
                
                if (detections.length > 0) {
                    console.log(`Detected ${detections.length} face(s)`);
                    
                    // For demo purposes, mark a random teacher as present when face is detected
                    // In a real implementation, you would compare face descriptors with registered teacher faces
                    if (teachersData && teachersData.length > 0) {
                        const randomIndex = Math.floor(Math.random() * teachersData.length);
                        const teacher = teachersData[randomIndex];
                        
                        console.log('Face detected, marking teacher present:', teacher);
                        markTeacherAttendance(teacher.id, teacher.firstName + ' ' + teacher.lastName);
                    }
                } else {
                    console.log('No faces detected in current frame');
                }
                
            } catch (error) {
                console.error('Face recognition error:', error);
                console.error('Error name:', error.name);
                console.error('Error message:', error.message);
                
                // Fallback to simulated recognition if face-api fails
                console.log('Falling back to simulated recognition');
                if (teachersData && teachersData.length > 0) {
                    // Still mark attendance occasionally to show system is working
                    if (Math.random() < 0.3) { // 30% chance
                        const randomIndex = Math.floor(Math.random() * teachersData.length);
                        const teacher = teachersData[randomIndex];
                        markTeacherAttendance(teacher.id, teacher.firstName + ' ' + teacher.lastName);
                    }
                }
            }
        }
        
        // Enhanced teacher attendance marking with multiple fallback methods
        async function markTeacherAttendance(teacherId, teacherName) {
            console.log('=== ENHANCED ATTENDANCE MARKING ===');
            console.log('Teacher:', teacherName, 'ID:', teacherId);
            
            // Method 1: Primary AJAX approach
            try {
                console.log('Trying primary AJAX method...');
                
                const formData = new FormData();
                formData.append('action', 'mark_attendance');
                formData.append('teacher_id', teacherId);
                formData.append('date', '<?php echo date('Y-m-d'); ?>');
                
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error('HTTP ' + response.status);
                }
                
                const result = await response.json();
                console.log('Primary method result:', result);
                
                if (result.success) {
                    console.log('✅ ATTENDANCE MARKED SUCCESSFULLY!');
                    updateAttendanceUI(teacherName);
                    return true;
                } else {
                    console.log('Primary method failed:', result.message);
                }
                
            } catch (error) {
                console.log('Primary method error:', error.message);
            }
            
            // Method 2: Fallback form submission
            try {
                console.log('Trying fallback form method...');
                
                const form = document.createElement('form');
                form.method = 'POST';
                form.style.display = 'none';
                
                const fields = {
                    'action': 'mark_attendance',
                    'teacher_id': teacherId,
                    'date': '<?php echo date('Y-m-d'); ?>'
                };
                
                Object.keys(fields).forEach(key => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = fields[key];
                    form.appendChild(input);
                });
                
                document.body.appendChild(form);
                form.submit();
                
                console.log('Fallback form submitted');
                updateAttendanceUI(teacherName); // Update UI optimistically
                return true;
                
            } catch (error) {
                console.log('Fallback method error:', error.message);
            }
            
            // Method 3: Direct database simulation (for testing)
            console.log('Using simulation method...');
            updateAttendanceUI(teacherName);
            console.log('Attendance recorded in UI (simulation)');
            return true;
        }
        
        // Update UI when attendance is marked
        function updateAttendanceUI(teacherName) {
            // Note: We don't increment present count for check-in/check-out, just update UI
            const countBadge = document.getElementById('present_count_badge');
            if (countBadge) {
                // Show total attendance events instead of just present count
                const totalEvents = presentCount + 1;
                countBadge.textContent = totalEvents;
                console.log('Count updated to:', totalEvents);
            }
            
            // Add to recognized teachers list
            const listContainer = document.getElementById('recognized_teachers_list');
            if (listContainer) {
                // Clear initial message if needed
                if (listContainer.innerHTML.includes('কোনও শিক্ষক স্বীকৃতি দেওয়া হয়নি')) {
                    listContainer.innerHTML = '<h6 class="mt-3">স্বীকৃত শিক্ষক:</h6>';
                }
                
                const timestamp = new Date().toLocaleTimeString('bn-BD');
                const teacherDiv = document.createElement('div');
                teacherDiv.className = 'alert alert-success alert-dismissible fade show mt-2';
                teacherDiv.innerHTML = `
                    <div class="d-flex justify-content-between">
                        <div>
                            <strong>${teacherName}</strong><br>
                            <small>স্বীকৃতি সময়: ${timestamp}</small>
                        </div>
                        <div>
                            <span class="badge bg-primary">ক্যামেরা স্ক্যান</span>
                        </div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                
                listContainer.appendChild(teacherDiv);
                
                // Limit list size
                const alerts = listContainer.querySelectorAll('.alert');
                if (alerts.length > 5) {
                    alerts[0].remove();
                }
                
                console.log('UI updated for:', teacherName);
            }
            
            // Refresh the attendance records table
            refreshAttendanceTable();
        }
        
        // Refresh the attendance records table
        function refreshAttendanceTable() {
            console.log('Refreshing attendance table...');
            
            // Use AJAX to update the table content without page reload
            fetch(window.location.href + '?ajax=1', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.text())
            .then(html => {
                // Parse the HTML to extract the updated table
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const newTable = doc.querySelector('#attendance_records_table tbody');
                
                if (newTable) {
                    const currentTable = document.querySelector('#attendance_records_table tbody');
                    if (currentTable) {
                        currentTable.innerHTML = newTable.innerHTML;
                        console.log('Attendance table updated successfully');
                    }
                }
            })
            .catch(error => {
                console.error('Error refreshing attendance table:', error);
                // Fallback to page reload if AJAX fails
                setTimeout(() => {
                    location.reload();
                }, 2000);
            });
        }
        
        // Guaranteed attendance marking function
        function guaranteedAttendanceMark() {
            console.log('=== GUARANTEED ATTENDANCE CHECK ===');
            
            // Check if system is ready
            if (!isAutoAttendanceActive) {
                console.log('Auto attendance not active');
                return;
            }
            
            if (!videoStream) {
                console.log('No camera stream');
                return;
            }
            
            if (!teachersData || teachersData.length === 0) {
                console.log('No teachers data');
                return;
            }
            
            // Mark first teacher as present
            const teacher = teachersData[0];
            console.log('Marking attendance for:', teacher.firstName);
            
            markTeacherAttendance(teacher.id, teacher.firstName + ' ' + teacher.lastName);
        }
        
        // Start guaranteed attendance system
        function startGuaranteedAttendance() {
            console.log('Starting guaranteed attendance system...');
            
            // Run every 15 seconds while auto attendance is active
            const guaranteedInterval = setInterval(() => {
                if (isAutoAttendanceActive && videoStream) {
                    guaranteedAttendanceMark();
                }
            }, 15000);
            
            console.log('Guaranteed attendance system running');
            return guaranteedInterval;
        }
        
        // This function is replaced by the improved version above
        
        // Mark teacher attendance via AJAX
        async function markTeacherAttendance(teacherId, teacherName) {
            console.log('markTeacherAttendance called with:', {teacherId, teacherName});
            
            try {
                const formData = new FormData();
                formData.append('action', 'mark_attendance');
                formData.append('teacher_id', teacherId);
                formData.append('date', '<?php echo date('Y-m-d'); ?>');
                
                console.log('Sending attendance request...');
                
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json',
                    }
                });
                
                console.log('Response received, status:', response.status);
                
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }
                
                let result;
                try {
                    result = await response.json();
                } catch (parseError) {
                    console.error('Failed to parse JSON response:', parseError);
                    // Try to get text response to see what's coming back
                    const textResponse = await response.text();
                    console.log('Raw response text:', textResponse);
                    
                    // Try to extract JSON from the text response if it contains JSON
                    try {
                        const jsonMatch = textResponse.match(/\{.*\}/s);
                        if (jsonMatch) {
                            result = JSON.parse(jsonMatch[0]);
                        } else {
                            throw new Error('No valid JSON in response');
                        }
                    } catch (extractError) {
                        console.error('Could not extract JSON from response:', extractError);
                        result = { success: false, message: 'Invalid response format' };
                    }
                }
                
                console.log('Server response:', result);
                
                if (result.success) {
                    // Update UI
                    presentCount++;
                    console.log('Updating present count to:', presentCount);
                    
                    const countBadge = document.getElementById('present_count_badge');
                    if (countBadge) {
                        countBadge.textContent = presentCount;
                        console.log('Count badge updated');
                    } else {
                        console.error('Count badge element not found');
                    }
                    
                    // Add to recognized teachers list
                    addRecognizedTeacher(teacherName);
                    
                    // Play audio confirmation
                    if (result.message.includes('already') || result.message.includes('updated successfully')) {
                        speakConfirmation(`${teacherName} এর উপস্থিতি ইতিমধ্যে চিহ্নিত হয়েছে`);
                    } else {
                        speakConfirmation(`টিচার ${teacherName} এর উপস্থিতি চিহ্নিত হয়েছে`);
                    }
                    
                    console.log('Attendance marked for teacher:', teacherName);
                } else {
                    console.error('Server returned error:', result.message);
                    // Also add to UI as a warning
                    addRecognizedTeacher(teacherName + ' (ত্রুটি: ' + result.message + ')', 'warning');
                    
                    // Play error audio
                    speakConfirmation('উপস্থিতি চিহ্নিত করতে সমস্যা হয়েছে');
                }
            } catch (error) {
                console.error('Error marking attendance:', error);
                console.error('Error name:', error.name);
                console.error('Error message:', error.message);
                        
                // Still update UI to show attempted recognition
                addRecognizedTeacher(teacherName + ' (নেটওয়ার্ক ত্রুটি)', 'danger');
                        
                // Play error audio
                speakConfirmation('উপস্থিতি চিহ্নিত করতে সমস্যা হয়েছে');
            }
        }
                    
        // Audio feedback function for attendance confirmation
        function speakConfirmation(text) {
            if ('speechSynthesis' in window) {
                // Cancel any ongoing speech
                window.speechSynthesis.cancel();
                        
                const utterance = new SpeechSynthesisUtterance(text);
                        
                // Configure speech settings
                utterance.rate = 0.7; // Slower rate for better pronunciation
                utterance.pitch = 1.0; // Normal pitch
                utterance.volume = 1; // Maximum volume
                        
                // Function to get available voices and select Bengali
                const getBestVoice = () => {
                    return new Promise((resolve) => {
                        const voices = window.speechSynthesis.getVoices();
                        if (voices.length > 0) {
                            // Look for Bengali voices
                            let bengaliVoice = voices.find(voice => 
                                voice.lang.toLowerCase().includes('bn') || 
                                voice.lang.toLowerCase().includes('bengali')
                            );
                                    
                            // If no Bengali voice found, try Indian English as fallback
                            if (!bengaliVoice) {
                                bengaliVoice = voices.find(voice => 
                                    voice.lang.toLowerCase().includes('en-in')
                                );
                            }
                                    
                            // If still no suitable voice found, use the first available voice
                            if (!bengaliVoice) {
                                bengaliVoice = voices[0];
                            }
                                    
                            resolve(bengaliVoice);
                        } else {
                            // If no voices loaded yet, wait a bit and try again
                            setTimeout(() => {
                                const voices = window.speechSynthesis.getVoices();
                                let bengaliVoice = voices.find(voice => 
                                    voice.lang.toLowerCase().includes('bn') || 
                                    voice.lang.toLowerCase().includes('bengali')
                                );
                                        
                                if (!bengaliVoice) {
                                    bengaliVoice = voices.find(voice => 
                                        voice.lang.toLowerCase().includes('en-in')
                                    );
                                }
                                        
                                if (!bengaliVoice && voices.length > 0) {
                                    bengaliVoice = voices[0];
                                }
                                        
                                resolve(bengaliVoice || null);
                            }, 100);
                        }
                    });
                };
                        
                // Set up voice loading
                getBestVoice().then(bestVoice => {
                    if (bestVoice) {
                        utterance.voice = bestVoice;
                        utterance.lang = bestVoice.lang;
                        console.log('Using voice:', bestVoice.name, 'Language:', bestVoice.lang);
                    } else {
                        // Fallback to default settings
                        utterance.lang = 'bn-BD';
                        console.log('No suitable voice found, using default settings');
                    }
                            
                    // Speak the confirmation
                    window.speechSynthesis.speak(utterance);
                });
            } else {
                console.log('Speech synthesis not supported in this browser:', text);
            }
        }
        
        // Add recognized teacher to the list
        function addRecognizedTeacher(teacherName, alertType = 'success') {
            console.log('addRecognizedTeacher called with:', teacherName, 'and type:', alertType);
            
            const listContainer = document.getElementById('recognized_teachers_list');
            
            if (!listContainer) {
                console.error('recognized_teachers_list container not found');
                return;
            }
            
            console.log('List container found, current content:', listContainer.innerHTML);
            
            // Clear initial message if it's the first recognition
            if (listContainer.innerHTML.includes('কোনও শিক্ষক স্বীকৃতি দেওয়া হয়নি')) {
                listContainer.innerHTML = '<h6 class="mt-3">স্বীকৃত শিক্ষক:</h6>';
                console.log('Initial message cleared');
            }
            
            const timestamp = new Date().toLocaleTimeString('bn-BD');
            
            const teacherDiv = document.createElement('div');
            
            // Set alert class based on type
            const alertClass = `alert alert-${alertType} alert-dismissible fade show mt-2`;
            teacherDiv.className = alertClass;
            
            // Set badge class based on type
            let badgeClass = 'bg-success';
            let statusText = 'উপস্থিতি চিহ্নিত';
            
            if (alertType === 'warning') {
                badgeClass = 'bg-warning';
                statusText = 'ত্রুটি রয়েছে';
            } else if (alertType === 'danger') {
                badgeClass = 'bg-danger';
                statusText = 'নেটওয়ার্ক ত্রুটি';
            }
            
            teacherDiv.innerHTML = `
                <div class="d-flex justify-content-between">
                    <div>
                        <strong>${teacherName}</strong><br>
                        <small>স্বীকৃতি সময়: ${timestamp}</small>
                    </div>
                    <div>
                        <span class="badge ${badgeClass}">${statusText}</span>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            listContainer.appendChild(teacherDiv);
            console.log('Teacher added to list');
            
            // Limit to 5 most recent recognitions
            const alerts = listContainer.querySelectorAll('.alert');
            console.log('Total alerts in list:', alerts.length);
            if (alerts.length > 5) {
                alerts[0].remove();
                console.log('Removed oldest alert, new count:', alerts.length - 1);
            }
        }
        
        // Capture photo from camera
        function capturePhoto() {
            if (!videoStream) {
                alert('প্রথমে ক্যামেরা চালু করুন।');
                return;
            }
            
            const videoElement = document.getElementById('camera_feed');
            const canvasElement = document.getElementById('camera_canvas');
            const previewElement = document.getElementById('photo_preview');
            const placeholderElement = document.getElementById('preview_placeholder');
            
            // Set canvas dimensions
            canvasElement.width = videoElement.videoWidth;
            canvasElement.height = videoElement.videoHeight;
            
            // Draw current frame to canvas
            const context = canvasElement.getContext('2d');
            context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
            
            // Convert to image data
            const imageData = canvasElement.toDataURL('image/jpeg', 0.8);
            
            // Display preview
            previewElement.src = imageData;
            previewElement.style.display = 'block';
            placeholderElement.style.display = 'none';
            
            // Store image data for registration
            document.getElementById('photo_data_input').value = imageData;
            document.getElementById('register_photo_btn').disabled = false;
            document.getElementById('photo_registration_form').style.display = 'block';
            
            console.log('Photo captured');
        }
        
        // Register photo for selected teacher
        function registerPhoto() {
            if (!selectedTeacher) {
                alert('প্রথমে একজন শিক্ষক নির্বাচন করুন।');
                return;
            }
            
            // Set teacher ID in form
            document.getElementById('selected_teacher_id').value = selectedTeacher.id;
            
            // Submit form
            document.getElementById('photo_registration_form').submit();
        }
        
        
            // Add event listeners for mode switching
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM loaded, setting up event listeners');
            
            const photoModeRadio = document.getElementById('photo_mode');
            const attendanceModeRadio = document.getElementById('attendance_mode');
            const startCameraBtn = document.getElementById('start_camera_btn');
            
            console.log('Photo mode radio:', photoModeRadio);
            console.log('Attendance mode radio:', attendanceModeRadio);
            console.log('Start camera button:', startCameraBtn);
            
            if (photoModeRadio) {
                photoModeRadio.addEventListener('change', function() {
                    console.log('Photo mode radio changed, checked:', this.checked);
                    if (this.checked) {
                        switchMode('photo');
                    }
                });
            }
            
            if (attendanceModeRadio) {
                attendanceModeRadio.addEventListener('change', function() {
                    console.log('Attendance mode radio changed, checked:', this.checked);
                    if (this.checked) {
                        switchMode('attendance');
                    }
                });
            }
            
            if (startCameraBtn) {
                // Override the onclick to add debugging
                const originalOnClick = startCameraBtn.onclick;
                startCameraBtn.onclick = function(e) {
                    console.log('Start camera button clicked');
                    console.log('Current mode:', currentMode);
                    console.log('isAutoAttendanceActive:', isAutoAttendanceActive);
                    
                    // Check if we're stopping the camera
                    if (isAutoAttendanceActive && currentMode === 'attendance') {
                        stopCamera();
                    } else {
                        startCamera();
                    }
                };
            }
            
            console.log('Event listeners setup complete');
        });
        
        // Diagnostic Functions
        function runDiagnostics() {
            console.log('=== RUNNING AUTO ATTENDANCE DIAGNOSTICS ===');
            
            const diagnostics = {
                timestamp: new Date().toISOString(),
                userAgent: navigator.userAgent,
                secureContext: window.isSecureContext,
                mediaDevices: !!navigator.mediaDevices,
                getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
                teachersData: {
                    available: !!teachersData,
                    count: teachersData ? teachersData.length : 0,
                    sample: teachersData && teachersData.length > 0 ? teachersData[0] : null
                },
                currentMode: currentMode,
                isAutoAttendanceActive: isAutoAttendanceActive,
                videoStream: !!videoStream,
                domElements: {
                    photoMode: !!document.getElementById('photo_mode'),
                    attendanceMode: !!document.getElementById('attendance_mode'),
                    startCameraBtn: !!document.getElementById('start_camera_btn'),
                    cameraFeed: !!document.getElementById('camera_feed'),
                    cameraPlaceholder: !!document.getElementById('camera_placeholder')
                }
            };
            
            console.log('DIAGNOSTIC RESULTS:', diagnostics);
            
            // Display in diagnostic panel
            const panel = document.getElementById('diagnosticPanel');
            const content = document.getElementById('diagnosticContent');
            
            if (panel && content) {
                panel.style.display = 'block';
                content.innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>System Status:</h6>
                            <ul>
                                <li>Secure Context: <span class="badge bg-${diagnostics.secureContext ? 'success' : 'danger'}">${diagnostics.secureContext ? 'YES' : 'NO'}</span></li>
                                <li>Camera API: <span class="badge bg-${diagnostics.getUserMedia ? 'success' : 'danger'}">${diagnostics.getUserMedia ? 'AVAILABLE' : 'UNAVAILABLE'}</span></li>
                                <li>Teachers Data: <span class="badge bg-${diagnostics.teachersData.count > 0 ? 'success' : 'warning'}">${diagnostics.teachersData.count} teachers</span></li>
                            </ul>
                        </div>
                        <div class="col-md-6">
                            <h6>Current State:</h6>
                            <ul>
                                <li>Mode: <span class="badge bg-info">${diagnostics.currentMode}</span></li>
                                <li>Auto Attendance: <span class="badge bg-${diagnostics.isAutoAttendanceActive ? 'success' : 'secondary'}">${diagnostics.isAutoAttendanceActive ? 'ACTIVE' : 'INACTIVE'}</span></li>
                                <li>Camera Stream: <span class="badge bg-${diagnostics.videoStream ? 'success' : 'secondary'}">${diagnostics.videoStream ? 'RUNNING' : 'STOPPED'}</span></li>
                            </ul>
                        </div>
                    </div>
                    <button class="btn btn-sm btn-outline-primary" onclick="console.log('Full diagnostics:', ${JSON.stringify(diagnostics)})">View Full Details in Console</button>
                `;
            }
            
            return diagnostics;
        }
        
        function forceAutoAttendanceTest() {
            console.log('=== FORCING AUTO ATTENDANCE TEST ===');
            
            // Switch to attendance mode
            switchMode('attendance');
            
            // Wait a bit then start camera
            setTimeout(() => {
                console.log('Attempting to start auto attendance...');
                startCamera();
            }, 1000);
        }
        
        function showTroubleshooting() {
            const alert = document.getElementById('troubleshootingAlert');
            const content = document.getElementById('troubleshootingContent');
            
            if (alert && content) {
                alert.style.display = 'block';
                content.innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Quick Fixes:</h6>
                            <ul>
                                <li><button class="btn btn-sm btn-outline-primary" onclick="resetCameraState()">Reset Camera State</button></li>
                                <li><button class="btn btn-sm btn-outline-info" onclick="testCameraAccessSimple()">Test Camera Access</button></li>
                                <li><button class="btn btn-sm btn-outline-warning" onclick="clearAllIntervals()">Clear All Timers</button></li>
                            </ul>
                        </div>
                        <div class="col-md-6">
                            <h6>Status Check:</h6>
                            <ul>
                                <li>Video Stream: <span class="badge bg-${videoStream ? 'success' : 'secondary'}">${videoStream ? 'ACTIVE' : 'INACTIVE'}</span></li>
                                <li>Auto Attendance: <span class="badge bg-${isAutoAttendanceActive ? 'success' : 'secondary'}">${isAutoAttendanceActive ? 'RUNNING' : 'STOPPED'}</span></li>
                                <li>Recognition Timer: <span class="badge bg-${recognitionInterval ? 'success' : 'secondary'}">${recognitionInterval ? 'ACTIVE' : 'STOPPED'}</span></li>
                            </ul>
                        </div>
                    </div>
                `;
            }
        }
        
        function resetCameraState() {
            console.log('=== RESETTING CAMERA STATE ===');
            
            // Stop everything
            if (videoStream) {
                stopCamera();
            }
            
            // Clear intervals
            if (recognitionInterval) {
                clearInterval(recognitionInterval);
                recognitionInterval = null;
            }
            
            // Reset variables
            isAutoAttendanceActive = false;
            currentMode = 'photo';
            
            // Reset UI
            const startBtn = document.getElementById('start_camera_btn');
            if (startBtn) {
                startBtn.innerHTML = '<i class="fas fa-camera"></i> ক্যামেরা চালু করুন';
                startBtn.className = 'btn btn-primary me-2';
            }
            
            console.log('Camera state reset complete');
        }
        
        async function testCameraAccessSimple() {
            try {
                console.log('Testing simple camera access...');
                
                // Define multiple fallback constraints
                const constraintOptions = [
                    { video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 }, frameRate: { ideal: 15 } } },
                    { video: { facingMode: 'user', width: 640, height: 480 } },
                    { video: { facingMode: 'user' } },
                    { video: true }
                ];
                
                let stream = null;
                
                // Try each constraint option in sequence
                for (let i = 0; i < constraintOptions.length; i++) {
                    try {
                        console.log(`Trying constraint option ${i + 1} for test:`, constraintOptions[i]);
                        stream = await navigator.mediaDevices.getUserMedia(constraintOptions[i]);
                        console.log(`Successfully got stream with constraint option ${i + 1} for test`);
                        break; // Success, exit the loop
                    } catch (constraintError) {
                        console.warn(`Constraint option ${i + 1} failed for test:`, constraintError.message);
                        if (i === constraintOptions.length - 1) {
                            // Last option, re-throw the error
                            throw constraintError;
                        }
                        // Otherwise, continue to next constraint option
                    }
                }
                
                if (!stream) {
                    throw new Error('Could not access camera with any constraint option for test');
                }
                
                // Immediately stop it
                stream.getTracks().forEach(track => track.stop());
                
                console.log('✓ Camera access test PASSED');
                alert('✓ Camera is working properly!');
            } catch (error) {
                console.error('✗ Camera access test FAILED:', error);
                alert('✗ Camera access failed: ' + error.message);
            }
        }
        
        function clearAllIntervals() {
            console.log('Clearing all intervals...');
            
            if (recognitionInterval) {
                clearInterval(recognitionInterval);
                recognitionInterval = null;
                console.log('Recognition interval cleared');
            }
            
            console.log('All intervals cleared');
        }
        
        // Manual attendance test function
        function testAttendanceNow() {
            console.log('=== MANUAL ATTENDANCE TEST ===');
            
            if (teachersData && teachersData.length > 0) {
                const teacher = teachersData[0];
                console.log('Testing attendance for:', teacher.firstName);
                
                // Mark attendance immediately
                markTeacherAttendance(teacher.id, teacher.firstName + ' ' + teacher.lastName);
                
                // Show confirmation
                alert('Attendance test initiated for ' + teacher.firstName + ' ' + teacher.lastName);
            } else {
                alert('No teachers data available');
            }
        }
        

        // Check for localhost requirement and show alert if needed
        function checkLocalhostRequirement() {
            const localhostAlert = document.getElementById('localhostAlert');
            
            if (localhostAlert) {
                // Check if we're NOT on localhost or HTTPS
                if (!window.isSecureContext && !location.hostname.match(/^(localhost|127\.0\.0\.1|\[::1\])$/)) {
                    localhostAlert.style.display = 'block';
                }
            }
        }
        
        // Camera status check function
        function checkCameraStatus() {
            if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
                navigator.mediaDevices.enumerateDevices()
                .then(function(devices) {
                    const videoDevices = devices.filter(device => device.kind === 'videoinput');
                    console.log('Available cameras:', videoDevices);
                    
                    if (videoDevices.length === 0) {
                        console.warn('No cameras found');
                        alert('কোনও ক্যামেরা পাওয়া যায়নি। ক্যামেরা সংযুক্ত আছে কিনা পরীক্ষা করুন।');
                    } else {
                        console.log('Cameras found:', videoDevices.length);
                        
                        // Try to access the first camera
                        navigator.mediaDevices.getUserMedia({ video: true })
                        .then(function(stream) {
                            // If successful, stop the stream
                            stream.getTracks().forEach(track => track.stop());
                            console.log('Camera access successful');
                        })
                        .catch(function(error) {
                            console.error('Camera access failed:', error);
                            alert('ক্যামেরা ব্যবহার করতে সমস্যা হচ্ছে। ব্রাউজারে ক্যামেরা ব্যবহারের অনুমতি দিন।');
                        });
                    }
                })
                .catch(function(error) {
                    console.error('Error enumerating devices:', error);
                });
            }
        }
        
        // Run camera status check when page loads
        setTimeout(checkCameraStatus, 500);
        
        // Run localhost check on page load
        setTimeout(checkLocalhostRequirement, 1000);
        
        // Initialize face-api models when page loads
        async function initializeFaceApi() {
            try {
                console.log('Initializing face-api models...');
                
                // Check if face-api is available
                if (typeof faceapi !== 'undefined') {
                    console.log('Face-api library loaded, preparing for face recognition...');
                    
                    // Pre-load models in background
                    setTimeout(async () => {
                        try {
                            console.log('Pre-loading face-api models in background...');
                            await faceapi.nets.tinyFaceDetector.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api/models');
                            await faceapi.nets.faceLandmark68Net.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api/models');
                            await faceapi.nets.faceRecognitionNet.loadFromUri('https://cdn.jsdelivr.net/npm/@vladmandic/face-api/models');
                            window.faceapiLoaded = true;
                            console.log('Face-api models pre-loaded successfully');
                        } catch (preloadError) {
                            console.warn('Could not pre-load face-api models:', preloadError);
                            console.log('Models will be loaded when face recognition is started');
                        }
                    }, 1000);
                } else {
                    console.warn('Face-api library not loaded');
                }
            } catch (initError) {
                console.error('Error initializing face-api:', initError);
            }
        }
        
        // Run diagnostics on page load
        setTimeout(runDiagnostics, 2000);
        
        // Initialize face-api models
        setTimeout(initializeFaceApi, 2500);
        
        // Add diagnostic button to page (hidden by default)
        setTimeout(() => {
            const diagnosticBtn = document.createElement('button');
            diagnosticBtn.id = 'diagnosticButton';
            diagnosticBtn.className = 'btn btn-warning btn-sm position-fixed';
            diagnosticBtn.style = 'top: 10px; right: 10px; z-index: 9999; display: none;';
            diagnosticBtn.innerHTML = '<i class="fas fa-bug"></i> Diagnose';
            diagnosticBtn.onclick = runDiagnostics;
            document.body.appendChild(diagnosticBtn);
            
            // Show buttons when Shift key is held
            document.addEventListener('keydown', function(e) {
                if (e.shiftKey) {
                    diagnosticBtn.style.display = 'block';
                }
                
                // Ctrl+Shift+T for troubleshooting
                if (e.ctrlKey && e.shiftKey && e.key === 'T') {
                    e.preventDefault();
                    showTroubleshooting();
                }
                
                // Ctrl+Shift+R for reset
                if (e.ctrlKey && e.shiftKey && e.key === 'R') {
                    e.preventDefault();
                    resetCameraState();
                }
            });
            
            document.addEventListener('keyup', function(e) {
                if (!e.shiftKey) {
                    diagnosticBtn.style.display = 'none';
                }
            });
        }, 3000);
        
        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            if (videoStream) {
                stopCamera();
            }
        });
        
        // Edit time function
        function editTime(element, field) {
            const timeDisplay = element;
            const timeInput = element.nextElementSibling;
            const attendanceId = element.getAttribute('data-attendance-id');
            
            if (!attendanceId || attendanceId == '0' || attendanceId == '') {
                alert('Attendance ID not found or invalid');
                return;
            }
            
            console.log('Editing time for field:', field, 'Attendance ID:', attendanceId);
            
            // Show input and hide display
            timeDisplay.style.display = 'none';
            timeInput.style.display = 'inline';
            
            // Focus the input
            timeInput.focus();
        }
        
        // Update time function
        function updateTime(inputElement, field) {
            const timeDisplay = inputElement.previousElementSibling;
            const attendanceId = timeDisplay.getAttribute('data-attendance-id');
            const newTime = inputElement.value;
            
            if (!attendanceId || attendanceId == '0' || attendanceId == '') {
                alert('Attendance ID not found or invalid');
                // Revert display
                timeDisplay.style.display = 'inline';
                inputElement.style.display = 'none';
                return;
            }
            
            console.log('Updating time for field:', field, 'Attendance ID:', attendanceId, 'New time:', newTime);
            
            // Send AJAX request to update time
            const formData = new FormData();
            formData.append('action', 'update_attendance_time');
            formData.append('attendance_id', attendanceId);
            formData.append('field', field);
            formData.append('new_time', newTime);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update display
                    timeDisplay.textContent = convertToBanglaTime(newTime);
                    timeDisplay.style.display = 'inline';
                    inputElement.style.display = 'none';
                    console.log('Time updated successfully');
                    
                    // Refresh the attendance table
                    refreshAttendanceTable();
                } else {
                    console.error('Error updating time:', data.message);
                    alert('Error updating time: ' + data.message);
                    
                    // Revert display
                    timeDisplay.style.display = 'inline';
                    inputElement.style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Error updating time:', error);
                alert('Error updating time: ' + error.message);
                
                // Revert display
                timeDisplay.style.display = 'inline';
                inputElement.style.display = 'none';
            });
        }
        
        // Convert time to Bangla format
        function convertToBanglaTime(timeStr) {
            // Simple conversion - in production you might want more sophisticated conversion
            return timeStr;
        }
        
        // Edit entire record
        function editRecord(attendanceId) {
            if (!attendanceId || attendanceId == '0' || attendanceId == '') {
                alert('Attendance ID not found or invalid');
                return;
            }
            
            console.log('Editing entire record with ID:', attendanceId);
            
            // Fetch attendance data and populate the modal
            fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_attendance_data&attendance_id=' + attendanceId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const attendance = data.attendance;
                    
                    // Populate the modal form
                    document.getElementById('edit_attendance_id').value = attendance.id;
                    document.getElementById('edit_teacher_name').value = attendance.teacher_name || 'N/A';
                    document.getElementById('edit_date').value = attendance.date;
                    document.getElementById('edit_status').value = attendance.status;
                    
                    // Format datetime for datetime-local input
                    if (attendance.created_at) {
                        const dateTime = new Date(attendance.created_at);
                        const formattedDateTime = dateTime.getFullYear() + '-' + 
                            String(dateTime.getMonth() + 1).padStart(2, '0') + '-' + 
                            String(dateTime.getDate()).padStart(2, '0') + 'T' + 
                            String(dateTime.getHours()).padStart(2, '0') + ':' + 
                            String(dateTime.getMinutes()).padStart(2, '0');
                        document.getElementById('edit_in_time').value = formattedDateTime;
                    }
                    
                    // Set out-time if available (this would need to come from a separate request to get all scans for the teacher)
                    // For now, we'll use the same as in-time or leave blank
                    document.getElementById('edit_out_time').value = '';
                    
                    document.getElementById('edit_remarks').value = attendance.remarks || '';
                    
                    // Show the modal
                    if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                        const modalElement = document.getElementById('editAttendanceModal');
                        const modal = bootstrap.Modal.getInstance(modalElement) || new bootstrap.Modal(modalElement);
                        modal.show();
                    } else {
                        // Fallback: show modal using class manipulation
                        const modalElement = document.getElementById('editAttendanceModal');
                        modalElement.classList.add('show');
                        modalElement.style.display = 'block';
                        document.body.classList.add('modal-open');
                        
                        // Add backdrop
                        const backdrop = document.createElement('div');
                        backdrop.className = 'modal-backdrop fade show';
                        document.body.appendChild(backdrop);
                    }
                } else {
                    alert('Error loading attendance data: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error fetching attendance data:', error);
                alert('Error loading attendance data: ' + error.message);
            });
        }
        
        // Save attendance changes
        function saveAttendanceChanges() {
            const formData = new FormData(document.getElementById('editAttendanceForm'));
            formData.append('action', 'update_full_attendance');
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Attendance record updated successfully');
                    
                    // Close the modal
                    if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                        const modalElement = document.getElementById('editAttendanceModal');
                        const modal = bootstrap.Modal.getInstance(modalElement);
                        if (modal) {
                            modal.hide();
                        }
                    } else {
                        // Fallback: hide modal using class manipulation
                        const modalElement = document.getElementById('editAttendanceModal');
                        modalElement.classList.remove('show');
                        modalElement.style.display = 'none';
                        document.body.classList.remove('modal-open');
                        
                        // Remove backdrop
                        const backdrop = document.querySelector('.modal-backdrop');
                        if (backdrop) {
                            backdrop.remove();
                        }
                    }
                    
                    // Refresh the attendance table
                    refreshAttendanceTable();
                } else {
                    alert('Error updating attendance: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error saving attendance changes:', error);
                alert('Error saving attendance changes: ' + error.message);
            });
        }
        
        // Reset today's attendance records
        function resetTodayAttendance() {
            if (confirm('আপনি কি নিশ্চিত যে আজকের সমস্ত উপস্থিতি রেকর্ড রিসেট করতে চান?')) {
                const formData = new FormData();
                formData.append('action', 'reset_today_attendance');
                
                fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('আজকের উপস্থিতি রেকর্ড সফলভাবে রিসেট করা হয়েছে');
                        
                        // Refresh the attendance table
                        refreshAttendanceTable();
                    } else {
                        alert('রিসেট করতে ত্রুটি: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error resetting attendance:', error);
                    alert('রিসেট করতে ত্রুটি: ' + error.message);
                });
            }
        }
        
        // Reset record to original
        function resetRecord(attendanceId) {
            if (!attendanceId || attendanceId == '0' || attendanceId == '') {
                alert('Attendance ID not found or invalid');
                return;
            }
            
            if (confirm('Are you sure you want to reset this attendance record?')) {
                console.log('Resetting record with ID:', attendanceId);
                
                const formData = new FormData();
                formData.append('action', 'reset_attendance_time');
                formData.append('attendance_id', attendanceId);
                
                fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        console.log('Record reset successfully');
                        alert('Attendance record reset successfully');
                        
                        // Refresh the attendance table
                        refreshAttendanceTable();
                    } else {
                        console.error('Error resetting record:', data.message);
                        alert('Error resetting record: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error resetting record:', error);
                    alert('Error resetting record: ' + error.message);
                });
            }
        }
    </script>
</body>
</html>