<?php
session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';

// Check if user is logged in and is an admin
require_admin();

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];

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

// Handle duty adjustment actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'adjust_duty':
            $teacher_id = (int)$_POST['teacher_id'];
            $adjustment_type = $_POST['adjustment_type'];
            $routine_id = isset($_POST['routine_id']) ? (int)$_POST['routine_id'] : null;

            try {
                if ($adjustment_type === 'remove_class' && $routine_id) {
                    // Remove a class from teacher's schedule
                    $stmt = $pdo->prepare("DELETE FROM timetable WHERE id = ? AND teacher_id = ?");
                    $result = $stmt->execute([$routine_id, $teacher_id]);

                    if ($result) {
                        $success_message = 'শিক্ষকের ক্লাস সফলভাবে রিমুভ করা হয়েছে।';
                    } else {
                        $error_message = 'ক্লাস রিমুভ করতে সমস্যা হয়েছে।';
                    }
                } elseif ($adjustment_type === 'add_class') {
                    // This would require a more complex interface, for now just show message
                    $error_message = 'ক্লাস অ্যাড করার জন্য রুটিন পেজে যান।';
                }
            } catch (Exception $e) {
                $error_message = 'ত্রুটি: ' . $e->getMessage();
            }
            break;

        case 'reset_teacher_schedule':
            $teacher_id = (int)$_POST['teacher_id'];

            try {
                $stmt = $pdo->prepare("DELETE FROM timetable WHERE teacher_id = ?");
                $result = $stmt->execute([$teacher_id]);

                if ($result) {
                    $affected_rows = $stmt->rowCount();
                    $success_message = "শিক্ষকের সকল ক্লাস ({$affected_rows} টি) রিসেট করা হয়েছে।";
                } else {
                    $error_message = 'শিডিউল রিসেট করতে সমস্যা হয়েছে।';
                }
            } catch (Exception $e) {
                $error_message = 'ত্রুটি: ' . $e->getMessage();
            }
            break;

        case 'bulk_reset_teacher_schedules':
            if (!isset($_POST['selected_teachers']) || empty($_POST['selected_teachers'])) {
                $error_message = 'কোন শিক্ষক নির্বাচন করা হয়নি।';
                break;
            }

            $selected_teachers = $_POST['selected_teachers'];
            $total_affected = 0;
            $teacher_count = 0;

            try {
                foreach ($selected_teachers as $teacher_id) {
                    $teacher_id = (int)$teacher_id;
                    $stmt = $pdo->prepare("DELETE FROM timetable WHERE teacher_id = ?");
                    $result = $stmt->execute([$teacher_id]);

                    if ($result) {
                        $total_affected += $stmt->rowCount();
                        $teacher_count++;
                    }
                }

                if ($teacher_count > 0) {
                    $success_message = "{$teacher_count} জন শিক্ষকের সকল ক্লাস ({$total_affected} টি) রিসেট করা হয়েছে।";
                } else {
                    $error_message = 'কোন ক্লাস রিসেট করা যায়নি।';
                }
            } catch (Exception $e) {
                $error_message = 'ত্রুটি: ' . $e->getMessage();
            }
            break;
    }
}

// Get all teachers with their workload statistics
$teachers_query = "
    SELECT
        t.id,
        t.employee_id,
        t.first_name,
        t.last_name,
        t.designation,
        t.status,
        COUNT(DISTINCT cs.class_id) as total_classes,
        COUNT(DISTINCT cs.subject_id) as total_subjects,
        COUNT(DISTINCT tt.id) as total_routines,
        COALESCE(SUM(TIMESTAMPDIFF(MINUTE, tt.start_time, tt.end_time)), 0) as total_minutes
    FROM teachers t
    LEFT JOIN class_subjects cs ON t.id = cs.teacher_id
    LEFT JOIN timetable tt ON t.id = tt.teacher_id
    WHERE t.status = 'active'
    GROUP BY t.id, t.employee_id, t.first_name, t.last_name, t.designation, t.status
    ORDER BY t.first_name, t.last_name
";

$teachers = $pdo->query($teachers_query)->fetchAll();

// Get detailed workload for each teacher
$teacher_workloads = [];
foreach ($teachers as $teacher) {
    $teacher_id = $teacher['id'];

    // Get all routines for this teacher
    $routines_query = "
        SELECT
            tt.id,
            tt.day_of_week,
            tt.start_time,
            tt.end_time,
            tt.room_number,
            c.name as class_name,
            c.section as class_section,
            s.name as subject_name,
            s.code as subject_code,
            TIMESTAMPDIFF(MINUTE, tt.start_time, tt.end_time) as duration_minutes
        FROM timetable tt
        JOIN classes c ON tt.class_id = c.id
        JOIN subjects s ON tt.subject_id = s.id
        WHERE tt.teacher_id = ?
        ORDER BY tt.day_of_week, tt.start_time
    ";

    $stmt = $pdo->prepare($routines_query);
    $stmt->execute([$teacher_id]);
    $teacher_workloads[$teacher_id] = $stmt->fetchAll();
}

// Calculate workload statistics
$workload_stats = [
    'total_teachers' => count($teachers),
    'avg_classes_per_teacher' => 0,
    'avg_hours_per_teacher' => 0,
    'max_classes' => 0,
    'min_classes' => PHP_INT_MAX,
    'overloaded_teachers' => 0,
    'underloaded_teachers' => 0
];

$total_classes = 0;
$total_hours = 0;

foreach ($teachers as $teacher) {
    $total_classes += $teacher['total_classes'];
    $total_hours += $teacher['total_minutes'] / 60; // Convert to hours

    if ($teacher['total_classes'] > $workload_stats['max_classes']) {
        $workload_stats['max_classes'] = $teacher['total_classes'];
    }
    if ($teacher['total_classes'] < $workload_stats['min_classes']) {
        $workload_stats['min_classes'] = $teacher['total_classes'];
    }

    // Consider overloaded if more than 25 classes or 30+ hours per week
    if ($teacher['total_classes'] > 25 || ($teacher['total_minutes'] / 60) > 30) {
        $workload_stats['overloaded_teachers']++;
    }

    // Consider underloaded if less than 10 classes or 15 hours per week
    if ($teacher['total_classes'] < 10 || ($teacher['total_minutes'] / 60) < 15) {
        $workload_stats['underloaded_teachers']++;
    }
}

if ($workload_stats['total_teachers'] > 0) {
    $workload_stats['avg_classes_per_teacher'] = round($total_classes / $workload_stats['total_teachers'], 1);
    $workload_stats['avg_hours_per_teacher'] = round($total_hours / $workload_stats['total_teachers'], 1);
}

if ($workload_stats['min_classes'] == PHP_INT_MAX) {
    $workload_stats['min_classes'] = 0;
}

// Days mapping for display
$days_map = [
    'sunday' => 'রবিবার',
    'monday' => 'সোমবার',
    'tuesday' => 'মঙ্গলবার',
    'wednesday' => 'বুধবার',
    'thursday' => 'বৃহস্পতিবার',
    'friday' => 'শুক্রবার',
    'saturday' => 'শনিবার'
];
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষকের ডিউটি ম্যানেজমেন্ট - অ্যাডমিন প্যানেল</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Bengali:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Noto Sans Bengali', 'Siyam Rupali', Arial, sans-serif;
            font-size: 16px;
            line-height: 1.6;
        }

        .workload-card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }

        .workload-card:hover {
            transform: translateY(-2px);
        }

        .teacher-card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }

        .teacher-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            border-color: #006747;
        }

        .teacher-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            padding: 15px;
            border-radius: 8px 8px 0 0;
        }

        .workload-stats {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }

        .routine-item {
            background-color: #fff;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 10px;
            margin: 5px 0;
        }

        .overloaded {
            background-color: #f8d7da !important;
            border-color: #dc3545 !important;
        }

        .underloaded {
            background-color: #fff3cd !important;
            border-color: #ffc107 !important;
        }

        .normal-load {
            background-color: #d4edda !important;
            border-color: #28a745 !important;
        }

        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .action-btn {
            margin: 2px;
        }

        .time-display {
            font-weight: bold;
            color: #006747;
        }

        .subject-badge {
            background-color: #006747;
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.8em;
        }

        /* Print Styles for A4 Report */
        @media print {
            @page {
                size: A4;
                margin: 1cm;
            }

            body {
                font-family: 'Noto Sans Bengali', 'Hind Siliguri', Arial, sans-serif !important;
                font-size: 12pt !important;
                line-height: 1.4 !important;
                color: #000 !important;
                background: white !important;
            }

            /* Hide non-print elements */
            .no-print,
            .sidebar,
            .navbar,
            .btn,
            .form-check,
            .collapse,
            .mobile-toggle,
            .sidebar-toggle,
            .print-controls,
            .action-btn {
                display: none !important;
            }

            /* Show print-only content */
            .print-only {
                display: block !important;
            }

            /* Page header for print */
            .print-header {
                text-align: center;
                border-bottom: 3px solid #006747;
                padding-bottom: 15px;
                margin-bottom: 20px;
                page-break-after: avoid;
            }

            .print-header h1 {
                color: #006747;
                font-size: 24pt;
                font-weight: bold;
                margin: 0;
            }

            .print-header p {
                font-size: 14pt;
                color: #666;
                margin: 5px 0 0 0;
            }

            /* Stats section */
            .print-stats {
                display: flex !important;
                justify-content: space-around;
                margin-bottom: 20px;
                page-break-inside: avoid;
            }

            .stat-card {
                text-align: center;
                border: 2px solid #006747;
                border-radius: 8px;
                padding: 10px;
                flex: 1;
                margin: 0 5px;
                background: #f8f9fa !important;
            }

            .stat-number {
                font-size: 18pt;
                font-weight: bold;
                color: #006747;
                display: block;
            }

            .stat-label {
                font-size: 10pt;
                color: #333;
                margin-top: 2px;
            }

            /* Teacher cards for print */
            .teacher-card-print {
                border: 2px solid #dee2e6 !important;
                border-radius: 8px !important;
                margin-bottom: 15px !important;
                page-break-inside: avoid;
                background: white !important;
            }

            .teacher-header-print {
                background: linear-gradient(135deg, #006747 0%, #004d35 100%) !important;
                color: white !important;
                padding: 10px !important;
                border-radius: 8px 8px 0 0 !important;
                font-weight: bold !important;
            }

            .teacher-body-print {
                padding: 10px !important;
            }

            .workload-stats-print {
                display: flex !important;
                justify-content: space-around !important;
                background: #f8f9fa !important;
                padding: 8px !important;
                border-radius: 5px !important;
                margin-bottom: 10px !important;
            }

            .stat-item {
                text-align: center !important;
                flex: 1 !important;
            }

            .stat-value {
                font-weight: bold !important;
                font-size: 12pt !important;
                color: #006747 !important;
            }

            .stat-desc {
                font-size: 9pt !important;
                color: #666 !important;
            }

            .routines-print {
                font-size: 10pt !important;
            }

            .routine-item-print {
                border: 1px solid #e9ecef !important;
                border-radius: 4px !important;
                padding: 6px !important;
                margin: 3px 0 !important;
                background: #f8f9fa !important;
            }

            .subject-info-print {
                font-weight: bold !important;
                font-size: 10pt !important;
                color: #006747 !important;
            }

            .teacher-info-print {
                font-size: 9pt !important;
                color: #666 !important;
            }

            .time-display-print {
                font-weight: bold !important;
                color: #006747 !important;
                font-size: 10pt !important;
            }

            /* Footer */
            .print-footer {
                text-align: center;
                border-top: 2px solid #006747;
                padding-top: 10px;
                margin-top: 20px;
                font-size: 10pt;
                color: #666;
            }

            /* Page breaks */
            .page-break {
                page-break-before: always;
            }

            .no-page-break {
                page-break-inside: avoid;
            }

            /* Responsive table for print */
            .print-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 15px;
            }

            .print-table th,
            .print-table td {
                border: 1px solid #dee2e6;
                padding: 6px;
                text-align: left;
                font-size: 10pt;
            }

            .print-table th {
                background: #006747 !important;
                color: white !important;
                font-weight: bold;
            }

            /* Workload indicators */
            .workload-normal { background: #d4edda !important; }
            .workload-overloaded { background: #f8d7da !important; }
            .workload-underloaded { background: #fff3cd !important; }
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="index.php">
                <i class="fas fa-cogs"></i> অ্যাডমিন প্যানেল
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php">
                    <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-balance-scale"></i> শিক্ষকের ডিউটি ম্যানেজমেন্ট</h2>
                    <div>
                        <button class="btn btn-info btn-sm me-2" onclick="printReport()">
                            <i class="fas fa-print"></i> রিপোর্ট প্রিন্ট (A4)
                        </button>
                        <button class="btn btn-secondary btn-sm" onclick="window.print()">
                            <i class="fas fa-print"></i> সাধারণ প্রিন্ট
                        </button>
                    </div>
                </div>

                <?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; ?>

                <!-- Workload Statistics -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card stats-card text-white">
                            <div class="card-body text-center">
                                <i class="fas fa-users fa-2x mb-2"></i>
                                <h4><?php echo $workload_stats['total_teachers']; ?></h4>
                                <p class="mb-0">মোট শিক্ষক</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stats-card text-white">
                            <div class="card-body text-center">
                                <i class="fas fa-chart-line fa-2x mb-2"></i>
                                <h4><?php echo $workload_stats['avg_classes_per_teacher']; ?></h4>
                                <p class="mb-0">গড় ক্লাস/শিক্ষক</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stats-card text-white">
                            <div class="card-body text-center">
                                <i class="fas fa-clock fa-2x mb-2"></i>
                                <h4><?php echo $workload_stats['avg_hours_per_teacher']; ?>h</h4>
                                <p class="mb-0">গড় ঘণ্টা/শিক্ষক</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stats-card text-white">
                            <div class="card-body text-center">
                                <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                                <h4><?php echo $workload_stats['overloaded_teachers']; ?></h4>
                                <p class="mb-0">ওভারলোডেড শিক্ষক</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bulk Actions Bar - Only show if there are multiple teachers -->
                <?php if (count($teachers) > 1): ?>
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center flex-wrap">
                                    <div class="d-flex gap-3 mb-2 mb-md-0">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="selectAllTeachers" onchange="toggleAllTeachers(this.checked)">
                                            <label class="form-check-label fw-bold" for="selectAllTeachers">
                                                <i class="fas fa-check-square"></i> সব শিক্ষক সিলেক্ট করুন
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="selectOverloadedTeachers" onchange="toggleOverloadedTeachers(this.checked)">
                                            <label class="form-check-label fw-bold text-danger" for="selectOverloadedTeachers">
                                                <i class="fas fa-exclamation-triangle"></i> শুধু ওভারলোডেড শিক্ষক
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="selectUnderloadedTeachers" onchange="toggleUnderloadedTeachers(this.checked)">
                                            <label class="form-check-label fw-bold text-warning" for="selectUnderloadedTeachers">
                                                <i class="fas fa-exclamation-circle"></i> শুধু আন্ডারলোডেড শিক্ষক
                                            </label>
                                        </div>
                                    </div>
                                    <div>
                                        <button type="button" class="btn btn-danger btn-sm" id="bulkResetBtn" onclick="confirmBulkReset()" disabled>
                                            <i class="fas fa-trash-alt"></i> সিলেক্টেড শিক্ষকদের রিসেট করুন
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <strong>বাল্ক রিসেট:</strong> একাধিক শিক্ষক থাকলে এখানে বাল্ক রিসেট অপশন দেখানো হবে।
                            বর্তমানে <?php echo count($teachers); ?> জন শিক্ষক আছেন।
                        </div>
                    </div>
                </div>
                <?php endif; ?>

               

                <!-- Screen View Teacher Table -->
                <div class="screen-view">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h4><i class="fas fa-table"></i> শিক্ষকের ডিউটি ম্যানেজমেন্ট রিপোর্ট</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <strong>তৈরির তারিখ:</strong> <?php echo date('d/m/Y H:i:s'); ?> | 
                                <strong>মোট শিক্ষক:</strong> <?php echo count($teachers); ?> জন
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-3">
                                    <div class="alert alert-info text-center">
                                        <strong><?php echo $workload_stats['total_teachers']; ?></strong><br>
                                        মোট শিক্ষক
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="alert alert-secondary text-center">
                                        <strong><?php echo $workload_stats['avg_classes_per_teacher']; ?></strong><br>
                                        গড় ক্লাস/শিক্ষক
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="alert alert-secondary text-center">
                                        <strong><?php echo $workload_stats['avg_hours_per_teacher']; ?>h</strong><br>
                                        গড় ঘণ্টা/শিক্ষক
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="alert alert-warning text-center">
                                        <strong><?php echo $workload_stats['overloaded_teachers']; ?></strong><br>
                                        ওভারলোডেড শিক্ষক
                                    </div>
                                </div>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th style="width: 5%;">#</th>
                                            <th style="width: 20%;">শিক্ষকের নাম</th>
                                            <th style="width: 15%;">আইডি</th>
                                            <th style="width: 10%;">ক্লাস</th>
                                            <th style="width: 10%;">বিষয়</th>
                                            <th style="width: 10%;">ঘণ্টা</th>
                                            <th style="width: 15%;">ওয়ার্কলোড</th>
                                            <th style="width: 15%;">বর্তমান ক্লাসসমূহ</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($teachers as $index => $teacher):
                                            $total_hours = round($teacher['total_minutes'] / 60, 1);
                                            $workload_status = 'স্বাভাবিক';
                                            $workload_class = '';

                                            if ($teacher['total_classes'] > 25 || $total_hours > 30) {
                                                $workload_status = 'ওভারলোডেড';
                                                $workload_class = 'table-danger';
                                            } elseif ($teacher['total_classes'] < 10 || $total_hours < 15) {
                                                $workload_status = 'আন্ডারলোডেড';
                                                $workload_class = 'table-warning';
                                            } else {
                                                $workload_class = 'table-success';
                                            }
                                        ?>
                                        <tr class="<?php echo $workload_class; ?>">
                                            <td><?php echo $index + 1; ?></td>
                                            <td><?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?></td>
                                            <td><?php echo htmlspecialchars($teacher['employee_id']); ?></td>
                                            <td><?php echo $teacher['total_classes']; ?></td>
                                            <td><?php echo $teacher['total_subjects']; ?></td>
                                            <td><?php echo $total_hours; ?>h</td>
                                            <td><?php echo $workload_status; ?></td>
                                            <td>
                                                <?php
                                                $routines = isset($teacher_workloads[$teacher['id']]) ? $teacher_workloads[$teacher['id']] : [];
                                                if (!empty($routines)) {
                                                    $subjects = [];
                                                    foreach ($routines as $routine) {
                                                        $subjects[] = htmlspecialchars($routine['subject_name']) . ' (' . htmlspecialchars($days_map[$routine['day_of_week']] ?? $routine['day_of_week']) . ')';
                                                    }
                                                    echo implode(', ', array_slice($subjects, 0, 3)); // Show first 3 subjects
                                                    if (count($subjects) > 3) {
                                                        echo '...';
                                                    }
                                                } else {
                                                    echo 'কোন ক্লাস নেই';
                                                }
                                                ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Print Footer -->
                <div class="print-only print-footer">
                    <p>এই রিপোর্টটি স্বয়ংক্রিয়ভাবে তৈরি করা হয়েছে | <?php echo date('d/m/Y H:i:s'); ?></p>
                </div>

                <!-- Teachers List (Screen View) -->
                <div class="row no-print">
                    <?php foreach ($teachers as $teacher): ?>
                        <?php
                        $total_hours = round($teacher['total_minutes'] / 60, 1);
                        $workload_class = 'normal-load';

                        if ($teacher['total_classes'] > 25 || $total_hours > 30) {
                            $workload_class = 'overloaded';
                        } elseif ($teacher['total_classes'] < 10 || $total_hours < 15) {
                            $workload_class = 'underloaded';
                        }
                        ?>
                        <div class="col-md-6">
                            <div class="card teacher-card">
                                <div class="card-header teacher-header <?php echo $workload_class; ?>" data-workload-class="<?php echo $workload_class; ?>">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <div class="form-check mb-0">
                                                <input class="form-check-input teacher-checkbox" type="checkbox" name="selected_teachers[]" value="<?php echo $teacher['id']; ?>" id="teacher-<?php echo $teacher['id']; ?>-check" onchange="updateBulkButton()">
                                                <label class="form-check-label text-white" for="teacher-<?php echo $teacher['id']; ?>-check">
                                                    <h5 class="mb-0">
                                                        <i class="fas fa-user-graduate"></i>
                                                        <?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?>
                                                    </h5>
                                                    <small>আইডি: <?php echo htmlspecialchars($teacher['employee_id']); ?> | <?php echo htmlspecialchars($teacher['designation']); ?></small>
                                                </label>
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <button class="btn btn-light btn-sm" type="button" data-bs-toggle="collapse" data-bs-target="#teacher-<?php echo $teacher['id']; ?>" aria-expanded="false">
                                                <i class="fas fa-chevron-down"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="workload-stats">
                                        <div class="row text-center">
                                            <div class="col-4">
                                                <strong><?php echo $teacher['total_classes']; ?></strong><br>
                                                <small>ক্লাস</small>
                                            </div>
                                            <div class="col-4">
                                                <strong><?php echo $teacher['total_subjects']; ?></strong><br>
                                                <small>বিষয়</small>
                                            </div>
                                            <div class="col-4">
                                                <strong><?php echo $total_hours; ?>h</strong><br>
                                                <small>ঘণ্টা/সপ্তাহ</small>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="d-flex justify-content-between mb-3">
                                        <div>
                                            <?php if ($teacher['total_routines'] > 0): ?>
                                                <button class="btn btn-danger btn-sm action-btn" data-bs-toggle="modal" data-bs-target="#resetModal" data-teacher-id="<?php echo $teacher['id']; ?>" data-teacher-name="<?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?>">
                                                    <i class="fas fa-trash-alt"></i> সব ক্লাস রিসেট
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                        <div>
                                            <a href="teachers/routine.php?teacher_id=<?php echo $teacher['id']; ?>" class="btn btn-primary btn-sm action-btn" target="_blank">
                                                <i class="fas fa-calendar-alt"></i> রুটিন দেখুন
                                            </a>
                                        </div>
                                    </div>

                                    <div class="collapse" id="teacher-<?php echo $teacher['id']; ?>">
                                        <h6>বর্তমান ক্লাসসমূহ:</h6>
                                        <?php if (!empty($teacher_workloads[$teacher['id']])): ?>
                                            <?php foreach ($teacher_workloads[$teacher['id']] as $routine): ?>
                                                <div class="routine-item">
                                                    <div class="d-flex justify-content-between align-items-start">
                                                        <div class="flex-grow-1">
                                                            <div class="d-flex justify-content-between">
                                                                <strong><?php echo htmlspecialchars($routine['subject_name']); ?> (<?php echo htmlspecialchars($routine['subject_code']); ?>)</strong>
                                                                <span class="subject-badge"><?php echo htmlspecialchars($days_map[$routine['day_of_week']] ?? $routine['day_of_week']); ?></span>
                                                            </div>
                                                            <div class="text-muted small">
                                                                <?php echo htmlspecialchars($routine['class_name'] . ' - ' . $routine['class_section']); ?>
                                                                <?php if (!empty($routine['room_number'])): ?>
                                                                    | রুম: <?php echo htmlspecialchars($routine['room_number']); ?>
                                                                <?php endif; ?>
                                                            </div>
                                                            <div class="time-display">
                                                                <?php echo date('h:i A', strtotime($routine['start_time'])); ?> - <?php echo date('h:i A', strtotime($routine['end_time'])); ?>
                                                                (<?php echo $routine['duration_minutes']; ?> মিনিট)
                                                            </div>
                                                        </div>
                                                        <div class="ms-2">
                                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিত যে আপনি এই ক্লাস রিমুভ করতে চান?')">
                                                                <input type="hidden" name="action" value="adjust_duty">
                                                                <input type="hidden" name="teacher_id" value="<?php echo $teacher['id']; ?>">
                                                                <input type="hidden" name="adjustment_type" value="remove_class">
                                                                <input type="hidden" name="routine_id" value="<?php echo $routine['id']; ?>">
                                                                <button type="submit" class="btn btn-outline-danger btn-sm action-btn" title="এই ক্লাস রিমুভ করুন">
                                                                    <i class="fas fa-minus"></i>
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <p class="text-muted">কোন ক্লাস অ্যাসাইন করা হয়নি</p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Reset Schedule Modal -->
    <div class="modal fade" id="resetModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-exclamation-triangle text-warning"></i> শিডিউল রিসেট</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="reset_teacher_schedule">
                        <input type="hidden" name="teacher_id" id="reset_teacher_id" value="">

                        <div class="alert alert-danger">
                            <strong>সতর্কতা!</strong> এই অ্যাকশন শিক্ষকের সকল ক্লাস রিমুভ করে দেবে।
                        </div>

                        <p>আপনি কি নিশ্চিত যে <strong id="reset_teacher_name"></strong> এর সকল ক্লাস রিসেট করতে চান?</p>
                        <p class="text-danger"><strong>এই কাজটি পূর্বাবস্থায় ফেরানো যাবে না।</strong></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-danger">রিসেট করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bulk Reset Modal -->
    <div class="modal fade" id="bulkResetModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-exclamation-triangle text-danger"></i> বাল্ক শিডিউল রিসেট</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="bulkResetForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="bulk_reset_teacher_schedules">

                        <div class="alert alert-danger">
                            <strong>সতর্কতা!</strong> এই অ্যাকশন নির্বাচিত শিক্ষকদের সকল ক্লাস রিমুভ করে দেবে।
                        </div>

                        <div id="selectedTeachersList">
                            <!-- Selected teachers will be listed here by JavaScript -->
                        </div>

                        <p>আপনি কি নিশ্চিত যে উপরের <strong id="selectedCount">0</strong> জন শিক্ষকের সকল ক্লাস রিসেট করতে চান?</p>
                        <p class="text-danger"><strong>এই কাজটি পূর্বাবস্থায় ফেরানো যাবে না।</strong></p>

                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="confirmBulkReset" required>
                            <label class="form-check-label" for="confirmBulkReset">
                                হ্যাঁ, আমি নিশ্চিত যে এই অ্যাকশন সম্পন্ন করতে চাই
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-danger" id="confirmBulkResetBtn" disabled>
                            <i class="fas fa-trash-alt"></i> রিসেট করুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Handle reset modal data
        document.querySelectorAll('[data-bs-toggle="modal"]').forEach(button => {
            button.addEventListener('click', function() {
                if (this.getAttribute('data-bs-target') === '#resetModal') {
                    const teacherId = this.getAttribute('data-teacher-id');
                    const teacherName = this.getAttribute('data-teacher-name');

                    document.getElementById('reset_teacher_id').value = teacherId;
                    document.getElementById('reset_teacher_name').textContent = teacherName;
                }
            });
        });

        // Bulk selection functions
        function toggleAllTeachers(checked) {
            // Uncheck other filter checkboxes
            document.getElementById('selectOverloadedTeachers').checked = false;
            document.getElementById('selectUnderloadedTeachers').checked = false;

            const checkboxes = document.querySelectorAll('.teacher-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = checked;
            });
            updateBulkButton();
        }

        function toggleOverloadedTeachers(checked) {
            // Uncheck other filter checkboxes
            document.getElementById('selectAllTeachers').checked = false;
            document.getElementById('selectUnderloadedTeachers').checked = false;

            const overloadedCards = document.querySelectorAll('.card-header.overloaded');
            overloadedCards.forEach(card => {
                const checkbox = card.querySelector('.teacher-checkbox');
                if (checkbox) {
                    checkbox.checked = checked;
                }
            });
            updateBulkButton();
        }

        function toggleUnderloadedTeachers(checked) {
            // Uncheck other filter checkboxes
            document.getElementById('selectAllTeachers').checked = false;
            document.getElementById('selectOverloadedTeachers').checked = false;

            const underloadedCards = document.querySelectorAll('.card-header.underloaded');
            underloadedCards.forEach(card => {
                const checkbox = card.querySelector('.teacher-checkbox');
                if (checkbox) {
                    checkbox.checked = checked;
                }
            });
            updateBulkButton();
        }

        function updateBulkButton() {
            const checkboxes = document.querySelectorAll('.teacher-checkbox:checked');
            const bulkBtn = document.getElementById('bulkResetBtn');

            if (checkboxes.length > 0) {
                bulkBtn.disabled = false;
                bulkBtn.innerHTML = `<i class="fas fa-trash-alt"></i> ${checkboxes.length} জন শিক্ষক রিসেট করুন`;
            } else {
                bulkBtn.disabled = true;
                bulkBtn.innerHTML = `<i class="fas fa-trash-alt"></i> সিলেক্টেড শিক্ষকদের রিসেট করুন`;
            }
        }

        function confirmBulkReset() {
            const selectedCheckboxes = document.querySelectorAll('.teacher-checkbox:checked');
            if (selectedCheckboxes.length === 0) {
                alert('কোন শিক্ষক নির্বাচন করা হয়নি!');
                return;
            }

            // Get selected teacher names
            const selectedTeachers = [];
            selectedCheckboxes.forEach(checkbox => {
                const teacherCard = checkbox.closest('.teacher-card');
                const teacherName = teacherCard.querySelector('.form-check-label h5').textContent.trim();
                selectedTeachers.push(teacherName);
            });

            // Update modal content
            document.getElementById('selectedCount').textContent = selectedTeachers.length;

            const teacherList = document.getElementById('selectedTeachersList');
            teacherList.innerHTML = '<h6>নির্বাচিত শিক্ষকগণ:</h6><ul class="list-group list-group-flush mb-3">';
            selectedTeachers.forEach(name => {
                teacherList.innerHTML += `<li class="list-group-item">${name}</li>`;
            });
            teacherList.innerHTML += '</ul>';

            // Clear form and show modal
            document.getElementById('bulkResetForm').reset();
            document.getElementById('confirmBulkResetBtn').disabled = true;

            const modal = new bootstrap.Modal(document.getElementById('bulkResetModal'));
            modal.show();
        }

        // Handle bulk reset confirmation checkbox
        document.getElementById('confirmBulkReset').addEventListener('change', function() {
            document.getElementById('confirmBulkResetBtn').disabled = !this.checked;
        });

        // Add selected teachers to form before submission
        document.getElementById('bulkResetForm').addEventListener('submit', function(e) {
            // Clear any existing hidden inputs
            this.querySelectorAll('input[name="selected_teachers[]"]').forEach(input => input.remove());

            // Add selected teacher IDs as hidden inputs
            const selectedCheckboxes = document.querySelectorAll('.teacher-checkbox:checked');
            selectedCheckboxes.forEach(checkbox => {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'selected_teachers[]';
                hiddenInput.value = checkbox.value;
                this.appendChild(hiddenInput);
            });
        });

        // Print report function
        function printReport() {
            // Temporarily show print-only content and hide screen content
            const printOnlyElements = document.querySelectorAll('.print-only');
            const noPrintElements = document.querySelectorAll('.no-print');

            // Show print elements
            printOnlyElements.forEach(el => {
                el.style.display = 'block';
            });

            // Hide screen elements
            noPrintElements.forEach(el => {
                el.style.display = 'none';
            });

            // Print the page
            window.print();

            // Restore original display after printing
            setTimeout(() => {
                printOnlyElements.forEach(el => {
                    el.style.display = '';
                });
                noPrintElements.forEach(el => {
                    el.style.display = '';
                });
            }, 1000);
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateBulkButton();

            // If only one teacher exists, hide bulk options and show message
            const teacherCount = document.querySelectorAll('.teacher-card').length;
            if (teacherCount <= 1) {
                const bulkActionsBar = document.querySelector('.row.mb-3');
                if (bulkActionsBar && bulkActionsBar.querySelector('.alert')) {
                    // Already showing the info message
                }
            }
        });
    </script>
</body>
</html>
