<?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 for registration with class, session, and group info
$stmt = $pdo->query("
    SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.photo, 
           s.class_id, s.session, s.group_name, c.name as class_name
    FROM students s
    LEFT JOIN classes c ON s.class_id = c.id
    WHERE s.status = 'active' 
    ORDER BY c.name, s.roll_number
");
$students = $stmt->fetchAll();

// Get unique sessions
$sessions = array_unique(array_column($students, 'session'));
$sessions = array_filter($sessions);
sort($sessions);

// Get unique classes
$classes = [];
$class_stmt = $pdo->query("SELECT id, name FROM classes WHERE status = 'active' ORDER BY name");
$classes = $class_stmt->fetchAll();

// Get unique groups
$groups = array_unique(array_column($students, 'group_name'));
$groups = array_filter($groups);
sort($groups);

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

// Handle photo registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_photo'])) {
    $student_id = (int)$_POST['student_id'];
    $photo_data = $_POST['photo_data'] ?? '';
    
    // Validate inputs
    if (empty($student_id) || empty($photo_data)) {
        $error_message = 'ছাত্র এবং ছবি প্রয়োজন';
        
        // If this is an AJAX request, return JSON response
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => $error_message]);
            exit();
        }
    } else {
        // Extract image data from base64
        $image_parts = explode(";base64,", $photo_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)) {
            $error_message = 'শুধুমাত্র JPEG এবং PNG ছবি অনুমোদিত';
        } else {
            // Create upload directory if it doesn't exist
            $upload_dir = '../uploads/students/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            // Generate unique filename
            $filename = 'student_' . $student_id . '_' . time() . '.' . $image_type;
            $filepath = $upload_dir . $filename;

            // Save image to file
            if (file_put_contents($filepath, $image_base64)) {
                // Update student record with photo path
                $stmt = $pdo->prepare("UPDATE students SET photo = ? WHERE id = ?");
                // Store relative path without '../'
                if ($stmt->execute([substr($filepath, 3), $student_id])) {
                    $success_message = 'ছবি সফলভাবে রেজিস্টার করা হয়েছে!';
                    
                    // If this is an AJAX request, return JSON response
                    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                        header('Content-Type: application/json');
                        echo json_encode(['success' => true, 'message' => $success_message]);
                        exit();
                    }
                } else {
                    $error_message = 'ছবি রেজিস্টার করতে সমস্যা হয়েছে';
                    
                    // If this is an AJAX request, return JSON response
                    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                        header('Content-Type: application/json');
                        echo json_encode(['success' => false, 'message' => $error_message]);
                        exit();
                    }
                }
            } else {
                $error_message = 'ছবি সংরক্ষণ করতে সমস্যা হয়েছে';
                
                // If this is an AJAX request, return JSON response
                if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => $error_message]);
                    exit();
                }
            }
        }
    }
}

// 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);
        }
        
        .student-item {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .student-item:hover {
            background-color: #f8f9fa;
            transform: translateY(-2px);
            box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
        }
        
        .student-item.selected {
            background-color: #e7f5ff;
            border-color: #339af0;
        }
        
        #student_search {
            border-radius: 0;
        }
        
        #student_search:focus {
            border-color: #339af0;
            box-shadow: 0 0 0 0.2rem rgba(51, 154, 240, 0.25);
        }
        
        .input-group .btn-outline-secondary {
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
        }
        
        .no-results {
            text-align: center;
            padding: 30px;
            color: #6c757d;
        }
        
        .no-results i {
            font-size: 48px;
            margin-bottom: 10px;
            color: #dee2e6;
        }
        
        .camera-container {
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
            border: 2px solid #dee2e6;
            border-radius: 0.375rem;
            overflow: hidden;
            margin-top: 20px;
        }
        
        .camera-feed {
            width: 100%;
            height: 300px;
            background-color: #000;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2em;
        }
        
        .preview-container {
            width: 100%;
            height: 300px;
            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;
        }
        
        .controls {
            margin-top: 15px;
            text-align: center;
        }
    </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-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-camera"></i> ছবি রেজিস্ট্রেশন</h5>
                                </div>
                                <div class="card-body">
                                    <?php if (!empty($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>
                                        <script>
                                            // Auto-redirect after 2 seconds to give user feedback
                                            setTimeout(function() {
                                                window.location.href = 'index.php';
                                            }, 2000);
                                        </script>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($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="student_id" id="student_id_input" value="">
                                        <input type="hidden" name="photo_data" id="photo_data" value="">
                                        
                                        <!-- Student Selection -->
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <h6>ছাত্র নির্বাচন করুন:</h6>
                                                
                                                <!-- Filter Section -->
                                                <div class="mb-3">
                                                    <div class="row g-2 mb-2">
                                                        <div class="col-md-3">
                                                            <select id="filter_session" class="form-select">
                                                                <option value="">সব সেশন</option>
                                                                <?php foreach ($sessions as $session): ?>
                                                                    <option value="<?php echo htmlspecialchars($session); ?>"><?php echo htmlspecialchars($session); ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <select id="filter_class" class="form-select">
                                                                <option value="">সব ক্লাস</option>
                                                                <?php foreach ($classes as $class): ?>
                                                                    <option value="<?php echo $class['id']; ?>"><?php echo htmlspecialchars($class['name']); ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <select id="filter_group" class="form-select">
                                                                <option value="">সব গ্রুপ</option>
                                                                <?php foreach ($groups as $group): ?>
                                                                    <option value="<?php echo htmlspecialchars($group); ?>"><?php echo htmlspecialchars($group); ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-3">
                                                            <button type="button" id="reset_filters" class="btn btn-outline-secondary w-100">
                                                                <i class="fas fa-undo"></i> রিসেট
                                                            </button>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Search Box -->
                                                    <div class="input-group">
                                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                                        <input type="text" id="student_search" class="form-control" placeholder="নাম বা রোল নম্বর দিয়ে খুঁজুন...">
                                                        <button type="button" id="clear_search" class="btn btn-outline-secondary" style="display: none;">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    </div>
                                                    <small class="text-muted mt-2 d-block">মোট ছাত্র: <span id="total_students"><?php echo count($students); ?></span> | দেখানো হচ্ছে: <span id="showing_students"><?php echo count($students); ?></span></small>
                                                </div>
                                                
                                                <div class="row" id="students_container">
                                                    <?php foreach ($students as $student): ?>
                                                        <div class="col-md-3 col-sm-6 mb-2 student-card" 
                                                             data-student-name="<?php echo strtolower($student['first_name'] . ' ' . $student['last_name']); ?>" 
                                                             data-roll-number="<?php echo $student['roll_number']; ?>"
                                                             data-session="<?php echo htmlspecialchars($student['session'] ?? ''); ?>"
                                                             data-class-id="<?php echo $student['class_id']; ?>"
                                                             data-group="<?php echo htmlspecialchars($student['group_name'] ?? ''); ?>">
                                                            <div class="student-item" data-student-id="<?php echo $student['id']; ?>">
                                                                <?php if ($student['photo'] && file_exists(__DIR__ . '/../' . ltrim($student['photo'], '/'))): ?>
                                                                    <img src="../<?php echo ltrim($student['photo'], '/'); ?>"
                                                                         alt="<?php echo $student['first_name']; ?>" 
                                                                         class="rounded-circle" style="width: 60px; height: 60px; object-fit: cover; float: left; margin-right: 10px; border: 2px solid #007bff;">
                                                                <?php else: ?>
                                                                    <div class="bg-secondary rounded-circle d-inline-block" 
                                                                         style="width: 60px; height: 60px; float: left; margin-right: 10px; display: flex; align-items: center; justify-content: center;">
                                                                        <i class="fas fa-user text-white" style="font-size: 24px;"></i>
                                                                    </div>
                                                                <?php endif; ?>
                                                                <div style="overflow: hidden;">
                                                                    <strong><?php echo $student['first_name'] . ' ' . $student['last_name']; ?></strong><br>
                                                                    <small class="text-muted">
                                                                        রোল: <?php echo $student['roll_number']; ?> | 
                                                                        <?php echo htmlspecialchars($student['class_name'] ?? 'N/A'); ?>
                                                                        <?php if ($student['group_name']): ?> | <?php echo htmlspecialchars($student['group_name']); ?><?php endif; ?>
                                                                    </small>
                                                                    <?php if ($student['photo']): ?>
                                                                        <br><small class="text-success"><i class="fas fa-check-circle"></i> ছবি রেজিস্টার্ড</small>
                                                                    <?php else: ?>
                                                                        <br><small class="text-muted"><i class="fas fa-times-circle"></i> ছবি মিসিং</small>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                
                                                <!-- No Results Message -->
                                                <div id="no_results" class="no-results" style="display: none;">
                                                    <i class="fas fa-search"></i>
                                                    <h5>কোনো ছাত্র পাওয়া যায়নি</h5>
                                                    <p>অনুগ্রহ করে অন্য নাম বা রোল নম্বর দিয়ে খুঁজুন</p>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Camera Section -->
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <h6>ক্যামেরা ব্যবহার করে ছবি তুলুন:</h6>
                                                <div class="camera-container">
                                                    <div class="camera-feed" id="camera_placeholder">
                                                        <i class="fas fa-camera fa-3x mb-2"></i>
                                                        <p>ক্যামেরা ফিড এখানে দেখানো হবে</p>
                                                    </div>
                                                    <video id="camera_feed" autoplay playsinline style="display: none; width: 100%; height: 300px;"></video>
                                                </div>
                                                
                                                <div class="controls">
                                                    <button type="button" id="start_camera" class="btn btn-primary me-2">
                                                        <i class="fas fa-video"></i> ক্যামেরা শুরু করুন
                                                    </button>
                                                    <button type="button" id="capture_photo" class="btn btn-success me-2" disabled>
                                                        <i class="fas fa-camera"></i> ছবি তুলুন
                                                    </button>
                                                    <button type="button" id="stop_camera" class="btn btn-secondary" disabled>
                                                        <i class="fas fa-stop"></i> ক্যামেরা বন্ধ করুন
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Preview Section -->
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <h6>ছবি প্রিভিউ:</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>
                                        </div>
                                        
                                        <!-- Action Buttons -->
                                        <div class="row">
                                            <div class="col-md-12">
                                                <button type="submit" name="register_photo" 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>
                let videoStream = null;
                const cameraFeed = document.getElementById('camera_feed');
                const cameraPlaceholder = document.getElementById('camera_placeholder');
                const photoPreview = document.getElementById('photo_preview');
                const previewPlaceholder = document.getElementById('preview_placeholder');
                const startCameraBtn = document.getElementById('start_camera');
                const captureBtn = document.getElementById('capture_photo');
                const stopCameraBtn = document.getElementById('stop_camera');
                const registerBtn = document.getElementById('register_btn');
                const photoDataInput = document.getElementById('photo_data');
                
                // Student selection handling
                document.querySelectorAll('.student-item').forEach(item => {
                    item.addEventListener('click', function() {
                        // Remove selected class from all items
                        document.querySelectorAll('.student-item').forEach(i => i.classList.remove('selected'));
                        
                        // Add selected class to clicked item
                        this.classList.add('selected');
                        
                        // Set the student ID in the form
                        const studentId = this.getAttribute('data-student-id');
                        document.getElementById('student_id_input').value = studentId;
                        
                        // Automatically start the camera when a student is selected
                        if (!videoStream) {
                            startCameraBtn.click();
                        }
                        
                        // Enable the register button if photo is available
                        if (photoPreview.style.display !== 'none') {
                            registerBtn.disabled = false;
                        }
                    });
                });
                
                // Start camera
                startCameraBtn.addEventListener('click', async function() {
                    try {
                        const stream = await navigator.mediaDevices.getUserMedia({ 
                            video: { facingMode: 'user' } 
                        });
                        
                        videoStream = stream;
                        cameraFeed.srcObject = stream;
                        cameraFeed.style.display = 'block';
                        cameraPlaceholder.style.display = 'none';
                        
                        captureBtn.disabled = false;
                        stopCameraBtn.disabled = false;
                        startCameraBtn.disabled = true;
                    } catch (err) {
                        console.error('Error accessing camera:', err);
                        alert('ক্যামেরা ব্যবহার করতে অসুবিধা হচ্ছে: ' + err.message);
                    }
                });
                
                // Stop camera
                stopCameraBtn.addEventListener('click', function() {
                    if (videoStream) {
                        const tracks = videoStream.getTracks();
                        tracks.forEach(track => track.stop());
                        videoStream = null;
                        cameraFeed.srcObject = null;
                        cameraFeed.style.display = 'none';
                        cameraPlaceholder.style.display = 'flex';
                        
                        captureBtn.disabled = true;
                        stopCameraBtn.disabled = true;
                        startCameraBtn.disabled = false;
                    }
                });
                
                // Capture photo
                captureBtn.addEventListener('click', async function() {
                    if (videoStream) {
                        try {
                            // Load face-api.js if not already loaded
                            await loadFaceApi();
                            
                            // Initialize face detection models
                            await initializeFaceModels();
                            
                            // Validate face alignment before capturing
                            const validationResult = await validateFaceAlignment(cameraFeed);
                            
                            if (!validationResult.isValid && validationResult.detectionCount > 0) {
                                alert(validationResult.feedback + ' মুখমণ্ডল কেন্দ্রে রেখে ডান-বাম ঠিক করে নিন।');
                                return;
                            }
                            
                            // All checks passed, prepare to capture the photo
                            // Wait 1.5 seconds to allow user to ensure proper positioning
                            setTimeout(() => {
                                const canvas = document.createElement('canvas');
                                canvas.width = cameraFeed.videoWidth;
                                canvas.height = cameraFeed.videoHeight;
                                
                                const context = canvas.getContext('2d');
                                context.drawImage(cameraFeed, 0, 0, canvas.width, canvas.height);
                                
                                // Convert to data URL
                                const imageData = canvas.toDataURL('image/jpeg');
                                
                                // Show preview
                                photoPreview.src = imageData;
                                photoPreview.style.display = 'block';
                                previewPlaceholder.style.display = 'none';
                                
                                // Store in hidden input
                                photoDataInput.value = imageData;
                                
                                // Enable register button
                                registerBtn.disabled = false;
                                
                                // Get student ID
                                const studentId = document.getElementById('student_id_input').value;
                                
                                // Automatically submit the form to register the photo if student is selected
                                if (studentId) {
                                    // Create a temporary form to submit the data
                                    const form = document.createElement('form');
                                    form.method = 'POST';
                                    form.action = '';
                                    
                                    const studentIdInput = document.createElement('input');
                                    studentIdInput.type = 'hidden';
                                    studentIdInput.name = 'student_id';
                                    studentIdInput.value = studentId;
                                    form.appendChild(studentIdInput);
                                    
                                    const photoDataInput = document.createElement('input');
                                    photoDataInput.type = 'hidden';
                                    photoDataInput.name = 'photo_data';
                                    photoDataInput.value = imageData;
                                    form.appendChild(photoDataInput);
                                    
                                    const registerInput = document.createElement('input');
                                    registerInput.type = 'hidden';
                                    registerInput.name = 'register_photo';
                                    registerInput.value = '1';
                                    form.appendChild(registerInput);
                                    
                                    document.body.appendChild(form);
                                    form.submit();
                                }
                            }, 1500); // Wait 1.5 seconds before capture
                        } catch (err) {
                            console.error('Error detecting face:', err);
                            
                            // Fallback to original capture without face validation
                            setTimeout(() => {
                                // Fallback to original capture without face validation
                                const canvas = document.createElement('canvas');
                                canvas.width = cameraFeed.videoWidth;
                                canvas.height = cameraFeed.videoHeight;
                                const context = canvas.getContext('2d');
                                context.drawImage(cameraFeed, 0, 0, canvas.width, canvas.height);
                                
                                // Convert to data URL
                                const imageData = canvas.toDataURL('image/jpeg');
                                
                                // Show preview
                                photoPreview.src = imageData;
                                photoPreview.style.display = 'block';
                                previewPlaceholder.style.display = 'none';
                                
                                // Store in hidden input
                                photoDataInput.value = imageData;
                                
                                // Enable register button
                                registerBtn.disabled = false;
                                
                                // Get student ID
                                const studentId = document.getElementById('student_id_input').value;
                                
                                // Automatically submit the form to register the photo if student is selected
                                if (studentId) {
                                    // Create a temporary form to submit the data
                                    const form = document.createElement('form');
                                    form.method = 'POST';
                                    form.action = '';
                                    
                                    const studentIdInput = document.createElement('input');
                                    studentIdInput.type = 'hidden';
                                    studentIdInput.name = 'student_id';
                                    studentIdInput.value = studentId;
                                    form.appendChild(studentIdInput);
                                    
                                    const photoDataInput = document.createElement('input');
                                    photoDataInput.type = 'hidden';
                                    photoDataInput.name = 'photo_data';
                                    photoDataInput.value = imageData;
                                    form.appendChild(photoDataInput);
                                    
                                    const registerInput = document.createElement('input');
                                    registerInput.type = 'hidden';
                                    registerInput.name = 'register_photo';
                                    registerInput.value = '1';
                                    form.appendChild(registerInput);
                                    
                                    document.body.appendChild(form);
                                    form.submit();
                                }
                            }, 1000); // Slight delay to allow UI to update
                        }
                    }
                });
                
                // Clear selection
                document.getElementById('clear_selection_btn').addEventListener('click', function() {
                    document.querySelectorAll('.student-item').forEach(i => i.classList.remove('selected'));
                    document.getElementById('student_id_input').value = '';
                    photoDataInput.value = '';
                    photoPreview.style.display = 'none';
                    previewPlaceholder.style.display = 'flex';
                    registerBtn.disabled = true;
                    
                    // Stop camera if active
                    if (videoStream) {
                        const tracks = videoStream.getTracks();
                        tracks.forEach(track => track.stop());
                        videoStream = null;
                        cameraFeed.srcObject = null;
                        cameraFeed.style.display = 'none';
                        cameraPlaceholder.style.display = 'flex';
                        
                        captureBtn.disabled = true;
                        stopCameraBtn.disabled = true;
                        startCameraBtn.disabled = false;
                    }
                });
                
                // When student is selected, enable register if photo exists
                document.querySelectorAll('.student-item').forEach(item => {
                    item.addEventListener('click', function() {
                        if (photoPreview.style.display !== 'none') {
                            registerBtn.disabled = false;
                        }
                    });
                });
                
                // Filter and Search Functionality
                const filterSession = document.getElementById('filter_session');
                const filterClass = document.getElementById('filter_class');
                const filterGroup = document.getElementById('filter_group');
                const resetFilters = document.getElementById('reset_filters');
                const searchInput = document.getElementById('student_search');
                const clearSearchBtn = document.getElementById('clear_search');
                const studentCards = document.querySelectorAll('.student-card');
                const totalStudentsSpan = document.getElementById('total_students');
                const showingStudentsSpan = document.getElementById('showing_students');
                const noResultsDiv = document.getElementById('no_results');
                const totalCount = studentCards.length;
                
                function applyFilters() {
                    const selectedSession = filterSession.value;
                    const selectedClass = filterClass.value;
                    const selectedGroup = filterGroup.value;
                    const searchTerm = searchInput.value.toLowerCase().trim();
                    let visibleCount = 0;
                    
                    // Show/hide clear search button
                    clearSearchBtn.style.display = searchTerm ? 'block' : 'none';
                    
                    studentCards.forEach(card => {
                        const cardSession = card.getAttribute('data-session');
                        const cardClass = card.getAttribute('data-class-id');
                        const cardGroup = card.getAttribute('data-group');
                        const studentName = card.getAttribute('data-student-name');
                        const rollNumber = card.getAttribute('data-roll-number');
                        
                        const matchSession = !selectedSession || cardSession === selectedSession;
                        const matchClass = !selectedClass || cardClass === selectedClass;
                        const matchGroup = !selectedGroup || cardGroup === selectedGroup;
                        const matchSearch = !searchTerm || studentName.includes(searchTerm) || rollNumber.includes(searchTerm);
                        
                        if (matchSession && matchClass && matchGroup && matchSearch) {
                            card.style.display = 'block';
                            visibleCount++;
                        } else {
                            card.style.display = 'none';
                        }
                    });
                    
                    showingStudentsSpan.textContent = visibleCount;
                    
                    // Show/hide no results message
                    if (visibleCount === 0) {
                        noResultsDiv.style.display = 'block';
                    } else {
                        noResultsDiv.style.display = 'none';
                    }
                }
                
                // Event listeners for filters
                filterSession.addEventListener('change', applyFilters);
                filterClass.addEventListener('change', applyFilters);
                filterGroup.addEventListener('change', applyFilters);
                
                // Event listener for search
                searchInput.addEventListener('input', applyFilters);
                
                // Clear search button
                clearSearchBtn.addEventListener('click', function() {
                    searchInput.value = '';
                    applyFilters();
                    searchInput.focus();
                });
                
                // Enter key to select first visible student
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        const firstVisible = document.querySelector('.student-card[style="display: block;"]');
                        if (firstVisible) {
                            firstVisible.querySelector('.student-item').click();
                        }
                    }
                });
                
                // Reset all filters and search
                resetFilters.addEventListener('click', function() {
                    filterSession.value = '';
                    filterClass.value = '';
                    filterGroup.value = '';
                    searchInput.value = '';
                    applyFilters();
                });
            </script>
        </div> <!-- End main-content -->
    </div> <!-- End sidebar-container -->
</body>
</html>