<?php
/**
 * Auto Attendance with Tabs
 * Tab 1: Camera - Take attendance via camera
 * Tab 2: Records - View auto-scanned attendance records
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/site_settings.php';
require_once __DIR__ . '/../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 active tab
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'camera';

// Get teacher's assigned classes if user is a teacher
$teacher_id = null;
$assigned_class_ids = [];
if ($_SESSION['user_role'] == 'teacher') {
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        $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)) {
    $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 {
    $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;
    }
}

// Get unique groups
$stmt = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name");
$groups = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Filter parameters
$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');
$selected_group = isset($_GET['group']) ? $_GET['group'] : '';

// Get students for camera tab
$students = [];
if ($active_tab == 'camera' && $selected_class > 0 && $selected_session) {
    $stmt = $pdo->prepare("
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.photo, 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();
}

// Get records for records tab
$attendance_records = [];
$class_group_stats = [];

// Get all classes report data
$all_classes_report = [];
if ($active_tab == 'all_classes') {
    // Get all classes with their attendance summary
    $all_classes_query = "
        SELECT 
            c.id as class_id,
            c.name as class_name,
            c.section,
            COUNT(DISTINCT s.id) as total_students,
            COUNT(DISTINCT CASE WHEN a.status = 'present' AND a.date = ? THEN s.id END) as present_count,
            COUNT(DISTINCT CASE WHEN a.status = 'absent' AND a.date = ? THEN s.id END) as absent_count,
            COUNT(DISTINCT CASE WHEN a.status = 'late' AND a.date = ? THEN s.id END) as late_count
        FROM classes c
        LEFT JOIN students s ON c.id = s.class_id AND s.status = 'active' AND s.session = ?
        LEFT JOIN attendance a ON s.id = a.student_id AND a.remarks LIKE '%Auto-marked%'
        WHERE c.status = 'active'
    ";
    
    $all_classes_params = [$selected_date, $selected_date, $selected_date, $selected_session];
    
    if ($_SESSION['user_role'] == 'teacher' && !empty($assigned_class_ids)) {
        $all_classes_query .= " AND c.id IN (" . implode(',', $assigned_class_ids) . ")";
    }
    
    $all_classes_query .= " GROUP BY c.id, c.name, c.section ORDER BY c.name, c.section";
    
    $stmt = $pdo->prepare($all_classes_query);
    $stmt->execute($all_classes_params);
    $all_classes_report = $stmt->fetchAll();
    
    // Calculate not marked for each class
    foreach ($all_classes_report as &$class_stat) {
        $class_stat['not_marked'] = $class_stat['total_students'] - $class_stat['present_count'] - $class_stat['absent_count'] - $class_stat['late_count'];
    }
    unset($class_stat);
}

if ($active_tab == 'records') {
    // Get auto-scanned attendance records
    $query = "
        SELECT 
            a.id as attendance_id,
            a.date,
            a.status,
            a.remarks,
            a.created_at,
            s.id as student_id,
            s.student_id as student_code,
            s.first_name,
            s.last_name,
            s.roll_number,
            s.photo,
            s.session,
            s.group_name,
            c.name as class_name,
            c.section,
            u.username as marked_by
        FROM attendance a
        JOIN students s ON a.student_id = s.id
        LEFT JOIN classes c ON s.class_id = c.id
        LEFT JOIN users u ON a.marked_by = u.id
        WHERE a.remarks LIKE '%Auto-marked%'
    ";
    
    $params = [];
    
    if ($selected_date) {
        $query .= " AND a.date = ?";
        $params[] = $selected_date;
    }
    
    if ($selected_class > 0) {
        $query .= " AND s.class_id = ?";
        $params[] = $selected_class;
    }
    
    if ($selected_session) {
        $query .= " AND s.session = ?";
        $params[] = $selected_session;
    }
    
    if ($selected_group) {
        $query .= " AND s.group_name = ?";
        $params[] = $selected_group;
    }
    
    $query .= " ORDER BY a.created_at DESC, s.roll_number ASC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $attendance_records = $stmt->fetchAll();
    
    // Calculate statistics
    $total_records = count($attendance_records);
    $present_count = count(array_filter($attendance_records, function($r) { return $r['status'] === 'present'; }));
    $absent_count = count(array_filter($attendance_records, function($r) { return $r['status'] === 'absent'; }));
    $late_count = count(array_filter($attendance_records, function($r) { return $r['status'] === 'late'; }));
    
    // Get class and group wise statistics
    $class_group_query = "
        SELECT 
            c.id as class_id,
            c.name as class_name,
            c.section,
            COALESCE(s.group_name, '') as group_name,
            COUNT(DISTINCT s.id) as total_students,
            COUNT(DISTINCT CASE WHEN a.status = 'present' AND a.remarks LIKE '%Auto-marked%' THEN s.id END) as present_count,
            COUNT(DISTINCT CASE WHEN a.status = 'absent' AND a.remarks LIKE '%Auto-marked%' THEN s.id END) as absent_count,
            COUNT(DISTINCT CASE WHEN a.status = 'late' AND a.remarks LIKE '%Auto-marked%' THEN s.id END) as late_count
        FROM students s
        JOIN classes c ON s.class_id = c.id
        LEFT JOIN attendance a ON s.id = a.student_id AND a.date = ? AND a.remarks LIKE '%Auto-marked%'
        WHERE s.status = 'active'
    ";
    
    $class_group_params = [$selected_date];
    
    if ($selected_session) {
        $class_group_query .= " AND s.session = ?";
        $class_group_params[] = $selected_session;
    }
    
    if ($selected_class > 0) {
        $class_group_query .= " AND s.class_id = ?";
        $class_group_params[] = $selected_class;
    }
    
    if ($selected_group) {
        $class_group_query .= " AND s.group_name = ?";
        $class_group_params[] = $selected_group;
    }
    
    $class_group_query .= " GROUP BY c.id, c.name, c.section, s.group_name ORDER BY c.name, c.section, s.group_name";
    
    $stmt = $pdo->prepare($class_group_query);
    $stmt->execute($class_group_params);
    $class_group_stats = $stmt->fetchAll();
    
    // Calculate not_marked for each group
    foreach ($class_group_stats as &$stat) {
        $stat['not_marked'] = $stat['total_students'] - $stat['present_count'] - $stat['absent_count'] - $stat['late_count'];
        $stat['absent_or_not_marked'] = $stat['absent_count'] + $stat['not_marked'];
    }
    unset($stat);
}

// Get user info for sidebar
$user_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'User';
if (isset($_SESSION['user_id']) && $_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>
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
        }
        .stats-card h3 {
            font-size: 2.5rem;
            margin-bottom: 5px;
        }
        .stats-card.present {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        }
        .stats-card.absent {
            background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
        }
        .stats-card.late {
            background: linear-gradient(135deg, #f7971e 0%, #ffd200 100%);
        }
        .class-group-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid #667eea;
        }
        .class-group-card .class-name {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        .class-group-card .group-name {
            font-size: 0.9rem;
            color: #666;
            margin-bottom: 10px;
        }
        .class-group-card .stats-row {
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }
        .class-group-card .stat-item {
            text-align: center;
            flex: 1;
            padding: 8px;
            border-radius: 5px;
            background: #f8f9fa;
        }
        .class-group-card .stat-item.present {
            background: #d4edda;
            color: #155724;
        }
        .class-group-card .stat-item.absent {
            background: #f8d7da;
            color: #721c24;
        }
        .class-group-card .stat-item.total {
            background: #e2e3e5;
            color: #383d41;
        }
        .class-group-card .stat-number {
            font-size: 1.5rem;
            font-weight: bold;
            display: block;
        }
        .class-group-card .stat-label {
            font-size: 0.75rem;
            text-transform: uppercase;
        }
        .attendance-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .student-photo {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 50%;
            border: 2px solid #28a745;
        }
        .student-photo-placeholder {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }
        .badge-present {
            background-color: #28a745;
        }
        .badge-absent {
            background-color: #dc3545;
        }
        .badge-late {
            background-color: #ffc107;
            color: #000;
        }
        .filter-section {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .empty-state {
            text-align: center;
            padding: 50px;
            color: #6c757d;
        }
        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            color: #dee2e6;
        }
        .camera-container {
            width: 100%;
            max-width: 640px;
            margin: 0 auto;
            border: 2px solid #dee2e6;
            border-radius: 0.375rem;
            overflow: hidden;
        }
        .camera-feed {
            width: 100%;
            height: 480px;
            background-color: #000;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2em;
        }
        .recognized-student {
            background-color: #d4edda;
            border: 2px solid #28a745;
            border-radius: 0.375rem;
            padding: 10px;
            margin: 10px 0;
            animation: highlight 1s;
        }
        @keyframes highlight {
            0% { background-color: #fff3cd; }
            50% { background-color: #d4edda; }
            100% { background-color: #d4edda; }
        }
        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        .status-present {
            background-color: #28a745;
        }
        .status-absent {
            background-color: #dc3545;
        }
        /* Enhanced Tab Styles */
        .card .nav-tabs {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 15px 15px 0 15px;
            border-bottom: 3px solid #007bff;
            margin: 0;
            border-radius: 0;
        }
        .card .nav-tabs .nav-item {
            margin-right: 8px;
            flex: 1;
        }
        .card .nav-tabs .nav-link {
            font-weight: 700;
            padding: 20px 10px;
            font-size: 1rem;
            border: 2px solid #dee2e6;
            border-radius: 8px 8px 0 0;
            background-color: #ffffff;
            color: #495057;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            min-height: 80px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .card .nav-tabs .nav-link:hover:not(.active) {
            background-color: #e3f2fd;
            border-color: #90caf9;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            color: #0056b3;
        }
        .card .nav-tabs .nav-link.active {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            border-color: #0056b3;
            box-shadow: 0 6px 20px rgba(0,123,255,0.4);
            transform: translateY(-4px);
            z-index: 10;
        }
        .card .nav-tabs .nav-link.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 20%;
            right: 20%;
            height: 4px;
            background-color: #ffd700;
            border-radius: 2px;
        }
        .tab-icon {
            font-size: 1.8rem;
            margin-bottom: 5px;
            display: block;
        }
        .nav-link span {
            font-size: 0.95rem;
            line-height: 1.2;
        }
    </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">
                    <!-- Tabs Navigation -->
                    <div class="card shadow-sm mb-4 border-0">
                        <div class="card-header bg-light py-3">
                            <h5 class="mb-0 text-dark">
                                <i class="fas fa-th-large me-2"></i>নেভিগেশন মেনু
                            </h5>
                        </div>
                        <div class="card-body p-0">
                            <ul class="nav nav-tabs" id="attendanceTabs" role="tablist">
                                <li class="nav-item flex-fill" role="presentation">
                                    <a class="nav-link <?php echo $active_tab == 'camera' ? 'active' : ''; ?> text-center" 
                                       href="?tab=camera" role="tab">
                                        <i class="fas fa-camera tab-icon d-block mb-1"></i>
                                        <span>ক্যামেরা দিয়ে হাজিরা নিন</span>
                                    </a>
                                </li>
                                <li class="nav-item flex-fill" role="presentation">
                                    <a class="nav-link <?php echo $active_tab == 'records' ? 'active' : ''; ?> text-center" 
                                       href="?tab=records" role="tab">
                                        <i class="fas fa-clipboard-list tab-icon d-block mb-1"></i>
                                        <span>অটো স্ক্যান রেকর্ড</span>
                                    </a>
                                </li>
                                <li class="nav-item flex-fill" role="presentation">
                                    <a class="nav-link <?php echo $active_tab == 'all_classes' ? 'active' : ''; ?> text-center" 
                                       href="?tab=all_classes" role="tab">
                                        <i class="fas fa-chart-pie tab-icon d-block mb-1"></i>
                                        <span>সকল শ্রেণীর রিপোর্ট</span>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <?php if ($active_tab == 'camera'): ?>
                    <!-- Camera Tab Content -->
                    <div class="tab-content">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0"><i class="fas fa-video"></i> অটোমেটিক উপস্থিতি মার্কিং</h5>
                            </div>
                            <div class="card-body">
                                <!-- Class, Session and Date Selection -->
                                <form method="GET" class="mb-4">
                                    <input type="hidden" name="tab" value="camera">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <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-3">
                                            <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>

                                <?php if ($selected_class > 0 && $selected_session): ?>
                                <!-- Camera Feed -->
                                <div class="row mb-4">
                                    <div class="col-md-8">
                                        <div class="camera-container">
                                            <div class="camera-feed">
                                                <video id="cameraFeed" autoplay playsinline style="display: none; width: 100%; height: 100%; object-fit: cover;"></video>
                                                <canvas id="cameraCanvas" style="display: none;"></canvas>
                                                <div id="cameraPlaceholder">
                                                    <i class="fas fa-camera fa-3x mb-2"></i>
                                                    <p>ক্যামেরা ফিড এখানে প্রদর্শিত হবে</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="text-center mt-2">
                                            <small class="text-muted">ক্যামেরার সামনে দাঁড়ালে স্বয়ংক্রিয়ভাবে উপস্থিতি চিহ্নিত করা হবে</small>
                                            <div class="mt-2">
                                                <button class="btn btn-success me-2" id="startCameraBtn">
                                                    <i class="fas fa-play"></i> ক্যামেরা শুরু করুন
                                                </button>
                                                <button class="btn btn-danger" id="stopCameraBtn" style="display: none;">
                                                    <i class="fas fa-stop"></i> বন্ধ করুন
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <!-- Attendance Summary -->
                                        <div class="row mb-4">
                                            <div class="col-md-6 mb-2">
                                                <div class="stats-card present" style="padding: 15px;">
                                                    <h4 id="presentCount">0</h4>
                                                    <p style="font-size: 0.9rem;"><i class="fas fa-check-circle"></i> উপস্থিত</p>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="stats-card absent" style="padding: 15px;">
                                                    <h4 id="absentCount">0</h4>
                                                    <p style="font-size: 0.9rem;"><i class="fas fa-times-circle"></i> অনুপস্থিত</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-12">
                                                <div class="alert alert-info py-2">
                                                    <small><i class="fas fa-info-circle"></i> মোট ছাত্র: <strong id="totalCount">0</strong> জন</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Recognized Students List -->
                                        <div class="card">
                                            <div class="card-header">
                                                <h6><i class="fas fa-users"></i> শেষ স্বীকৃত ছাত্র</h6>
                                            </div>
                                            <div class="card-body" style="max-height: 300px; overflow-y: auto;">
                                                <div id="recognizedStudents">
                                                    <p class="text-muted">কোনও ছাত্র স্বীকৃতি দেওয়া হয়নি</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Students List -->
                                <div class="card">
                                    <div class="card-header">
                                        <h6><i class="fas fa-list"></i> ছাত্র তালিকা (মোট: <?php echo count($students); ?> জন)</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-striped table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>ছবি</th>
                                                        <th>রোল</th>
                                                        <th>নাম</th>
                                                        <th>গ্রুপ</th>
                                                        <th>আজকের উপস্থিতি</th>
                                                        <th>অ্যাকশন</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($students as $student): 
                                                        // Check if already marked today
                                                        $stmt = $pdo->prepare("SELECT id, status FROM attendance WHERE student_id = ? AND date = ? AND remarks LIKE '%Auto-marked%'");
                                                        $stmt->execute([$student['id'], $selected_date]);
                                                        $today_attendance = $stmt->fetch();
                                                    ?>
                                                        <tr id="student_row_<?php echo $student['id']; ?>">
                                                            <td>
                                                                <?php if ($student['photo'] && file_exists(__DIR__ . '/../' . ltrim($student['photo'], '/'))): ?>
                                                                    <img src="../<?php echo ltrim($student['photo'], '/'); ?>"
                                                                         alt="<?php echo $student['first_name']; ?>" 
                                                                         class="student-photo">
                                                                <?php else: ?>
                                                                    <div class="student-photo-placeholder">
                                                                        <i class="fas fa-user"></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>
                                                            </td>
                                                            <td><?php echo !empty($student['group_name']) ? htmlspecialchars($student['group_name']) : 'N/A'; ?></td>
                                                            <td>
                                                                <?php if ($today_attendance): ?>
                                                                    <span class="badge badge-present">উপস্থিত</span>
                                                                    <small class="text-muted d-block">ID: <?php echo $today_attendance['id']; ?></small>
                                                                <?php else: ?>
                                                                    <span class="badge badge-absent">অনুপস্থিত</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if (!$today_attendance): ?>
                                                                    <button class="btn btn-sm btn-success mark-present-btn" 
                                                                            data-student-id="<?php echo $student['id']; ?>">
                                                                        <i class="fas fa-check"></i> উপস্থিত
                                                                    </button>
                                                                <?php else: ?>
                                                                    <button class="btn btn-sm btn-secondary" disabled>
                                                                        <i class="fas fa-check-double"></i> হয়ে গেছে
                                                                    </button>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle"></i> উপরের ফর্ম থেকে ক্লাস ও সেশন নির্বাচন করুন।
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <script>
                        let videoStream = null;
                        let isProcessing = false;
                        const cameraFeed = document.getElementById('cameraFeed');
                        const cameraCanvas = document.getElementById('cameraCanvas');
                        const cameraPlaceholder = document.getElementById('cameraPlaceholder');
                        const startCameraBtn = document.getElementById('startCameraBtn');
                        const stopCameraBtn = document.getElementById('stopCameraBtn');
                        const presentCountElement = document.getElementById('presentCount');
                        const recognizedStudentsDiv = document.getElementById('recognizedStudents');
                        
                        let presentCount = <?php 
                            // Count today's present students
                            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM attendance WHERE class_id = ? AND date = ? AND status = 'present' AND remarks LIKE '%Auto-marked%'");
                            $stmt->execute([$selected_class, $selected_date]);
                            echo $stmt->fetch()['count'];
                        ?>;
                        let totalStudents = <?php echo count($students); ?>;
                        let absentCount = totalStudents - presentCount;
                        
                        presentCountElement.textContent = presentCount;
                        document.getElementById('absentCount').textContent = absentCount;
                        document.getElementById('totalCount').textContent = totalStudents;
                        
                        // Start camera
                        startCameraBtn.addEventListener('click', async () => {
                            try {
                                videoStream = await navigator.mediaDevices.getUserMedia({ 
                                    video: { facingMode: 'user', width: 640, height: 480 } 
                                });
                                cameraFeed.srcObject = videoStream;
                                cameraFeed.style.display = 'block';
                                cameraPlaceholder.style.display = 'none';
                                startCameraBtn.style.display = 'none';
                                stopCameraBtn.style.display = 'inline-block';
                                
                                // Start auto recognition simulation
                                startAutoRecognition();
                            } catch (err) {
                                alert('ক্যামেরা অ্যাক্সেস করতে ব্যর্থ: ' + err.message);
                            }
                        });
                        
                        // Stop camera
                        stopCameraBtn.addEventListener('click', () => {
                            if (videoStream) {
                                videoStream.getTracks().forEach(track => track.stop());
                                videoStream = null;
                            }
                            cameraFeed.style.display = 'none';
                            cameraPlaceholder.style.display = 'flex';
                            startCameraBtn.style.display = 'inline-block';
                            stopCameraBtn.style.display = 'none';
                            stopAutoRecognition();
                        });
                        
                        // Auto recognition simulation
                        let recognitionInterval;
                        function startAutoRecognition() {
                            recognitionInterval = setInterval(() => {
                                if (!isProcessing) {
                                    captureAndRecognize();
                                }
                            }, 3000); // Check every 3 seconds
                        }
                        
                        function stopAutoRecognition() {
                            if (recognitionInterval) {
                                clearInterval(recognitionInterval);
                                recognitionInterval = null;
                            }
                        }
                        
                        function captureAndRecognize() {
                            if (!videoStream) return;
                            
                            isProcessing = true;
                            
                            // Capture frame
                            cameraCanvas.width = cameraFeed.videoWidth;
                            cameraCanvas.height = cameraFeed.videoHeight;
                            const ctx = cameraCanvas.getContext('2d');
                            ctx.drawImage(cameraFeed, 0, 0);
                            
                            // Get image data
                            const imageData = cameraCanvas.toDataURL('image/jpeg', 0.8);
                            
                            // Send to server for recognition
                            markAttendanceWithPhoto(imageData);
                        }
                        
                        function markAttendanceWithPhoto(imageData) {
                            const formData = new FormData();
                            formData.append('action', 'mark_attendance_photo');
                            formData.append('class_id', '<?php echo $selected_class; ?>');
                            formData.append('date', '<?php echo $selected_date; ?>');
                            formData.append('photo_data', imageData);
                            
                            fetch(window.location.href, {
                                method: 'POST',
                                body: formData
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success && data.student_id) {
                                    // Update UI
                                    updateStudentStatus(data.student_id, data.student_name);
                                }
                                isProcessing = false;
                            })
                            .catch(err => {
                                console.error('Error:', err);
                                isProcessing = false;
                            });
                        }
                        
                        function updateStudentStatus(studentId, studentName) {
                            // Increment count
                            presentCount++;
                            absentCount--;
                            if (absentCount < 0) absentCount = 0;
                            
                            presentCountElement.textContent = presentCount;
                            document.getElementById('absentCount').textContent = absentCount;
                            
                            // Add to recognized list
                            const studentDiv = document.createElement('div');
                            studentDiv.className = 'recognized-student';
                            studentDiv.innerHTML = `
                                <i class="fas fa-check-circle text-success"></i>
                                <strong>${studentName}</strong>
                                <small class="text-muted">${new Date().toLocaleTimeString('bn-BD')}</small>
                            `;
                            
                            if (recognizedStudentsDiv.querySelector('.text-muted')) {
                                recognizedStudentsDiv.innerHTML = '';
                            }
                            recognizedStudentsDiv.prepend(studentDiv);
                            
                            // Update table row
                            const row = document.getElementById('student_row_' + studentId);
                            if (row) {
                                const statusCell = row.querySelector('td:nth-child(5)');
                                const actionCell = row.querySelector('td:nth-child(6)');
                                statusCell.innerHTML = '<span class="badge badge-present">উপস্থিত</span>';
                                actionCell.innerHTML = '<button class="btn btn-sm btn-secondary" disabled><i class="fas fa-check-double"></i> হয়ে গেছে</button>';
                                row.style.backgroundColor = '#d4edda';
                                setTimeout(() => {
                                    row.style.backgroundColor = '';
                                }, 2000);
                            }
                            
                            // Keep only last 5 in the list
                            while (recognizedStudentsDiv.children.length > 5) {
                                recognizedStudentsDiv.removeChild(recognizedStudentsDiv.lastChild);
                            }
                        }
                        
                        // Manual mark present buttons
                        document.querySelectorAll('.mark-present-btn').forEach(btn => {
                            btn.addEventListener('click', function() {
                                const studentId = this.getAttribute('data-student-id');
                                markStudentPresent(studentId);
                            });
                        });
                        
                        function markStudentPresent(studentId) {
                            const formData = new FormData();
                            formData.append('action', 'mark_attendance');
                            formData.append('student_id', studentId);
                            formData.append('class_id', '<?php echo $selected_class; ?>');
                            formData.append('date', '<?php echo $selected_date; ?>');
                            
                            fetch(window.location.href, {
                                method: 'POST',
                                body: formData
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    const row = document.getElementById('student_row_' + studentId);
                                    const studentName = row.querySelector('td:nth-child(3)').textContent.trim();
                                    updateStudentStatus(studentId, studentName);
                                }
                            })
                            .catch(err => console.error('Error:', err));
                        }
                    </script>
                    <?php endif; ?>

                    <?php if ($active_tab == 'records'): ?>
                    <!-- Records Tab Content -->
                    <div class="tab-content">
                        <!-- Statistics Cards -->
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="stats-card">
                                    <h3><?php echo $total_records; ?></h3>
                                    <p><i class="fas fa-users"></i> মোট রেকর্ড</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stats-card present">
                                    <h3><?php echo $present_count; ?></h3>
                                    <p><i class="fas fa-check-circle"></i> উপস্থিত</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stats-card absent">
                                    <h3><?php echo $absent_count; ?></h3>
                                    <p><i class="fas fa-times-circle"></i> অনুপস্থিত</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stats-card late">
                                    <h3><?php echo $late_count; ?></h3>
                                    <p><i class="fas fa-clock"></i> দেরি</p>
                                </div>
                            </div>
                        </div>

                        <!-- Class-Group Statistics Section -->
                        <?php if (!empty($class_group_stats)): ?>
                        <div class="class-group-section">
                            <h5><i class="fas fa-chart-bar"></i> ক্লাস ও গ্রুপ ভিত্তিক পরিসংখ্যান</h5>
                            <div class="row">
                                <?php foreach ($class_group_stats as $stat): 
                                    $attendance_rate = $stat['total_students'] > 0 ? round(($stat['present_count'] / $stat['total_students']) * 100, 1) : 0;
                                ?>
                                    <div class="col-md-4 col-lg-3">
                                        <div class="class-group-card">
                                            <div class="class-name">
                                                <i class="fas fa-graduation-cap"></i> 
                                                <?php echo htmlspecialchars($stat['class_name'] . ' - ' . $stat['section']); ?>
                                            </div>
                                            <div class="group-name">
                                                <i class="fas fa-users"></i> 
                                                <?php echo htmlspecialchars($stat['group_name'] ?: 'সাধারণ'); ?>
                                            </div>
                                            <div class="stats-row">
                                                <div class="stat-item present">
                                                    <span class="stat-number"><?php echo $stat['present_count']; ?></span>
                                                    <span class="stat-label">উপস্থিত</span>
                                                </div>
                                                <div class="stat-item absent">
                                                    <span class="stat-number"><?php echo $stat['absent_or_not_marked']; ?></span>
                                                    <span class="stat-label">অনুপস্থিত</span>
                                                </div>
                                                <div class="stat-item total">
                                                    <span class="stat-number"><?php echo $stat['total_students']; ?></span>
                                                    <span class="stat-label">মোট</span>
                                                </div>
                                            </div>
                                            <?php if ($stat['not_marked'] > 0): ?>
                                            <div class="alert alert-warning mt-2 py-1 px-2 mb-0" style="font-size: 0.75rem;">
                                                <i class="fas fa-exclamation-triangle"></i> 
                                                <?php echo $stat['not_marked']; ?> জন এখনো চিহ্নিত হয়নি
                                            </div>
                                            <?php endif; ?>
                                            <div class="attendance-rate">
                                                <small class="text-muted">উপস্থিতির হার: <?php echo $attendance_rate; ?>%</small>
                                                <div class="progress">
                                                    <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $attendance_rate; ?>%" 
                                                         aria-valuenow="<?php echo $attendance_rate; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Filter Section -->
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <input type="hidden" name="tab" value="records">
                                <div class="col-md-2">
                                    <label class="form-label">তারিখ</label>
                                    <input type="date" name="date" class="form-control" value="<?php echo $selected_date; ?>">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">ক্লাস</label>
                                    <select name="class_id" class="form-select">
                                        <option value="">সব ক্লাস</option>
                                        <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>" 
                                                    <?php echo ($selected_class == $class['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">সেশন</label>
                                    <select name="session" class="form-select">
                                        <option value="">সব সেশন</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo htmlspecialchars($session); ?>" 
                                                    <?php echo ($selected_session == $session) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($session); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">গ্রুপ</label>
                                    <select name="group" class="form-select">
                                        <option value="">সব গ্রুপ</option>
                                        <?php foreach ($groups as $group): ?>
                                            <option value="<?php echo htmlspecialchars($group); ?>" 
                                                    <?php echo ($selected_group == $group) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($group); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-filter"></i> ফিল্টার
                                        </button>
                                        <a href="?tab=records" class="btn btn-outline-secondary">
                                            <i class="fas fa-undo"></i> রিসেট
                                        </a>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <!-- Attendance Records Table -->
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-list"></i> 
                                    অটো স্ক্যানকৃত উপস্থিতির তালিকা
                                    <?php if ($selected_date): ?>
                                        <span class="badge bg-light text-dark ms-2"><?php echo date('d F Y', strtotime($selected_date)); ?></span>
                                    <?php endif; ?>
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if (empty($attendance_records)): ?>
                                    <div class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <h4>কোনো রেকর্ড পাওয়া যায়নি</h4>
                                        <p>নির্বাচিত ফিল্টার অনুযায়ী কোনো অটো স্ক্যান উপস্থিতি রেকর্ড পাওয়া যায়নি।</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover attendance-table">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>ছবি</th>
                                                    <th>ছাত্রের তথ্য</th>
                                                    <th>ক্লাস</th>
                                                    <th>গ্রুপ</th>
                                                    <th>সেশন</th>
                                                    <th>তারিখ</th>
                                                    <th>সময়</th>
                                                    <th>স্ট্যাটাস</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($attendance_records as $index => $record): ?>
                                                    <tr>
                                                        <td><?php echo $index + 1; ?></td>
                                                        <td>
                                                            <?php if ($record['photo'] && file_exists(__DIR__ . '/../' . ltrim($record['photo'], '/'))): ?>
                                                                <img src="../<?php echo ltrim($record['photo'], '/'); ?>" 
                                                                     alt="<?php echo htmlspecialchars($record['first_name']); ?>" 
                                                                     class="student-photo">
                                                            <?php else: ?>
                                                                <div class="student-photo-placeholder">
                                                                    <i class="fas fa-user"></i>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <strong><?php echo htmlspecialchars($record['first_name'] . ' ' . $record['last_name']); ?></strong>
                                                            <br>
                                                            <small class="text-muted">
                                                                ID: <?php echo htmlspecialchars($record['student_code']); ?> | 
                                                                রোল: <?php echo htmlspecialchars($record['roll_number']); ?>
                                                            </small>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($record['class_name'] . ' - ' . $record['section']); ?></td>
                                                        <td><?php echo htmlspecialchars($record['group_name'] ?: 'N/A'); ?></td>
                                                        <td><?php echo htmlspecialchars($record['session']); ?></td>
                                                        <td><?php echo date('d M Y', strtotime($record['date'])); ?></td>
                                                        <td>
                                                            <small class="text-muted">
                                                                <?php echo date('h:i A', strtotime($record['created_at'])); ?>
                                                            </small>
                                                        </td>
                                                        <td>
                                                            <?php 
                                                            $badge_class = '';
                                                            $status_text = '';
                                                            switch ($record['status']) {
                                                                case 'present':
                                                                    $badge_class = 'badge-present';
                                                                    $status_text = 'উপস্থিত';
                                                                    break;
                                                                case 'absent':
                                                                    $badge_class = 'badge-absent';
                                                                    $status_text = 'অনুপস্থিত';
                                                                    break;
                                                                case 'late':
                                                                    $badge_class = 'badge-late';
                                                                    $status_text = 'দেরি';
                                                                    break;
                                                                default:
                                                                    $badge_class = 'bg-secondary';
                                                                    $status_text = $record['status'];
                                                            }
                                                            ?>
                                                            <span class="badge <?php echo $badge_class; ?>">
                                                                <?php echo $status_text; ?>
                                                            </span>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if ($active_tab == 'all_classes'): ?>
                    <!-- All Classes Report Tab Content -->
                    <div class="tab-content">
                        <!-- Filter Section -->
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <input type="hidden" name="tab" value="all_classes">
                                <div class="col-md-4">
                                    <label class="form-label">তারিখ</label>
                                    <input type="date" name="date" class="form-control" value="<?php echo $selected_date; ?>">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">সেশন</label>
                                    <select name="session" class="form-select">
                                        <option value="">সব সেশন</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo htmlspecialchars($session); ?>" 
                                                    <?php echo ($selected_session == $session) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($session); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-filter"></i> ফিল্টার
                                        </button>
                                        <a href="?tab=all_classes" class="btn btn-outline-secondary">
                                            <i class="fas fa-undo"></i> রিসেট
                                        </a>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <!-- Overall Summary -->
                        <?php
                        $grand_total = array_sum(array_column($all_classes_report, 'total_students'));
                        $grand_present = array_sum(array_column($all_classes_report, 'present_count'));
                        $grand_absent = array_sum(array_column($all_classes_report, 'absent_count'));
                        $grand_late = array_sum(array_column($all_classes_report, 'late_count'));
                        $grand_not_marked = array_sum(array_column($all_classes_report, 'not_marked'));
                        $overall_rate = $grand_total > 0 ? round(($grand_present / $grand_total) * 100, 1) : 0;
                        ?>
                        
                        <div class="card mb-4">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-chart-pie"></i> সার্বিক পরিসংখ্যান
                                    <?php if ($selected_date): ?>
                                        <span class="badge bg-light text-dark ms-2"><?php echo date('d F Y', strtotime($selected_date)); ?></span>
                                    <?php endif; ?>
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="stats-card" style="padding: 15px;">
                                            <h4><?php echo $grand_total; ?></h4>
                                            <p style="font-size: 0.85rem;">মোট ছাত্র</p>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="stats-card present" style="padding: 15px;">
                                            <h4><?php echo $grand_present; ?></h4>
                                            <p style="font-size: 0.85rem;">উপস্থিত</p>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="stats-card absent" style="padding: 15px;">
                                            <h4><?php echo $grand_absent; ?></h4>
                                            <p style="font-size: 0.85rem;">অনুপস্থিত</p>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="stats-card late" style="padding: 15px;">
                                            <h4><?php echo $grand_late; ?></h4>
                                            <p style="font-size: 0.85rem;">দেরি</p>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="stats-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 15px;">
                                            <h4><?php echo $grand_not_marked; ?></h4>
                                            <p style="font-size: 0.85rem;">চিহ্নিত হয়নি</p>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="text-center">
                                            <div style="font-size: 2rem; font-weight: bold; color: #28a745;"><?php echo $overall_rate; ?>%</div>
                                            <small class="text-muted">সার্বিক উপস্থিতি</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- All Classes Report Table -->
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-list-alt"></i> সকল শ্রেণীর উপস্থিতি রিপোর্ট
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if (empty($all_classes_report)): ?>
                                    <div class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <h4>কোনো তথ্য পাওয়া যায়নি</h4>
                                        <p>কোনো শ্রেণী পাওয়া যায়নি অথবা নির্বাচিত ফিল্টারে কোনো তথ্য নেই।</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover attendance-table">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>শ্রেণী</th>
                                                    <th class="text-center">মোট ছাত্র</th>
                                                    <th class="text-center">উপস্থিত</th>
                                                    <th class="text-center">অনুপস্থিত</th>
                                                    <th class="text-center">দেরি</th>
                                                    <th class="text-center">চিহ্নিত হয়নি</th>
                                                    <th class="text-center">উপস্থিতির হার</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($all_classes_report as $index => $class): 
                                                    $rate = $class['total_students'] > 0 ? round(($class['present_count'] / $class['total_students']) * 100, 1) : 0;
                                                ?>
                                                    <tr>
                                                        <td><?php echo $index + 1; ?></td>
                                                        <td>
                                                            <strong><?php echo htmlspecialchars($class['class_name'] . ' - ' . $class['section']); ?></strong>
                                                        </td>
                                                        <td class="text-center">
                                                            <span class="badge bg-secondary"><?php echo $class['total_students']; ?></span>
                                                        </td>
                                                        <td class="text-center">
                                                            <span class="badge badge-present"><?php echo $class['present_count']; ?></span>
                                                        </td>
                                                        <td class="text-center">
                                                            <span class="badge badge-absent"><?php echo $class['absent_count']; ?></span>
                                                        </td>
                                                        <td class="text-center">
                                                            <span class="badge badge-late"><?php echo $class['late_count']; ?></span>
                                                        </td>
                                                        <td class="text-center">
                                                            <?php if ($class['not_marked'] > 0): ?>
                                                                <span class="badge bg-warning text-dark"><?php echo $class['not_marked']; ?></span>
                                                            <?php else: ?>
                                                                <span class="badge bg-success">0</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td class="text-center">
                                                            <div class="progress" style="height: 20px;">
                                                                <div class="progress-bar bg-success" role="progressbar" 
                                                                     style="width: <?php echo $rate; ?>%" 
                                                                     aria-valuenow="<?php echo $rate; ?>" aria-valuemin="0" aria-valuemax="100">
                                                                    <?php echo $rate; ?>%
                                                                </div>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
</body>
</html>
