<?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 teacher's assigned classes if user is a teacher
$teacher_id = null;
$assigned_class_ids = [];
if ($_SESSION['user_role'] == 'teacher') {
    // Get teacher ID
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        
        // Get assigned class IDs
        $stmt = $pdo->prepare("SELECT DISTINCT c.id FROM classes c WHERE (c.class_teacher_id = ? OR c.id IN (SELECT class_id FROM class_subjects WHERE teacher_id = ?)) AND c.status = 'active'");
        $stmt->execute([$teacher_id, $teacher_id]);
        $assigned_classes = $stmt->fetchAll();
        $assigned_class_ids = array_column($assigned_classes, 'id');
    }
}

// Get classes for dropdown
if ($_SESSION['user_role'] == 'teacher' && !empty($assigned_class_ids)) {
    // Teacher: only show assigned classes
    $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
    $stmt = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN ($placeholders) AND status = 'active' ORDER BY name, section");
    $stmt->execute($assigned_class_ids);
    $classes = $stmt->fetchAll();
} else {
    // Admin: show all classes
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
    $classes = $stmt->fetchAll();
}

// Get sessions for dropdown
$stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC");
$sessions = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (empty($sessions)) {
    $currentYear = date('Y');
    for ($i = 0; $i < 5; $i++) {
        $sessions[] = $currentYear - $i;
    }
}

$selected_class = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$selected_session = isset($_GET['session']) ? $_GET['session'] : date('Y');
$selected_group = isset($_GET['group_name']) ? $_GET['group_name'] : '';
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

$students = [];

if ($selected_class > 0 && $selected_session) {
    // Get students in the selected class, session, and group
    if (!empty($selected_group)) {
        // Filter by group
        $stmt = $pdo->prepare(
            "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.photo, s.guardian_phone, s.group_name
            FROM students s 
            WHERE s.class_id = ? AND s.session = ? AND s.group_name = ? AND s.status = 'active'
            ORDER BY s.roll_number
        ");
        $stmt->execute([$selected_class, $selected_session, $selected_group]);
    } else {
        // Don't filter by group
        $stmt = $pdo->prepare(
            "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.photo, s.guardian_phone, s.group_name
            FROM students s 
            WHERE s.class_id = ? AND s.session = ? AND s.status = 'active'
            ORDER BY s.roll_number
        ");
        $stmt->execute([$selected_class, $selected_session]);
    }
    $students = $stmt->fetchAll();
}

$success_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>
        .dashboard-card {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        
        .quick-action-card {
            text-align: center;
            padding: 20px;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .quick-action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        
        .attendance-summary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 0.375rem;
            padding: 15px;
            text-align: center;
        }
        
        .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;
        }
        
        .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-calendar-check 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">
                    <?php if (isset($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; ?>

                    <!-- Quick Actions -->
                    <div class="row mb-4">
                        <div class="col-md-3 col-sm-6 mb-3">
                            <a href="dashboard.php" class="text-decoration-none">
                                <div class="quick-action-card dashboard-card bg-primary text-white">
                                    <i class="fas fa-dashboard fa-2x mb-2"></i>
                                    <h5>ড্যাশবোর্ড</h5>
                                    <p class="mb-0">উপস্থিতি ড্যাশবোর্ড</p>
                                </div>
                            </a>
                        </div>
                        <div class="col-md-3 col-sm-6 mb-3">
                            <a href="photo_registration.php" class="text-decoration-none">
                                <div class="quick-action-card dashboard-card bg-success text-white">
                                    <i class="fas fa-camera fa-2x mb-2"></i>
                                    <h5>ফটো রেজিস্ট্রেশন</h5>
                                    <p class="mb-0">ছাত্রের ছবি স্ক্যান করুন</p>
                                </div>
                            </a>
                        </div>
                        <div class="col-md-3 col-sm-6 mb-3">
                            <a href="messaging_config.php" class="text-decoration-none">
                                <div class="quick-action-card dashboard-card bg-info text-white">
                                    <i class="fas fa-comment-dots fa-2x mb-2"></i>
                                    <h5>মেসেজিং কনফিগ</h5>
                                    <p class="mb-0">মেসেজিং সেটিংস</p>
                                </div>
                            </a>
                        </div>
                        <div class="col-md-3 col-sm-6 mb-3">
                            <a href="config.php" class="text-decoration-none">
                                <div class="quick-action-card dashboard-card bg-warning text-white">
                                    <i class="fas fa-cog fa-2x mb-2"></i>
                                    <h5>কনফিগারেশন</h5>
                                    <p class="mb-0">সিস্টেম কনফিগারেশন</p>
                                </div>
                            </a>
                        </div>
                    </div>

                    <!-- Attendance Summary -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="attendance-summary">
                                <h4><?php echo count($students); ?></h4>
                                <p>মোট ছাত্র</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="attendance-summary">
                                <h4 id="presentCount">0</h4>
                                <p>উপস্থিত</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="attendance-summary">
                                <h4 id="absentCount"><?php echo count($students); ?></h4>
                                <p>অনুপস্থিত</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="attendance-summary">
                                <h4>০%</h4>
                                <p>উপস্থিতি হার</p>
                            </div>
                        </div>
                    </div>

                    <!-- Class, Session, Group and Date Selection -->
                    <form method="GET" class="mb-4">
                        <div class="row">
                            <div class="col-md-2">
                                <label for="class_id" class="form-label">ক্লাস নির্বাচন করুন</label>
                                <select class="form-select" id="class_id" name="class_id" required>
                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                    <?php foreach ($classes as $class): ?>
                                        <option value="<?php echo $class['id']; ?>" 
                                                <?php echo ($selected_class == $class['id']) ? 'selected' : ''; ?>>
                                            <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="session" class="form-label">সেশন</label>
                                <select class="form-select" id="session" name="session" required>
                                    <option value="">সেশন নির্বাচন করুন</option>
                                    <?php foreach ($sessions as $session): ?>
                                        <option value="<?php echo $session; ?>" 
                                                <?php echo ($selected_session == $session) ? 'selected' : ''; ?>>
                                            <?php echo $session; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="group_name" class="form-label">গ্রুপ</label>
                                <select class="form-select" id="group_name" name="group_name">
                                    <option value="">সব গ্রুপ</option>
                                    <?php
                                    // Get distinct groups for the selected class and session
                                    if ($selected_class > 0 && $selected_session) {
                                        $group_stmt = $pdo->prepare("SELECT DISTINCT group_name FROM students WHERE class_id = ? AND session = ? AND group_name IS NOT NULL AND group_name != '' AND status = 'active' ORDER BY group_name");
                                        $group_stmt->execute([$selected_class, $selected_session]);
                                        $groups = $group_stmt->fetchAll(PDO::FETCH_COLUMN);
                                        foreach ($groups as $group): ?>
                                        <option value="<?php echo htmlspecialchars($group); ?>" 
                                                <?php echo (isset($_GET['group_name']) && $_GET['group_name'] == $group) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($group); ?>
                                        </option>
                                    <?php endforeach; } ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <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-2">
                                <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>

                    <!-- Student Photo Registration Section -->
                    <?php if (!empty($students)): ?>
                    <div class="card mb-4">
                        <div class="card-header bg-success text-white">
                            <h5 class="mb-0"><i class="fas fa-user-plus"></i> ছাত্রের ছবি স্ক্যান ও রেজিস্টার করুন</h5>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" id="studentSearch" class="form-control" placeholder="ছাত্র খুঁজুন (নাম, রোল, ছাত্র আইডি বা ক্লাস দিয়ে অনুসন্ধান করুন)...">
                                        <button class="btn btn-outline-secondary" type="button" id="clearSearch">সাফ করুন</button>
                                    </div>
                                </div>
                            </div>
                                            
                            <div class="row">
                                <div class="col-md-6">
                                    <h6>ছাত্র নির্বাচন করুন:</h6>
                                    <div class="row" id="studentList">
                                        <?php foreach ($students as $student): ?>
                                            <div class="col-md-6 col-sm-12 mb-2 student-item-container" data-student-name="<?php echo strtolower($student['first_name'] . ' ' . $student['last_name']); ?>" data-student-roll="<?php echo $student['roll_number']; ?>" data-student-id="<?php echo $student['student_id']; ?>" data-group-name="<?php echo strtolower($student['group_name'] ?? ''); ?>" data-class-name="<?php echo strtolower($selected_class_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 $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 #28a745;">
                                                    <?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']; ?></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>
                                </div>
                                <div class="col-md-6">
                                    <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>
                            
                            <div class="row mt-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 class="mt-3">
                                        <button type="button" id="register_photo_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>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Additional Options -->
                    <div class="row">
                        <div class="col-md-12">
                            <div class="d-flex justify-content-between">
                                <a href="dashboard.php" class="btn btn-primary">
                                    <i class="fas fa-calendar-check"></i> উপস্থিতি নিন
                                </a>
                                <a href="register_biometric.php" class="btn btn-info">
                                    <i class="fas fa-fingerprint"></i> বায়োমেট্রিক রেজিস্ট্রেশন
                                </a>
                                <a href="../attendance/report.php" class="btn btn-secondary">
                                    <i class="fas fa-chart-bar"></i> রিপোর্ট
                                </a>
                            </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>
                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 registerPhotoBtn = document.getElementById('register_photo_btn');
                let selectedStudentId = null;
                
                // 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
                        selectedStudentId = this.getAttribute('data-student-id');
                        
                        // Automatically start the camera when a student is selected
                        if (!videoStream) {
                            startCameraBtn.click();
                        }
                        
                        // Enable register button if photo is available
                        if (photoPreview.style.display !== 'none') {
                            registerPhotoBtn.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', function() {
                    if (videoStream) {
                        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';
                        
                        // Make an AJAX request to register the photo
                        if (selectedStudentId) {
                            // Show loading indicator
                            registerPhotoBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> রেজিস্টার করা হচ্ছে...';
                            registerPhotoBtn.disabled = true;
                            
                            const formData = new FormData();
                            formData.append('student_id', selectedStudentId);
                            formData.append('photo_data', imageData);
                            formData.append('register_photo', '1');
                            
                            fetch('photo_registration.php', {
                                method: 'POST',
                                body: formData,
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest'
                                }
                            })
                            .then(response => {
                                if (response.headers.get('content-type')?.includes('application/json')) {
                                    return response.json();
                                } else {
                                    return response.text();
                                }
                            })
                            .then(result => {
                                if (typeof result === 'object' && result.success) {
                                    // Refresh the page to show updated student list
                                    location.reload();
                                } else {
                                    // Handle as HTML response (non-AJAX)
                                    location.reload();
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                alert('ছবি রেজিস্টার করতে সমস্যা হয়েছে');
                                registerPhotoBtn.innerHTML = '<i class="fas fa-save"></i> ছবি রেজিস্টার করুন';
                                registerPhotoBtn.disabled = false;
                            });
                        }
                    }
                });
                
                // Register photo
                registerPhotoBtn.addEventListener('click', function() {
                    if (!selectedStudentId) {
                        alert('প্রথমে একজন ছাত্র নির্বাচন করুন');
                        return;
                    }
                    
                    if (!photoPreview.src || photoPreview.style.display === 'none') {
                        alert('প্রথমে একটি ছবি তুলুন');
                        return;
                    }
                    
                    // Create form and submit
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = 'photo_registration.php';
                    
                    const studentIdInput = document.createElement('input');
                    studentIdInput.type = 'hidden';
                    studentIdInput.name = 'student_id';
                    studentIdInput.value = selectedStudentId;
                    form.appendChild(studentIdInput);
                    
                    const photoDataInput = document.createElement('input');
                    photoDataInput.type = 'hidden';
                    photoDataInput.name = 'photo_data';
                    photoDataInput.value = photoPreview.src;
                    form.appendChild(photoDataInput);
                    
                    const registerInput = document.createElement('input');
                    registerInput.type = 'hidden';
                    registerInput.name = 'register_photo';
                    registerInput.value = '1';
                    form.appendChild(registerInput);
                    
                    // Add a callback to refresh the student list after successful registration
                    form.addEventListener('submit', function() {
                        // Store the current selected student ID to re-select after page reload
                        sessionStorage.setItem('selectedStudentId', selectedStudentId);
                    });
                    
                    document.body.appendChild(form);
                    form.submit();
                });
                
                // Clear selection
                document.getElementById('clear_selection_btn').addEventListener('click', function() {
                    document.querySelectorAll('.student-item').forEach(i => i.classList.remove('selected'));
                    selectedStudentId = null;
                    photoPreview.style.display = 'none';
                    previewPlaceholder.style.display = 'flex';
                    registerPhotoBtn.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;
                    }
                });
                
                // Update attendance counts
                function updateAttendanceCounts() {
                    const presentCount = document.querySelectorAll('input[name*="[status]"]:checked[value="present"]').length;
                    const totalCount = document.querySelectorAll('input[name*="[status]"]').length;
                    const absentCount = totalCount - presentCount;
                    
                    document.getElementById('presentCount').textContent = presentCount;
                    document.getElementById('absentCount').textContent = absentCount;
                }
            </script>
            <script>
                // Student search functionality
                document.getElementById('studentSearch').addEventListener('input', function() {
                    const searchTerm = this.value.toLowerCase().trim();
                    
                    const studentContainers = document.querySelectorAll('.student-item-container');
                    
                    if (searchTerm === '') {
                        // Show all students if search is empty
                        studentContainers.forEach(container => {
                            container.style.display = 'block';
                        });
                    } else {
                        // Filter students based on search term
                        studentContainers.forEach(container => {
                            const studentName = container.getAttribute('data-student-name') || '';
                            const studentRoll = container.getAttribute('data-student-roll') || '';
                            const studentId = container.getAttribute('data-student-id') || '';
                            const groupName = container.getAttribute('data-group-name') || '';
                            
                            // Check if search term matches any of the fields
                            if (
                                studentName.includes(searchTerm) ||
                                studentRoll.includes(searchTerm) ||
                                studentId.includes(searchTerm) ||
                                groupName.includes(searchTerm)
                            ) {
                                container.style.display = 'block';
                            } else {
                                container.style.display = 'none';
                            }
                        });
                    }
                });
                
                // Clear search functionality
                document.getElementById('clearSearch').addEventListener('click', function() {
                    document.getElementById('studentSearch').value = '';
                    
                    // Show all students
                    const studentContainers = document.querySelectorAll('.student-item-container');
                    studentContainers.forEach(container => {
                        container.style.display = 'block';
                    });
                });
            </script>
        </div> <!-- End main-content -->
    </div> <!-- End sidebar-container -->
</body>
</html>