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

// 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);

// Get selected date (default to today)
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Get teachers for attendance
$stmt = $pdo->query("SELECT id, employee_id, first_name, last_name, photo FROM teachers WHERE status = 'active' ORDER BY first_name, last_name");
$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);

// Function to send auto message when attendance is marked
function sendTeacherAutoMessage($pdo, $teacher_id, $date) {
    try {
        // Get messaging configuration
        $config_stmt = $pdo->query("SELECT setting_key, setting_value FROM attendance_settings WHERE setting_key IN ('auto_message_enabled', 'message_template', 'sms_gateway', 'send_to_guardian', 'send_to_student', 'send_time_delay')");
        $config = $config_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        // Check if auto messaging is enabled
        if (!isset($config['auto_message_enabled']) || $config['auto_message_enabled'] !== '1') {
            return false;
        }
        
        // Get teacher details
        $stmt = $pdo->prepare("SELECT first_name, last_name, employee_id, phone FROM teachers WHERE id = ?");
        $stmt->execute([$teacher_id]);
        $teacher = $stmt->fetch();
        
        if (!$teacher) {
            return false;
        }
        
        // Prepare message
        $message_template = $config['message_template'] ?? 'আপনার সন্তান {student_name} এর উপস্থিতি সফলভাবে রেকর্ড করা হয়েছে। তারিখ: {date}';
        $message = $message_template;
        $message = str_replace('{student_name}', $teacher['first_name'] . ' ' . $teacher['last_name'], $message);
        $message = str_replace('{date}', date('d/m/Y', strtotime($date)), $message);
        $message = str_replace('{class}', 'Teacher', $message);
        $message = str_replace('{roll_number}', $teacher['employee_id'], $message);
        
        // Send message to teacher if configured and phone number exists
        if (isset($config['send_to_student']) && $config['send_to_student'] === '1' && !empty($teacher['phone'])) {
            error_log("Auto Message to Teacher ({$teacher['phone']}): $message");
        }
        
        return true;
    } catch (Exception $e) {
        error_log("Error sending auto message: " . $e->getMessage());
        return false;
    }
}

// Handle AJAX request for marking attendance
if (isset($_POST['action']) && $_POST['action'] === 'mark_attendance' && isset($_POST['teacher_id'])) {
    $teacher_id = (int)$_POST['teacher_id'];
    $date = $_POST['date'];
    
    try {
        // Check if attendance already exists for this teacher on this date
        $check_stmt = $pdo->prepare("SELECT id, status FROM attendance WHERE teacher_id = ? AND date = ?");
        $check_stmt->execute([$teacher_id, $date]);
        $existing_attendance = $check_stmt->fetch();
        
        if ($existing_attendance) {
            // Update existing attendance
            $stmt = $pdo->prepare(
                "UPDATE attendance SET 
                status = ?, remarks = ?, marked_by = ?, updated_at = NOW() 
                WHERE teacher_id = ? AND date = ?"
            );
            $stmt->execute(['present', 'Auto-marked via camera', $_SESSION['user_id'], $teacher_id, $date]);
            
            // Send auto message
            sendTeacherAutoMessage($pdo, $teacher_id, $date);
            
            echo json_encode(['success' => true, 'message' => 'Attendance already marked, updated successfully', 'was_already_present' => true]);
        } else {
            // Insert new attendance
            $stmt = $pdo->prepare(
                "INSERT INTO attendance (teacher_id, class_id, date, status, remarks, marked_by, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())"
            );
            $stmt->execute([$teacher_id, NULL, $date, 'present', 'Auto-marked via camera', $_SESSION['user_id']]);
            
            // Send auto message
            sendTeacherAutoMessage($pdo, $teacher_id, $date);
            
            echo json_encode(['success' => true, 'message' => 'Attendance marked successfully', 'was_already_present' => false]);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error handling attendance: ' . $e->getMessage()]);
    }
    exit;
}

// Get user info
$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'];
        }
    }
}
?>

<!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>
    
    <!-- CSS Libraries -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <link href="../assets/css/style.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .attendance-card {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }

        .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;
            position: relative;
            overflow: hidden;
        }
        
        #cameraFeed {
            filter: brightness(1.2) contrast(1.1) saturate(1.05);
            -webkit-filter: brightness(1.2) contrast(1.1) saturate(1.05);
        }

        .attendance-summary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 0.375rem;
            padding: 15px;
            text-align: center;
        }

        .recognized-student {
            background-color: #d4edda;
            border: 2px solid #28a745;
            border-radius: 0.375rem;
            padding: 10px;
            margin: 10px 0;
            animation: highlight 1s;
        }

        @keyframes highlight {
            0% { background-color: #fff3cd; }
            50% { background-color: #d4edda; }
            100% { background-color: #d4edda; }
        }

        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .status-present {
            background-color: #28a745;
        }

        .status-absent {
            background-color: #dc3545;
        }

        .status-recognizing {
            background-color: #ffc107;
        }

        .auto-attendance-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div class="sidebar-container">
        <?php echo $sidebar_html; ?>

        <div class="main-content">
            <!-- 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-calendar me-1"></i>
                        <?php echo date('d F Y', strtotime($selected_date)) . ' (' . date('l', strtotime($selected_date)) . ')'; ?>
                    </span>
                </p>
            </div>

            <!-- Floating Sidebar Toggle Button -->
            <button class="sidebar-toggle-float" onclick="toggleSidebar()" title="সাইডবার টগল করুন">
                <i class="fas fa-bars"></i>
            </button>

            <!-- Auto Attendance Toggle Button -->
            <button class="btn btn-success auto-attendance-btn" id="autoAttendanceToggle">
                <i class="fas fa-play"></i> অটো উপস্থিতি শুরু করুন
            </button>
            
            <!-- Content Body -->
            <div class="content-body">
                <div class="container-fluid mt-4">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card attendance-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">
                                    <!-- Date Selection -->
                                    <form method="GET" class="mb-4">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <label for="date" class="form-label">তারিখ</label>
                                                <input type="date" class="form-control" id="date" name="date"
                                                       value="<?php echo $selected_date; ?>" required>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label">&nbsp;</label>
                                                <div class="d-grid">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="fas fa-sync-alt"></i> রিফ্রেশ
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>

                                    <!-- Camera Feed -->
                                    <div class="row mb-4">
                                        <div class="col-md-8">
                                            <div class="camera-container">
                                                <div class="camera-feed">
                                                    <video id="cameraFeed" autoplay playsinline style="display: none; width: 100%; height: 100%; object-fit: cover;"></video>
                                                    <canvas id="cameraCanvas" style="display: none;"></canvas>
                                                    <div id="cameraPlaceholder">
                                                        <i class="fas fa-camera fa-3x mb-2"></i>
                                                        <p>ক্যামেরা ফিড এখানে প্রদর্শিত হবে</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="text-center mt-2">
                                                <small class="text-muted">ক্যামেরার সামনে দাঁড়ালে স্বয়ংক্রিয়ভাবে উপস্থিতি চিহ্নিত করা হবে</small>
                                                <div class="mt-2">
                                                   <small class="text-warning">
                                                       <i class="fas fa-info-circle"></i> ক্যামেরা কাজ না করলে নিশ্চিত করুন যে আপনি ঠিকানায় localhost ব্যবহার করছেন না IP ঠিকানা দিয়ে
                                                   </small>
                                               </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <!-- Attendance Summary -->
                                            <div class="row mb-4">
                                                <div class="col-md-12">
                                                    <div class="attendance-summary">
                                                        <h4 id="presentCount">0</h4>
                                                        <p>উপস্থিত শিক্ষক</p>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Recognized Teachers List -->
                                            <div class="card">
                                                <div class="card-header">
                                                    <h5><i class="fas fa-users"></i> শেষ স্বীকৃত শিক্ষক</h5>
                                                </div>
                                                <div class="card-body">
                                                    <div id="recognizedTeachers">
                                                        <p class="text-muted">কোনও শিক্ষক স্বীকৃতি দেওয়া হয়নি</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
            
                                    <!-- Teachers List -->
                                    <div class="card">
                                        <div class="card-header">
                                            <h5><i class="fas fa-list"></i> শিক্ষক তালিকা</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="table-responsive">
                                                <table class="table table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th>ছবি</th>
                                                            <th>কর্মচারী আইডি</th>
                                                            <th>নাম</th>
                                                            <th>উপস্থিতি</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($teachers as $teacher): ?>
                                                            <tr id="teacher_<?php echo $teacher['id']; ?>">
                                                                <td>
                                                                    <?php if ($teacher['photo'] && file_exists(__DIR__ . '/../' . $teacher['photo'])): ?>
                                                                        <img src="../<?php echo $teacher['photo']; ?>"
                                                                             alt="<?php echo $teacher['first_name']; ?>"
                                                                             class="profile-img-small" style="width: 40px; height: 40px; border: 2px solid #28a745;" data-has-photo="true">
                                                                    <?php else: ?>
                                                                        <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center"
                                                                             style="width: 40px; height: 40px;" data-has-photo="false">
                                                                            <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>
                                                                    <?php
                                                                    // Check if attendance is marked for this teacher on selected date
                                                                    $stmt = $pdo->prepare("SELECT status FROM attendance WHERE teacher_id = ? AND date = ?");
                                                                    $stmt->execute([$teacher['id'], $selected_date]);
                                                                    $attendance = $stmt->fetch();
                                                                    ?>
                                                                    <span class="status-indicator
                                                                        <?php
                                                                        if ($attendance) {
                                                                            echo $attendance['status'] === 'present' ? 'status-present' : 'status-absent';
                                                                        } else {
                                                                            echo 'status-absent';
                                                                        }
                                                                        ?>"></span>
                                                                    <?php
                                                                    if ($attendance) {
                                                                        echo $attendance['status'] === 'present' ? 'উপস্থিত' : 'অনুপস্থিত';
                                                                    } else {
                                                                        echo 'অনুপস্থিত';
                                                                    }
                                                                    ?>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
    <script>
        let videoStream = null;
        let isAutoAttendanceActive = false;
        let recognitionInterval = null;
        let cameraFeed, cameraCanvas, cameraPlaceholder, autoAttendanceToggle, recognizedTeachersDiv, presentCountElement;
        // Update present count
        function updatePresentCount() {
            let presentCount = 0;
            document.querySelectorAll('tbody tr').forEach(row => {
                const statusText = row.querySelector('td:last-child').textContent;
                if (statusText.includes('উপস্থিত')) {
                    presentCount++;
                }
            });
            if (presentCountElement) {
                presentCountElement.textContent = presentCount;
            }
        }

        // Wait for DOM to load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM loaded, initializing camera elements...');

            cameraFeed = document.getElementById('cameraFeed');
            cameraCanvas = document.getElementById('cameraCanvas');
            cameraPlaceholder = document.getElementById('cameraPlaceholder');
            autoAttendanceToggle = document.getElementById('autoAttendanceToggle');
            recognizedTeachersDiv = document.getElementById('recognizedTeachers');
            presentCountElement = document.getElementById('presentCount');

            console.log('Camera elements found:', {
                cameraFeed: !!cameraFeed,
                cameraCanvas: !!cameraCanvas,
                cameraPlaceholder: !!cameraPlaceholder,
                autoAttendanceToggle: !!autoAttendanceToggle,
                recognizedTeachersDiv: !!recognizedTeachersDiv,
                presentCountElement: !!presentCountElement
            });

            if (!autoAttendanceToggle) {
                console.error('ERROR: autoAttendanceToggle button not found!');
                alert('ERROR: Camera button not found on page!');
                return;
            }

            // Toggle auto attendance
            autoAttendanceToggle.addEventListener('click', async () => {
                if (!isAutoAttendanceActive) {
                    await startAutoAttendance();
                } else {
                    stopAutoAttendance();
                }
            });

            console.log('Camera button event listener attached successfully');

            // Initialize present count
            updatePresentCount();

            // Auto-submit form when date changes
            document.getElementById('date').addEventListener('change', function() {
                this.form.submit();
            });
        });

        // Start auto attendance system
        async function startAutoAttendance() {
            try {
                // Check if mediaDevices is supported
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    console.error('Camera API not supported');
                    throw new Error('Camera access is not supported in this browser. Please use a modern browser like Chrome, Firefox, or Edge.');
                }

                // Check if we're on a secure context (HTTPS, localhost, or 127.0.0.1)
                const isSecureContext = window.isSecureContext;
                console.log('Is secure context:', isSecureContext);

                // Get camera access with multiple fallback options
                let stream;
                const constraints = [
                    // Try front camera first (more common for attendance)
                    { video: { facingMode: { ideal: 'user' }, width: { ideal: 640 }, height: { ideal: 480 } } },
                    // Try rear camera
                    { video: { facingMode: { ideal: 'environment' }, width: { ideal: 640 }, height: { ideal: 480 } } },
                    // Try any camera with specific resolution
                    { video: { width: { ideal: 640 }, height: { ideal: 480 } } },
                    // Try any camera with basic constraints
                    { video: true }
                ];

                for (let constraint of constraints) {
                    try {
                        console.log('Trying camera constraint:', constraint);
                        stream = await navigator.mediaDevices.getUserMedia(constraint);
                        console.log('Camera access successful with constraint:', constraint);
                        break;
                    } catch (constraintErr) {
                        console.warn('Camera constraint failed:', constraint, constraintErr);
                        if (constraint === constraints[constraints.length - 1]) {
                            // This was the last constraint, rethrow the error
                            throw constraintErr;
                        }
                    }
                }

                videoStream = stream;
                cameraFeed.srcObject = stream;
                cameraFeed.style.display = 'block';
                cameraPlaceholder.style.display = 'none';

                // Update button state
                isAutoAttendanceActive = true;
                autoAttendanceToggle.innerHTML = '<i class="fas fa-stop"></i> অটো উপস্থিতি বন্ধ করুন';
                autoAttendanceToggle.className = 'btn btn-danger auto-attendance-btn';

                // Start periodic recognition
                recognitionInterval = setInterval(recognizeFace, 2000); // Check every 2 seconds

                console.log('Auto attendance started');
            } catch (err) {
                console.error('Error accessing camera:', err);
                let errorMessage = 'ক্যামেরা ব্যবহার করতে অসুবিধা হচ্ছে। ';
                if (err.name === 'NotAllowedError') {
                    errorMessage += 'ক্যামেরা অনুমতি দিন। ব্রাউজারে ক্যামেরা অনুমতি সক্ষম করুন।';
                } else if (err.name === 'NotFoundError') {
                    errorMessage += 'কোনো ক্যামেরা পাওয়া যায়নি।';
                } else if (err.name === 'NotReadableError') {
                    errorMessage += 'ক্যামেরা অন্য অ্যাপ্লিকেশনে ব্যবহার হচ্ছে।';
                } else if (err.name === 'OverconstrainedError') {
                    errorMessage += 'ক্যামেরা সেটিংস সমর্থিত নয়।';
                } else if (err.name === 'SecurityError') {
                    errorMessage += 'ক্যামেরা ব্যবহারের জন্য সিকিউর কানেকশন (HTTPS) প্রয়োজন। MAMP এ আপনি হয় localhost নামে বা 127.0.0.1 ঠিকানায় সাইটটি চালাচ্ছেন তা নিশ্চিত করুন।';
                } else {
                    errorMessage += 'বিস্তারিত ত্রুটি: ' + (err.message || 'অজানা ত্রুটি');
                }

                alert(errorMessage + '\n\nপরামর্শ: Chrome/Firefox ব্রাউজার ব্যবহার করুন, ক্যামেরা অনুমতি দিন, এবং সঠিক ঠিকানায় সাইটটি ব্যবহার করুন।');
            }
        }

        // Stop auto attendance system
        // Stop auto attendance system
        function stopAutoAttendance() {
            if (videoStream) {
                const tracks = videoStream.getTracks();
                tracks.forEach(track => track.stop());
                videoStream = null;
                cameraFeed.srcObject = null;
                cameraFeed.style.display = 'none';
                cameraPlaceholder.style.display = 'flex';
            }

            // Clear recognition interval
            if (recognitionInterval) {
                clearInterval(recognitionInterval);
                recognitionInterval = null;
            }

            // Update button state
            isAutoAttendanceActive = false;
            autoAttendanceToggle.innerHTML = '<i class="fas fa-play"></i> অটো উপস্থিতি শুরু করুন';
            autoAttendanceToggle.className = 'btn btn-success auto-attendance-btn';

            console.log('Auto attendance stopped');
        }

        // Simulate face recognition and attendance marking
        async function recognizeFace() {
            if (!isAutoAttendanceActive) {
                console.log('Recognition skipped - auto attendance not active');
                return;
            }
            console.log('Recognizing face...');

            // Draw current frame to canvas for processing
            cameraCanvas.width = cameraFeed.videoWidth;
            cameraCanvas.height = cameraFeed.videoHeight;
            const context = cameraCanvas.getContext('2d');
            context.drawImage(cameraFeed, 0, 0, cameraCanvas.width, cameraCanvas.height);

            // Convert to data URL for processing
            const imageData = cameraCanvas.toDataURL('image/jpeg');

            // In a real implementation, this would send the image to a face recognition service
            // For now, we'll simulate recognition by randomly selecting a teacher

            // The above code was incorrectly looking for class_id which doesn't exist on teacher page

            // Simulate face recognition by randomly selecting a teacher from the current list
            // Only select teachers who have registered photos (green border indicates photo exists)
            const teacherRows = document.querySelectorAll('tbody tr[id^="teacher_"]');
            if (teacherRows.length > 0) {
                // Filter teachers who have photos (check for data-has-photo attribute)
                const teachersWithPhotos = Array.from(teacherRows).filter(row => {
                    // Check if the row has an image with data-has-photo="true"
                    const imgElement = row.querySelector('img[data-has-photo="true"]');

                    // A teacher has a photo if the img tag has data-has-photo="true"
                    return imgElement !== null;
                });

                if (teachersWithPhotos.length > 0) {
                    // Randomly select a teacher from those with photos (simulating recognition)
                    const randomIndex = Math.floor(Math.random() * teachersWithPhotos.length);
                    const teacherRow = teachersWithPhotos[randomIndex];
                    const teacherId = teacherRow.id.replace('teacher_', '');

                    // Check if this teacher is already marked present today
                    const statusElement = teacherRow.querySelector('td:last-child');
                    if (!statusElement.textContent.includes('উপস্থিত')) {
                        const teacherName = getTeacherNameById(teacherId);
                        
                        // Mark attendance for this teacher
                        markAttendance(teacherId, teacherName);
                        
                        // Play immediate audio confirmation of scan completion
                        speakConfirmation(`স্ক্যান সম্পন্ন, টিচার ${teacherName} এর উপস্থিতি চিহ্নিত হচ্ছে`);
                    } else {
                        const teacherName = getTeacherNameById(teacherId);
                        // Teacher already marked as present, provide feedback
                        speakConfirmation(`টিচার ${teacherName} এর উপস্থিতি ইতিমধ্যে চিহ্নিত হয়েছে`);
                    }
                } else {
                    // No teachers with photos found, but we can still simulate a scan
                    speakConfirmation('কোন টিচার স্ক্যান করা হয়নি, ছবি নেই');
                }
            }
        }

        // Get teacher name by ID
        function getTeacherNameById(teacherId) {
            const teacherRow = document.getElementById(`teacher_${teacherId}`);
            if (teacherRow) {
                return teacherRow.querySelector('td:nth-child(3) strong').textContent;
            }
            return 'Unknown';
        }
                
        // Mark attendance for a teacher via AJAX
        async function markAttendance(teacherId, teacherName) {
            const date = document.getElementById('date').value;
        
            try {
                const response = await fetch('', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=mark_attendance&teacher_id=${teacherId}&date=${date}`
                });
        
                const result = await response.json();
        
                if (result.success) {
                    // Update UI to show attendance marked
                    const teacherRow = document.getElementById(`teacher_${teacherId}`);
                    if (teacherRow) {
                        const statusElement = teacherRow.querySelector('td:last-child');
                        statusElement.innerHTML = '<span class="status-indicator status-present"></span> উপস্থিত';
                                        
                        // Add to recognized teachers list
                        addRecognizedTeacher(teacherId);
                                        
                        // Update present count
                        updatePresentCount();
                                        
                        // Play audio confirmation based on whether attendance was already marked
                        if (result.was_already_present) {
                            speakConfirmation(`${teacherName} এর উপস্থিতি ইতিমধ্যে চিহ্নিত হয়েছে`);
                        } else {
                            speakConfirmation(`টিচার ${teacherName} এর উপস্থিতি চিহ্নিত হয়েছে`);
                        }
                    }
                
                    console.log('Attendance marked for teacher:', teacherId);
                } else {
                    console.error('Error marking attendance:', result.message);
                    // Play error audio
                    speakConfirmation('উপস্থিতি চিহ্নিত করতে সমস্যা হয়েছে');
                }
            } catch (error) {
                console.error('Error marking attendance:', error);
                // Play error audio
                speakConfirmation('উপস্থিতি চিহ্নিত করতে সমস্যা হয়েছে');
            }
        }

        // Add recognized teacher to the list
        function addRecognizedTeacher(teacherId) {
            const teacherRow = document.getElementById(`teacher_${teacherId}`);
            if (!teacherRow) return;

            const teacherName = teacherRow.querySelector('td:nth-child(3) strong').textContent;
            const teacherRoll = teacherRow.querySelector('td:nth-child(2) .badge').textContent;

            const timestamp = new Date().toLocaleTimeString('bn-BD');

            const teacherDiv = document.createElement('div');
            teacherDiv.className = 'recognized-student';
            teacherDiv.innerHTML = `
                <div class="d-flex justify-content-between">
                    <div>
                        <strong>${teacherName}</strong><br>
                        <small>আইডি: ${teacherRoll}</small>
                    </div>
                    <div class="text-end">
                        <small class="text-muted">${timestamp}</small><br>
                        <span class="badge bg-success">উপস্থিতি চিহ্নিত</span>
                    </div>
                </div>
            `;

            // Add to top of the list
            recognizedTeachersDiv.insertBefore(teacherDiv, recognizedTeachersDiv.firstChild);

            // Limit to 5 most recent recognitions
            const allRecognized = recognizedTeachersDiv.querySelectorAll('.recognized-student');
            if (allRecognized.length > 5) {
                recognizedTeachersDiv.removeChild(allRecognized[allRecognized.length - 1]);
            }
        }
        
        // 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);
            }
        }
    </script>
</body>
</html>