<?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 admin 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 students and teachers for registration
$stmt = $pdo->query("SELECT id, student_id, first_name, last_name, roll_number, photo FROM students WHERE status = 'active' ORDER BY first_name, last_name");
$students = $stmt->fetchAll();

$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();

$type = $_GET['type'] ?? 'student';
$id = $_GET['id'] ?? null;

$success_message = '';
$error_message = '';

// Handle biometric registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_biometric'])) {
    $user_type = $_POST['user_type'];
    $user_id = (int)$_POST['user_id'];
    $method = $_POST['method'];
    $biometric_data = $_POST['biometric_data'] ?? '';
        
    // Validate inputs
    if (empty($user_type) || empty($user_id) || empty($method)) {
        $error_message = 'সব তথ্য প্রয়োজন';
    } else {
        $user_name = '';
            
        if ($user_type === 'student') {
            $stmt = $pdo->prepare("SELECT first_name, last_name FROM students WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            if ($user) {
                $user_name = $user['first_name'] . ' ' . $user['last_name'];
            }
        } else {
            $stmt = $pdo->prepare("SELECT first_name, last_name FROM teachers WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            if ($user) {
                $user_name = $user['first_name'] . ' ' . $user['last_name'];
            }
        }
            
        // Handle biometric data storage
        if ($method === 'face' && !empty($biometric_data)) {
            // Extract image data from base64
            $image_parts = explode(";base64,", $biometric_data);
            $image_type_aux = explode("image/", $image_parts[0]);
            $image_type = $image_type_aux[1];
            $image_base64 = base64_decode($image_parts[1]);

            // Validate image type
            $allowed_types = ['jpeg', 'jpg', 'png'];
            if (in_array(strtolower($image_type), $allowed_types)) {
                // Create upload directory if it doesn't exist
                $upload_dir = '../uploads/biometric_faces/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }

                // Generate unique filename
                $filename = $user_type . '_' . $user_id . '_' . time() . '_face.' . $image_type;
                $filepath = $upload_dir . $filename;

                // Save image to file
                if (file_put_contents($filepath, $image_base64)) {
                    // Save biometric template record to database
                    $stmt = $pdo->prepare("INSERT INTO biometric_templates (user_type, user_id, template_data, template_type, status) VALUES (?, ?, ?, 'face', 'active') ON DUPLICATE KEY UPDATE template_data = VALUES(template_data), status = 'active'");
                    $relative_path = substr($filepath, 3); // Remove '../' prefix
                    if ($stmt->execute([$user_type, $user_id, $relative_path])) {
                        $method_name = 'ফেস';
                        $success_message = "$method_name রেজিস্ট্রেশন সফল হয়েছে: $user_name";
                    } else {
                        $error_message = 'ডাটাবেসে ফেস ডেটা সংরক্ষণ করতে সমস্যা হয়েছে';
                    }
                } else {
                    $error_message = 'ছবি সংরক্ষণ করতে সমস্যা হয়েছে';
                }
            } else {
                $error_message = 'শুধুমাত্র JPEG এবং PNG ছবি অনুমোদিত';
            }
        } elseif ($method === 'fingerprint') {
            // For fingerprint, we'll store a simulated template
            $fingerprint_template = "simulated_fingerprint_template_for_{$user_type}_{$user_id}_" . time();
            $stmt = $pdo->prepare("INSERT INTO biometric_templates (user_type, user_id, template_data, template_type, status) VALUES (?, ?, ?, 'fingerprint', 'active') ON DUPLICATE KEY UPDATE template_data = VALUES(template_data), status = 'active'");
            if ($stmt->execute([$user_type, $user_id, $fingerprint_template])) {
                $method_name = 'ফিংগারপ্রিন্ট';
                $success_message = "$method_name রেজিস্ট্রেশন সফল হয়েছে: $user_name";
            } else {
                $error_message = 'ফিংগারপ্রিন্ট ডেটা সংরক্ষণ করতে সমস্যা হয়েছে';
            }
        } else {
            // If face method but no biometric data provided
            if ($method === 'face') {
                $error_message = 'ফেস ডেটা প্রয়োজন';
            } else {
                $error_message = 'অজানা বায়োমেট্রিক পদ্ধতি';
            }
        }
    }
}

// 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>
    <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>
        .registration-card {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        
        .user-item {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .user-item:hover {
            background-color: #f8f9fa;
            transform: translateY(-2px);
            box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
        }
        
        .user-item.selected {
            background-color: #e7f5ff;
            border-color: #339af0;
        }
        
        .biometric-container {
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
            border: 2px solid #dee2e6;
            border-radius: 0.375rem;
            overflow: hidden;
            margin-top: 20px;
        }
        
        .biometric-device {
            width: 100%;
            height: 300px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: white;
            border-radius: 0.375rem;
        }
        
        .fingerprint-device {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .face-device {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        .device-icon {
            font-size: 4em;
            margin-bottom: 15px;
        }
        
        .scan-button {
            margin-top: 15px;
            padding: 10px 20px;
            background-color: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 0.375rem;
            color: white;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .scan-button:hover {
            background-color: rgba(255, 255, 255, 0.3);
        }
        
        .preview-container {
            width: 100%;
            height: 300px;
            background-color: #000;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2em;
        }
    </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-id-card 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">
        <div class="row">
            <div class="col-md-12">
                <div class="card registration-card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-id-card"></i> বায়োমেট্রিক রেজিস্ট্রেশন</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="">
                            <input type="hidden" name="user_id" id="user_id_input" value="">
                            <input type="hidden" name="user_type" id="user_type_input" value="<?php echo $type; ?>">
                            <input type="hidden" name="biometric_data" id="biometric_data" value="">
                            
                            <!-- User Type Selection -->
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="type_selector" id="student_type" value="student" <?php echo $type === 'student' ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-primary" for="student_type">ছাত্র</label>
                                        
                                        <input type="radio" class="btn-check" name="type_selector" id="teacher_type" value="teacher" <?php echo $type === 'teacher' ? 'checked' : ''; ?>>
                                        <label class="btn btn-outline-primary" for="teacher_type">শিক্ষক</label>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- User Selection -->
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <h6>ব্যবহারকারী নির্বাচন করুন:</h6>
                                    <div class="row">
                                        <?php if ($type === 'student'): ?>
                                            <?php foreach ($students as $student): ?>
                                                <div class="col-md-3 col-sm-6 mb-2">
                                                    <div class="user-item" data-user-id="<?php echo $student['id']; ?>" data-user-type="student">
                                                        <?php if ($student['photo'] && file_exists(__DIR__ . '/../' . ltrim($student['photo'], '/'))): ?>
                                                            <img src="..<?php echo $student['photo']; ?>"
                                                                 alt="<?php echo $student['first_name']; ?>" 
                                                                 class="rounded-circle" style="width: 40px; height: 40px; float: left; margin-right: 10px;">
                                                        <?php else: ?>
                                                            <div class="bg-secondary rounded-circle d-inline-block" 
                                                                 style="width: 40px; height: 40px; float: left; margin-right: 10px;">
                                                                <i class="fas fa-user text-white"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div>
                                                            <strong><?php echo $student['first_name'] . ' ' . $student['last_name']; ?></strong><br>
                                                            <small class="text-muted">রোল: <?php echo $student['roll_number']; ?></small>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <?php foreach ($teachers as $teacher): ?>
                                                <div class="col-md-3 col-sm-6 mb-2">
                                                    <div class="user-item" data-user-id="<?php echo $teacher['id']; ?>" data-user-type="teacher">
                                                        <?php if ($teacher['photo'] && file_exists(__DIR__ . '/../' . ltrim($teacher['photo'], '/'))): ?>
                                                            <img src="..<?php echo $teacher['photo']; ?>"
                                                                 alt="<?php echo $teacher['first_name']; ?>" 
                                                                 class="rounded-circle" style="width: 40px; height: 40px; float: left; margin-right: 10px;">
                                                        <?php else: ?>
                                                            <div class="bg-secondary rounded-circle d-inline-block" 
                                                                 style="width: 40px; height: 40px; float: left; margin-right: 10px;">
                                                                <i class="fas fa-user text-white"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div>
                                                            <strong><?php echo $teacher['first_name'] . ' ' . $teacher['last_name']; ?></strong><br>
                                                            <small class="text-muted">ID: <?php echo $teacher['employee_id']; ?></small>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Biometric Method Selection -->
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <h6>বায়োমেট্রিক পদ্ধতি নির্বাচন করুন:</h6>
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="method" id="fingerprint_method" value="fingerprint">
                                        <label class="btn btn-outline-success" for="fingerprint_method">
                                            <i class="fas fa-fingerprint"></i> ফিংগারপ্রিন্ট
                                        </label>
                                        
                                        <input type="radio" class="btn-check" name="method" id="face_method" value="face">
                                        <label class="btn btn-outline-info" for="face_method">
                                            <i class="fas fa-user"></i> মুখমণ্ডল
                                        </label>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Biometric Device -->
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <h6>বায়োমেট্রিক ডিভাইস:</h6>
                                    <div id="biometric_container" class="biometric-container" style="display: none;">
                                        <div id="fingerprint_device" class="biometric-device fingerprint-device">
                                            <i class="fas fa-fingerprint device-icon"></i>
                                            <h5>ফিংগারপ্রিন্ট স্ক্যানার</h5>
                                            <p>আপনার আঙুল স্ক্যান করুন</p>
                                            <div class="scan-button" id="scan_fingerprint_btn">
                                                <i class="fas fa-hand-pointer"></i> স্ক্যান শুরু করুন
                                            </div>
                                        </div>
                                        
                                        <div id="face_device" class="biometric-device face-device" style="display: none;">
                                            <i class="fas fa-user device-icon"></i>
                                            <h5>ফেস রিকগনিশন ক্যামেরা</h5>
                                            <p>ক্যামেরার সামনে দাঁড়ান</p>
                                            <div class="scan-button" id="scan_face_btn">
                                                <i class="fas fa-camera"></i> স্ক্যান শুরু করুন
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div id="preview_container" class="preview-container" style="display: none;">
                                        <video id="cameraPreview" autoplay playsinline style="display: none;"></video>
                                        <canvas id="cameraCanvas" style="display: none;"></canvas>
                                        <div id="previewPlaceholder">
                                            <i class="fas fa-user fa-3x mb-2"></i>
                                            <p>ক্যামেরা প্রিভিউ এখানে দেখানো হবে</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Action Buttons -->
                            <div class="row">
                                <div class="col-md-12">
                                    <button type="submit" name="register_biometric" id="register_btn" class="btn btn-success" disabled>
                                        <i class="fas fa-save"></i> বায়োমেট্রিক রেজিস্টার করুন
                                    </button>
                                    <button type="button" id="clear_selection_btn" class="btn btn-secondary ms-2">
                                        <i class="fas fa-undo"></i> নির্বাচন সাফ করুন
                                    </button>
                                    <a href="dashboard.php" class="btn btn-primary ms-2">
                                        <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
            </div> <!-- End content-body -->
            
            <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 src="../assets/js/face-detection.js"></script>
            <script>
                // User selection handling
                document.querySelectorAll('.user-item').forEach(item => {
                    item.addEventListener('click', function() {
                        // Remove selected class from all items
                        document.querySelectorAll('.user-item').forEach(i => i.classList.remove('selected'));
                        
                        // Add selected class to clicked item
                        this.classList.add('selected');
                        
                        // Set the user ID and type in the form
                        const userId = this.getAttribute('data-user-id');
                        const userType = this.getAttribute('data-user-type');
                        
                        document.getElementById('user_id_input').value = userId;
                        document.getElementById('user_type_input').value = userType;
                        
                        // Enable the register button
                        document.getElementById('register_btn').disabled = false;
                    });
                });
                
                // User type switching
                document.getElementById('student_type').addEventListener('change', function() {
                    if (this.checked) {
                        window.location.href = '?type=student';
                    }
                });
                
                document.getElementById('teacher_type').addEventListener('change', function() {
                    if (this.checked) {
                        window.location.href = '?type=teacher';
                    }
                });
                
                // Biometric method selection
                document.getElementById('fingerprint_method').addEventListener('change', function() {
                    if (this.checked) {
                        document.getElementById('fingerprint_device').style.display = 'flex';
                        document.getElementById('face_device').style.display = 'none';
                        document.getElementById('biometric_container').style.display = 'block';
                        document.getElementById('preview_container').style.display = 'none';
                    }
                });
                
                document.getElementById('face_method').addEventListener('change', function() {
                    if (this.checked) {
                        document.getElementById('fingerprint_device').style.display = 'none';
                        document.getElementById('face_device').style.display = 'flex';
                        document.getElementById('biometric_container').style.display = 'block';
                        document.getElementById('preview_container').style.display = 'block';
                    }
                });
                
                // Fingerprint scanning
                document.getElementById('scan_fingerprint_btn').addEventListener('click', function() {
                    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> স্ক্যান হচ্ছে...';
                    this.style.backgroundColor = 'rgba(255, 255, 255, 0.4)';
                    
                    // Simulate scanning process
                    setTimeout(() => {
                        this.innerHTML = '<i class="fas fa-check"></i> সফল!';
                        this.style.backgroundColor = 'rgba(40, 167, 69, 0.3)';
                        
                        // Reset after delay
                        setTimeout(() => {
                            this.innerHTML = '<i class="fas fa-hand-pointer"></i> স্ক্যান শুরু করুন';
                            this.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
                        }, 2000);
                        
                        alert('ফিংগারপ্রিন্ট সফলভাবে রেজিস্টার করা হয়েছে!');
                    }, 2000);
                });
                
                // Face scanning
                let videoStream = null;
                const cameraPreview = document.getElementById('cameraPreview');
                const cameraCanvas = document.getElementById('cameraCanvas');
                const previewPlaceholder = document.getElementById('previewPlaceholder');
                
                document.getElementById('scan_face_btn').addEventListener('click', async function() {
                    try {
                        // Load face-api.js if not already loaded
                        await loadFaceApi();
                        
                        const stream = await navigator.mediaDevices.getUserMedia({ 
                            video: { facingMode: 'user' } 
                        });
                        
                        videoStream = stream;
                        cameraPreview.srcObject = stream;
                        cameraPreview.style.display = 'block';
                        previewPlaceholder.style.display = 'none';
                        
                        // Initialize face detection models
                        await initializeFaceModels();
                        
                        // Continuously detect faces and provide feedback to user
                        const detectFaces = async () => {
                            if (!videoStream) return;

                            try {
                                const validationResult = await validateFaceAlignment(cameraPreview);
                                
                                // Update button text based on validation result
                                if (validationResult.isValid) {
                                    this.innerHTML = '<i class="fas fa-smile"></i> মুখমণ্ডল ঠিক আছে! ক্যাপচার হচ্ছে...';
                                    this.style.backgroundColor = 'rgba(40, 167, 69, 0.3)';
                                    
                                    // Wait 2 seconds to allow user to ensure proper positioning
                                    setTimeout(async () => {
                                        // Capture the face image
                                        const canvas = document.createElement('canvas');
                                        canvas.width = cameraPreview.videoWidth;
                                        canvas.height = cameraPreview.videoHeight;
                                        
                                        const context = canvas.getContext('2d');
                                        context.drawImage(cameraPreview, 0, 0, canvas.width, canvas.height);
                                        
                                        // Convert to data URL and store in hidden input
                                        const imageData = canvas.toDataURL('image/jpeg', 0.8); // Use direct capture after validation
                                        document.getElementById('biometric_data').value = imageData;
                                        
                                        // Stop the camera after successful capture
                                        if (videoStream) {
                                            const tracks = videoStream.getTracks();
                                            tracks.forEach(track => track.stop());
                                            videoStream = null;
                                            cameraPreview.srcObject = null;
                                            cameraPreview.style.display = 'none';
                                            previewPlaceholder.style.display = 'flex';
                                            
                                            this.innerHTML = '<i class="fas fa-check"></i> সফল!';
                                            
                                            // Alert user that face has been captured
                                            alert('মুখমণ্ডল সঠিকভাবে ক্যাপচার করা হয়েছে! এখন রেজিস্টার বাটনে ক্লিক করুন।');
                                        }
                                        
                                        // Remove interval after successful capture
                                        clearInterval(detectInterval);
                                    }, 2000); // Wait 2 seconds before capture
                                } else {
                                    this.innerHTML = '<i class="fas fa-user"></i> ' + validationResult.feedback;
                                    this.style.backgroundColor = validationResult.alignment.isCentered && validationResult.alignment.isProperSize ? 'rgba(255, 193, 7, 0.3)' : 'rgba(220, 53, 69, 0.3)';
                                }
                            } catch (error) {
                                console.error('Face validation error:', error);
                                // Count consecutive errors to provide user option
                                if (typeof this.errorCount === 'undefined') {
                                    this.errorCount = 0;
                                }
                                this.errorCount++;
                                
                                // If multiple errors occur, offer user option
                                if (this.errorCount >= 3) {
                                    const userChoice = confirm('মুখমণ্ডল সনাক্তকরণে পুনরাবৃত্ত ত্রুটি হচ্ছে। সরাসরি ছবি ক্যাপচার করতে চান?');
                                    if (userChoice) {
                                        // Direct capture without face validation
                                        const canvas = document.createElement('canvas');
                                        canvas.width = cameraPreview.videoWidth;
                                        canvas.height = cameraPreview.videoHeight;
                                        
                                        const context = canvas.getContext('2d');
                                        context.drawImage(cameraPreview, 0, 0, canvas.width, canvas.height);
                                        
                                        // Convert to data URL and store in hidden input
                                        const imageData = canvas.toDataURL('image/jpeg', 0.8);
                                        document.getElementById('biometric_data').value = imageData;
                                        
                                        // Stop the camera after successful capture
                                        if (videoStream) {
                                            const tracks = videoStream.getTracks();
                                            tracks.forEach(track => track.stop());
                                            videoStream = null;
                                            cameraPreview.srcObject = null;
                                            cameraPreview.style.display = 'none';
                                            previewPlaceholder.style.display = 'flex';
                                            
                                            this.innerHTML = '<i class="fas fa-check"></i> সফল!';
                                            
                                            // Alert user that face has been captured
                                            alert('মুখমণ্ডল ক্যাপচার করা হয়েছে! এখন রেজিস্টার বাটনে ক্লিক করুন।');
                                        }
                                        
                                        // Remove interval after successful capture
                                        clearInterval(detectInterval);
                                        return;
                                    } else {
                                        this.errorCount = 0; // Reset error counter
                                    }
                                }
                                
                                this.innerHTML = '<i class="fas fa-user"></i> মুখমণ্ডল সামনে নেন';
                                this.style.backgroundColor = 'rgba(220, 53, 69, 0.3)';
                            }
                        };
                        
                        // Start face detection interval
                        const detectInterval = setInterval(detectFaces, 500); // Detect every 500ms
                        
                        // Stop detection after 25 seconds if no face is captured
                        setTimeout(() => {
                            clearInterval(detectInterval);
                            if (videoStream) {
                                const tracks = videoStream.getTracks();
                                tracks.forEach(track => track.stop());
                                videoStream = null;
                                cameraPreview.srcObject = null;
                                cameraPreview.style.display = 'none';
                                previewPlaceholder.style.display = 'flex';
                                
                                this.innerHTML = '<i class="fas fa-camera"></i> স্ক্যান শুরু করুন';
                                this.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
                                
                                const userChoice = confirm('25 সেকেন্ড পরেও মুখমণ্ডল সঠিকভাবে সনাক্ত করা যায়নি। সরাসরি ছবি ক্যাপচার করতে চান? মুখমণ্ডল কেন্দ্রে রেখে ডান-বাম ঠিক করে নিন।');
                                if (userChoice) {
                                    // Direct capture without face validation
                                    const canvas = document.createElement('canvas');
                                    canvas.width = cameraPreview.videoWidth;
                                    canvas.height = cameraPreview.videoHeight;
                                    
                                    const context = canvas.getContext('2d');
                                    context.drawImage(cameraPreview, 0, 0, canvas.width, canvas.height);
                                    
                                    // Convert to data URL and store in hidden input
                                    const imageData = canvas.toDataURL('image/jpeg', 0.8);
                                    document.getElementById('biometric_data').value = imageData;
                                    
                                    // Update button state
                                    this.innerHTML = '<i class="fas fa-check"></i> সফল!';
                                    this.style.backgroundColor = 'rgba(40, 167, 69, 0.3)';
                                    
                                    // Alert user that face has been captured
                                    alert('মুখমণ্ডল ক্যাপচার করা হয়েছে! এখন রেজিস্টার বাটনে ক্লিক করুন।');
                                }
                            }
                        }, 25000);
                    } catch (err) {
                        console.error('Error accessing camera or loading face detection:', err);
                        alert('ক্যামেরা বা মুখমণ্ডল সনাক্তকরণ ব্যবহার করতে অসুবিধা হচ্ছে: ' + err.message);
                        
                        // Stop camera if active
                        if (videoStream) {
                            const tracks = videoStream.getTracks();
                            tracks.forEach(track => track.stop());
                            videoStream = null;
                            cameraPreview.srcObject = null;
                            cameraPreview.style.display = 'none';
                            previewPlaceholder.style.display = 'flex';
                        }
                    }
                });
                
                // Clear selection
                document.getElementById('clear_selection_btn').addEventListener('click', function() {
                    document.querySelectorAll('.user-item').forEach(i => i.classList.remove('selected'));
                    document.getElementById('user_id_input').value = '';
                    document.getElementById('register_btn').disabled = true;
                    
                    // Reset biometric method selection
                    document.querySelectorAll('input[name="method"]').forEach(radio => {
                        radio.checked = false;
                    });
                    
                    document.getElementById('biometric_container').style.display = 'none';
                    document.getElementById('preview_container').style.display = 'none';
                    
                    // Stop camera if active
                    if (videoStream) {
                        const tracks = videoStream.getTracks();
                        tracks.forEach(track => track.stop());
                        videoStream = null;
                        cameraPreview.srcObject = null;
                        cameraPreview.style.display = 'none';
                        previewPlaceholder.style.display = 'flex';
                    }
                    
                    // Clear biometric data
                    document.getElementById('biometric_data').value = '';
                });
                
                // Form submission handler
                document.querySelector('form').addEventListener('submit', function(e) {
                    const method = document.querySelector('input[name="method"]:checked');
                    if (method && method.value === 'face') {
                        const biometricData = document.getElementById('biometric_data').value;
                        if (!biometricData) {
                            e.preventDefault();
                            alert('মুখমণ্ডল রেজিস্টার করতে হলে প্রথমে ক্যামেরা থেকে ছবি ক্যাপচার করুন।');
                            return false;
                        }
                    }
                });
            </script>
        </div> <!-- End main-content -->
    </div> <!-- End sidebar-container -->
</body>
</html>