<?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_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

$students = [];
$teachers = [];

if ($selected_class > 0 && $selected_session) {
    // Get students in the selected class and session
    $stmt = $pdo->prepare("
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.photo
        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();
}

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

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

// Function to send auto message when attendance is marked
function sendAutoMessage($pdo, $student_id, $date) {
    try {
        // Get messaging configuration
        $config_stmt = $pdo->query("SELECT setting_key, setting_value FROM attendance_settings WHERE setting_key IN ('auto_message_enabled', 'message_template', 'sms_gateway', 'send_to_guardian', 'send_to_student', 'send_time_delay')");
        $config = $config_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        // Check if auto messaging is enabled
        if (!isset($config['auto_message_enabled']) || $config['auto_message_enabled'] !== '1') {
            return false;
        }
        
        // Get student details
        $stmt = $pdo->prepare("SELECT s.first_name, s.last_name, s.roll_number, c.name as class_name, s.guardian_phone, s.phone FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
        $stmt->execute([$student_id]);
        $student = $stmt->fetch();
        
        if (!$student) {
            return false;
        }
        
        // Prepare message
        $message_template = $config['message_template'] ?? 'আপনার সন্তান {student_name} এর উপস্থিতি সফলভাবে রেকর্ড করা হয়েছে। তারিখ: {date}';
        $message = $message_template;
        $message = str_replace('{student_name}', $student['first_name'] . ' ' . $student['last_name'], $message);
        $message = str_replace('{date}', date('d/m/Y', strtotime($date)), $message);
        $message = str_replace('{class}', $student['class_name'], $message);
        $message = str_replace('{roll_number}', $student['roll_number'], $message);
        
        // Send message to guardian if configured
        if (isset($config['send_to_guardian']) && $config['send_to_guardian'] === '1' && !empty($student['guardian_phone'])) {
            // In a real implementation, this would send an SMS through the selected gateway
            // For demo purposes, we'll just log the message
            error_log("Auto Message to Guardian ({$student['guardian_phone']}): $message");
        }
        
        // Send message to student if configured and phone number exists
        if (isset($config['send_to_student']) && $config['send_to_student'] === '1' && !empty($student['phone'])) {
            error_log("Auto Message to Student ({$student['phone']}): $message");
        }
        
        return true;
    } catch (Exception $e) {
        error_log("Error sending auto message: " . $e->getMessage());
        return false;
    }
}

// Handle form submission for manual attendance marking
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_attendance'])) {
    $class_id = (int)$_POST['class_id'];
    $session = $_POST['session'];
    $date = $_POST['date'];
    $attendance_data = $_POST['attendance'] ?? [];
    
    if (empty($attendance_data)) {
        $error_message = 'কোন উপস্থিতি তথ্য পাওয়া যায়নি';
    } else {
        try {
            $pdo->beginTransaction();
            
            // Delete existing attendance for this class and date
            $stmt = $pdo->prepare("DELETE FROM attendance WHERE class_id = ? AND date = ?");
            $stmt->execute([$class_id, $date]);
            
            // Insert new attendance records
            $stmt = $pdo->prepare("
                INSERT INTO attendance (student_id, class_id, date, status, remarks, marked_by) 
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            
            foreach ($attendance_data as $student_id => $data) {
                $status = $data['status'];
                $remarks = trim($data['remarks'] ?? '');
                
                $stmt->execute([$student_id, $class_id, $date, $status, $remarks, $_SESSION['user_id']]);
                
                // Send auto message if status is present
                if ($status === 'present') {
                    sendAutoMessage($pdo, $student_id, $date);
                }
            }
            
            $pdo->commit();
            $success_message = 'উপস্থিতি সফলভাবে সংরক্ষণ করা হয়েছে';
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'উপস্থিতি সংরক্ষণে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}

// 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>
        .attendance-card {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        
        .attendance-method {
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .attendance-method:hover {
            transform: translateY(-3px);
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        
        .camera-container {
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
            border: 2px solid #dee2e6;
            border-radius: 0.375rem;
            overflow: hidden;
        }
        
        .camera-feed {
            width: 100%;
            height: 300px;
            background-color: #000;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2em;
        }
        
        .fingerprint-scanner {
            width: 100%;
            height: 300px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: white;
            border-radius: 0.375rem;
        }
        
        .fingerprint-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;
        }
        
        .scan-button:hover {
            background-color: rgba(255, 255, 255, 0.3);
        }
        
        .attendance-summary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 0.375rem;
            padding: 15px;
            text-align: center;
        }
        
        .config-section {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 20px;
        }
        
        .biometric-status {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 5px;
        }
        
        .status-active {
            background-color: #28a745;
        }
        
        .status-inactive {
            background-color: #dc3545;
        }
    </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">
        <div class="row">
            <div class="col-md-12">
                <div class="card attendance-card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-dashboard"></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; ?>

                        <!-- Configuration Section -->
                        <div class="config-section mb-4">
                            <h5><i class="fas fa-cog"></i> কনফিগারেশন</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">ক্যামেরা স্ক্যানিং</label>
                                        <div>
                                            <span class="biometric-status status-active"></span>
                                            <span>সক্রিয়</span>
                                            <div class="form-check form-switch d-inline-block ms-3">
                                                <input class="form-check-input" type="checkbox" id="cameraToggle" checked>
                                                <label class="form-check-label" for="cameraToggle">সক্ষম করুন</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">ফিংগারপ্রিন্ট স্ক্যানিং</label>
                                        <div>
                                            <span class="biometric-status status-active"></span>
                                            <span>সক্রিয়</span>
                                            <div class="form-check form-switch d-inline-block ms-3">
                                                <input class="form-check-input" type="checkbox" id="fingerprintToggle" checked>
                                                <label class="form-check-label" for="fingerprintToggle">সক্ষম করুন</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Class, Session and Date Selection -->
                        <form method="GET" class="mb-4">
                            <div class="row">
                                <div class="col-md-4">
                                    <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-3">
                                    <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-3">
                                    <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>

                        <!-- Attendance Methods -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="attendance-method card h-100">
                                    <div class="card-body text-center">
                                        <div class="camera-container">
                                            <div class="camera-feed">
                                                <video id="cameraFeed" autoplay playsinline style="display: none;"></video>
                                                <canvas id="cameraCanvas" style="display: none;"></canvas>
                                                <div id="cameraPlaceholder">
                                                    <i class="fas fa-camera fa-3x mb-2"></i>
                                                    <p>ক্যামেরা ফিড</p>
                                                </div>
                                            </div>
                                        </div>
                                        <h5 class="mt-3"><i class="fas fa-camera"></i> ক্যামেরা স্ক্যানিং</h5>
                                        <p class="text-muted">ছাত্র/শিক্ষকের ছবি ধরে উপস্থিতি নিন</p>
                                        <button id="startCameraBtn" class="btn btn-success mt-2">
                                            <i class="fas fa-play"></i> ক্যামেরা শুরু করুন
                                        </button>
                                        <button id="captureBtn" class="btn btn-primary mt-2" disabled>
                                            <i class="fas fa-camera"></i> ছবি তুলুন
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="attendance-method card h-100">
                                    <div class="card-body text-center">
                                        <div class="fingerprint-scanner">
                                            <i class="fas fa-fingerprint fingerprint-icon"></i>
                                            <h5>ফিংগারপ্রিন্ট স্ক্যানার</h5>
                                            <p>আপনার আঙুল স্ক্যান করুন</p>
                                            <div class="scan-button" id="scanFingerBtn">
                                                <i class="fas fa-hand-pointer"></i> স্ক্যান শুরু করুন
                                            </div>
                                        </div>
                                        <h5 class="mt-3"><i class="fas fa-fingerprint"></i> ফিংগারপ্রিন্ট স্ক্যানিং</h5>
                                        <p class="text-muted">ছাত্র/শিক্ষকের ফিংগারপ্রিন্ট ধরে উপস্থিতি নিন</p>
                                    </div>
                                </div>
                            </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><?php echo count($teachers); ?></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>

                        <!-- Quick Actions -->
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <div class="d-flex justify-content-between">
                                    <button id="markAllPresentBtn" class="btn btn-success">
                                        <i class="fas fa-check-double"></i> সবাইকে উপস্থিত
                                    </button>
                                    <button id="markAllAbsentBtn" class="btn btn-danger">
                                        <i class="fas fa-times"></i> সবাইকে অনুপস্থিত
                                    </button>
                                    <button id="saveAttendanceBtn" class="btn btn-primary">
                                        <i class="fas fa-save"></i> উপস্থিতি সংরক্ষণ করুন
                                    </button>
                                    <a href="../attendance/report.php" class="btn btn-secondary">
                                        <i class="fas fa-chart-bar"></i> রিপোর্ট দেখুন
                                    </a>
                                </div>
                            </div>
                        </div>

                        <!-- Manual Attendance Entry (Fallback) -->
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-edit"></i> ম্যানুয়াল উপস্থিতি নিন</h5>
                            </div>
                            <div class="card-body">
                                <form method="POST" action="">
                                    <input type="hidden" name="class_id" value="<?php echo $selected_class; ?>">
                                    <input type="hidden" name="session" value="<?php echo $selected_session; ?>">
                                    <input type="hidden" name="date" value="<?php echo $selected_date; ?>">
                                    
                                    <div class="table-responsive">
                                        <table class="table table-striped">
                                            <thead>
                                                <tr>
                                                    <th>ছবি</th>
                                                    <th>রোল</th>
                                                    <th>নাম</th>
                                                    <th>উপস্থিতি</th>
                                                    <th>মন্তব্য</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($students as $student): ?>
                                                    <tr>
                                                        <td>
                                                            <?php if ($student['photo'] && file_exists(__DIR__ . '/../' . ltrim($student['photo'], '/'))): ?>
                                                                <img src="../<?php echo $student['photo']; ?>"
                                                                     alt="<?php echo $student['first_name']; ?>" 
                                                                     class="profile-img-small" style="width: 40px; height: 40px;">
                                                            <?php else: ?>
                                                                <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" 
                                                                     style="width: 40px; height: 40px;">
                                                                    <i class="fas fa-user text-white"></i>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-info"><?php echo $student['roll_number']; ?></span>
                                                        </td>
                                                        <td>
                                                            <strong><?php echo $student['first_name'] . ' ' . $student['last_name']; ?></strong>
                                                            <br><small class="text-muted"><?php echo $student['student_id']; ?></small>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group" role="group">
                                                                <input type="radio" class="btn-check" 
                                                                       name="attendance[<?php echo $student['id']; ?>][status]" 
                                                                       value="present" 
                                                                       id="present_<?php echo $student['id']; ?>_manual">
                                                                <label class="btn btn-outline-success btn-sm" 
                                                                       for="present_<?php echo $student['id']; ?>_manual">
                                                                    <i class="fas fa-check"></i> উপস্থিত
                                                                </label>

                                                                <input type="radio" class="btn-check" 
                                                                       name="attendance[<?php echo $student['id']; ?>][status]" 
                                                                       value="absent" 
                                                                       id="absent_<?php echo $student['id']; ?>_manual" checked>
                                                                <label class="btn btn-outline-danger btn-sm" 
                                                                       for="absent_<?php echo $student['id']; ?>_manual">
                                                                    <i class="fas fa-times"></i> অনুপস্থিত
                                                                </label>

                                                                <input type="radio" class="btn-check" 
                                                                       name="attendance[<?php echo $student['id']; ?>][status]" 
                                                                       value="late" 
                                                                       id="late_<?php echo $student['id']; ?>_manual">
                                                                <label class="btn btn-outline-warning btn-sm" 
                                                                       for="late_<?php echo $student['id']; ?>_manual">
                                                                    <i class="fas fa-clock"></i> দেরি
                                                                </label>

                                                                <input type="radio" class="btn-check" 
                                                                       name="attendance[<?php echo $student['id']; ?>][status]" 
                                                                       value="excused" 
                                                                       id="excused_<?php echo $student['id']; ?>_manual">
                                                                <label class="btn btn-outline-info btn-sm" 
                                                                       for="excused_<?php echo $student['id']; ?>_manual">
                                                                    <i class="fas fa-user-clock"></i> ছুটি
                                                                </label>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <input type="text" class="form-control form-control-sm" 
                                                                   name="attendance[<?php echo $student['id']; ?>][remarks]" 
                                                                   placeholder="মন্তব্য (ঐচ্ছিক)"
                                                                   value="">
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <div class="row mt-3">
                                        <div class="col-md-12">
                                            <button type="submit" name="submit_attendance" class="btn btn-success">
                                                <i class="fas fa-save"></i> উপস্থিতি সংরক্ষণ করুন
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </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>
                // Camera functionality
                const startCameraBtn = document.getElementById('startCameraBtn');
                const captureBtn = document.getElementById('captureBtn');
                const cameraFeed = document.getElementById('cameraFeed');
                const cameraCanvas = document.getElementById('cameraCanvas');
                const cameraPlaceholder = document.getElementById('cameraPlaceholder');
                let videoStream = null;

                startCameraBtn.addEventListener('click', async () => {
                    try {
                        const stream = await navigator.mediaDevices.getUserMedia({ 
                            video: { facingMode: 'environment' } 
                        });
                        
                        videoStream = stream;
                        cameraFeed.srcObject = stream;
                        cameraFeed.style.display = 'block';
                        cameraPlaceholder.style.display = 'none';
                        captureBtn.disabled = false;
                        startCameraBtn.innerHTML = '<i class="fas fa-stop"></i> ক্যামেরা বন্ধ করুন';
                        startCameraBtn.classList.remove('btn-success');
                        startCameraBtn.classList.add('btn-danger');
                    } catch (err) {
                        console.error('Error accessing camera:', err);
                        alert('ক্যামেরা ব্যবহার করতে অসুবিধা হচ্ছে: ' + err.message);
                    }
                });

                // Stop camera when clicking stop button
                startCameraBtn.addEventListener('click', function(e) {
                    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;
                        startCameraBtn.innerHTML = '<i class="fas fa-play"></i> ক্যামেরা শুরু করুন';
                        startCameraBtn.classList.remove('btn-danger');
                        startCameraBtn.classList.add('btn-success');
                    }
                });

                // Capture photo
                captureBtn.addEventListener('click', () => {
                    if (videoStream) {
                        const context = cameraCanvas.getContext('2d');
                        cameraCanvas.width = cameraFeed.videoWidth;
                        cameraCanvas.height = cameraFeed.videoHeight;
                        context.drawImage(cameraFeed, 0, 0, cameraCanvas.width, cameraCanvas.height);
                        
                        // Convert to data URL for processing
                        const imageData = cameraCanvas.toDataURL('image/jpeg');
                        console.log('Captured image data:', imageData.substring(0, 50) + '...');
                        
                        // Here you would send the image data to the backend for face recognition
                        // For now, just show an alert
                        alert('ছবি তোলা হয়েছে! (প্রকৃত মুখ চেনার সিস্টেমে পাঠানো হবে)');
                    }
                });

                // Fingerprint scanning functionality
                const scanFingerBtn = document.getElementById('scanFingerBtn');
                scanFingerBtn.addEventListener('click', () => {
                    // Simulate fingerprint scanning process
                    scanFingerBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> স্ক্যান হচ্ছে...';
                    scanFingerBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.4)';
                    
                    setTimeout(() => {
                        scanFingerBtn.innerHTML = '<i class="fas fa-check"></i> সফল!';
                        scanFingerBtn.style.backgroundColor = 'rgba(40, 167, 69, 0.3)';
                        
                        // Reset after delay
                        setTimeout(() => {
                            scanFingerBtn.innerHTML = '<i class="fas fa-hand-pointer"></i> স্ক্যান শুরু করুন';
                            scanFingerBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
                        }, 2000);
                        
                        // Here you would integrate with actual fingerprint scanner
                        alert('ফিংগারপ্রিন্ট স্ক্যান করা হয়েছে! (প্রকৃত ফিংগারপ্রিন্ট স্ক্যানারে পাঠানো হবে)');
                    }, 2000);
                });

                // Quick action buttons
                document.getElementById('markAllPresentBtn').addEventListener('click', () => {
                    document.querySelectorAll('input[name*="[status]"][value="present"]').forEach(radio => {
                        radio.checked = true;
                    });
                    updateAttendanceCounts();
                });

                document.getElementById('markAllAbsentBtn').addEventListener('click', () => {
                    document.querySelectorAll('input[name*="[status]"][value="absent"]').forEach(radio => {
                        radio.checked = true;
                    });
                    updateAttendanceCounts();
                });

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

                // Listen for changes in attendance radios to update counts
                document.querySelectorAll('input[name*="[status]"]').forEach(radio => {
                    radio.addEventListener('change', updateAttendanceCounts);
                });

                // Save attendance button
                document.getElementById('saveAttendanceBtn').addEventListener('click', () => {
                    // Submit the form programmatically
                    document.querySelector('form[method="POST"]').submit();
                });

                // Auto-submit form when class, session or date changes
                document.getElementById('class_id').addEventListener('change', function() {
                    if (this.value) {
                        this.form.submit();
                    }
                });

                document.getElementById('session').addEventListener('change', function() {
                    const classSelect = document.getElementById('class_id');
                    if (classSelect.value) {
                        this.form.submit();
                    }
                });

                document.getElementById('date').addEventListener('change', function() {
                    const classSelect = document.getElementById('class_id');
                    if (classSelect.value) {
                        this.form.submit();
                    }
                });
            </script>
        </div> <!-- End main-content -->
    </div> <!-- End sidebar-container -->
</body>
</html>