<?php
session_start();

// Handle success message from PRG pattern
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

// 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'];
$user_name = $_SESSION['user_name'] ?? $_SESSION['username'] ?? 'অ্যাডমিন';

// Ensure teacher_leaves table exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS teacher_leaves (
        id INT AUTO_INCREMENT PRIMARY KEY,
        teacher_id INT NOT NULL,
        leave_type ENUM('sick', 'casual', 'annual', 'maternity', 'medical', 'other') NOT NULL,
        start_date DATE NOT NULL,
        end_date DATE NOT NULL,
        reason TEXT NOT NULL,
        status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
        applied_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        approved_by INT NULL,
        approved_date TIMESTAMP NULL,
        remarks TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (teacher_id) REFERENCES teachers(id) ON DELETE CASCADE,
        FOREIGN KEY (approved_by) REFERENCES users(id) ON DELETE SET NULL
    )");
} catch (Exception $e) {
    $error_message = "Database setup error: " . $e->getMessage();
}

// Handle edit, delete, approval/rejection
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'edit_leave' && isset($_POST['leave_id'])) {
        $leave_id = (int)$_POST['leave_id'];
        $teacher_id = (int)$_POST['teacher_id'];
        $leave_type = $_POST['leave_type'];
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $reason = trim($_POST['reason']);
        $status = $_POST['status'];

        // Validation
        if (empty($teacher_id) || empty($leave_type) || empty($start_date) || empty($end_date) || empty($reason)) {
            $error_message = 'সব ক্ষেত্র পূরণ করুন';
        } elseif (strtotime($end_date) < strtotime($start_date)) {
            $error_message = 'শেষ তারিখ শুরুর তারিখের পরে হতে হবে';
        }

        if (empty($error_message)) {
            try {
                $stmt = $pdo->prepare("UPDATE teacher_leaves SET teacher_id = ?, leave_type = ?, start_date = ?, end_date = ?, reason = ?, status = ?, updated_at = NOW() WHERE id = ?");
                $result = $stmt->execute([$teacher_id, $leave_type, $start_date, $end_date, $reason, $status, $leave_id]);

                if ($result) {
                    $message = 'ছুটির আবেদন সফলভাবে আপডেট করা হয়েছে।';
                    // Use PRG pattern to prevent resubmission on refresh
                    $_SESSION['success_message'] = $message;
                    header('Location: ' . $_SERVER['PHP_SELF'] . ($_GET ? '?' . http_build_query($_GET) : ''));
                    exit();
                } else {
                    $error_message = 'আপডেট করতে সমস্যা হয়েছে।';
                }
            } catch (Exception $e) {
                $error_message = 'ত্রুটি: ' . $e->getMessage();
            }
        }
    } elseif ($_POST['action'] === 'delete_leave' && isset($_POST['leave_id'])) {
        $leave_id = (int)$_POST['leave_id'];

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

            if ($result) {
                $message = 'ছুটির আবেদন সফলভাবে মুছে ফেলা হয়েছে।';
                // Use PRG pattern to prevent resubmission on refresh
                $_SESSION['success_message'] = $message;
                header('Location: ' . $_SERVER['PHP_SELF'] . ($_GET ? '?' . http_build_query($_GET) : ''));
                exit();
            } else {
                $error_message = 'মুছে ফেলতে সমস্যা হয়েছে।';
            }
        } catch (Exception $e) {
            $error_message = 'ত্রুটি: ' . $e->getMessage();
        }
    } elseif ($_POST['action'] === 'approve' || $_POST['action'] === 'reject') {
        try {
            $action = $_POST['action'];
            $leave_id = (int)$_POST['leave_id'];
            $remarks = trim($_POST['remarks'] ?? '');

            $status = $action === 'approve' ? 'approved' : 'rejected';
            $stmt = $pdo->prepare("UPDATE teacher_leaves SET status = ?, approved_by = ?, approved_date = NOW(), remarks = ? WHERE id = ?");
            $result = $stmt->execute([$status, $user_id, $remarks, $leave_id]);

            if ($result) {
                $message = $action === 'approve' ? 'ছুটি অনুমোদন করা হয়েছে।' : 'ছুটি প্রত্যাখ্যান করা হয়েছে।';
                // Use PRG pattern to prevent resubmission on refresh
                $_SESSION['success_message'] = $message;
                header('Location: ' . $_SERVER['PHP_SELF'] . ($_GET ? '?' . http_build_query($_GET) : ''));
                exit();
            } else {
                $error_message = 'অ্যাকশন সম্পন্ন করতে সমস্যা হয়েছে।';
            }
        } catch (Exception $e) {
            $error_message = 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

// Handle bulk approve
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'bulk_approve') {
    if (!isset($_POST['selected_leaves']) || empty($_POST['selected_leaves'])) {
        $error_message = 'কোনো আবেদন নির্বাচিত হয়নি।';
    } else {
        $selected_leaves = json_decode($_POST['selected_leaves'], true);
        $remarks = trim($_POST['bulk_remarks'] ?? '');
        $success_count = 0;
        $error_count = 0;

        foreach ($selected_leaves as $leave_id) {
            try {
                $stmt = $pdo->prepare("UPDATE teacher_leaves SET status = 'approved', approved_by = ?, approved_date = NOW(), remarks = ? WHERE id = ? AND status = 'pending'");
                $result = $stmt->execute([$user_id, $remarks, $leave_id]);
                if ($result && $stmt->rowCount() > 0) {
                    $success_count++;
                } else {
                    $error_count++;
                }
            } catch (Exception $e) {
                $error_count++;
            }
        }

        if ($success_count > 0) {
            $message = "{$success_count} টি ছুটির আবেদন সফলভাবে অনুমোদন করা হয়েছে।";
            if ($error_count > 0) {
                $message .= " {$error_count} টি আবেদন প্রসেস করতে সমস্যা হয়েছে।";
            }
            $_SESSION['success_message'] = $message;
        } else {
            $error_message = 'কোনো আবেদন অনুমোদন করা যায়নি।';
        }

        header('Location: ' . $_SERVER['PHP_SELF'] . ($_GET ? '?' . http_build_query($_GET) : ''));
        exit();
    }
}

// Handle bulk reject
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'bulk_reject') {
    if (!isset($_POST['selected_leaves']) || empty($_POST['selected_leaves'])) {
        $error_message = 'কোনো আবেদন নির্বাচিত হয়নি।';
    } elseif (!isset($_POST['bulk_remarks']) || empty(trim($_POST['bulk_remarks']))) {
        $error_message = 'প্রত্যাখ্যানের কারণ উল্লেখ করুন।';
    } else {
        $selected_leaves = json_decode($_POST['selected_leaves'], true);
        $remarks = trim($_POST['bulk_remarks']);
        $success_count = 0;
        $error_count = 0;

        foreach ($selected_leaves as $leave_id) {
            try {
                $stmt = $pdo->prepare("UPDATE teacher_leaves SET status = 'rejected', approved_by = ?, approved_date = NOW(), remarks = ? WHERE id = ? AND status = 'pending'");
                $result = $stmt->execute([$user_id, $remarks, $leave_id]);
                if ($result && $stmt->rowCount() > 0) {
                    $success_count++;
                } else {
                    $error_count++;
                }
            } catch (Exception $e) {
                $error_count++;
            }
        }

        if ($success_count > 0) {
            $message = "{$success_count} টি ছুটির আবেদন সফলভাবে প্রত্যাখ্যান করা হয়েছে।";
            if ($error_count > 0) {
                $message .= " {$error_count} টি আবেদন প্রসেস করতে সমস্যা হয়েছে।";
            }
            $_SESSION['success_message'] = $message;
        } else {
            $error_message = 'কোনো আবেদন প্রত্যাখ্যান করা যায়নি।';
        }

        header('Location: ' . $_SERVER['PHP_SELF'] . ($_GET ? '?' . http_build_query($_GET) : ''));
        exit();
    }
}

// Handle reset all leaves
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reset_all') {
    if (!isset($_POST['confirm_reset']) || $_POST['confirm_reset'] !== '1') {
        $error_message = 'অননুমোদিত অ্যাকশন।';
    } elseif (!isset($_POST['reset_confirmation']) || strtoupper(trim($_POST['reset_confirmation'])) !== 'RESET') {
        $error_message = 'কনফার্মেশন টেক্সট সঠিক নয়।';
    } else {
        try {
            // Reset all leave applications to pending status and clear approval data
            $stmt = $pdo->prepare("UPDATE teacher_leaves SET status = 'pending', approved_by = NULL, approved_date = NULL, remarks = NULL, updated_at = NOW()");
            $result = $stmt->execute();

            if ($result) {
                $affected_rows = $stmt->rowCount();
                $message = "সকল শিক্ষকের ছুটি রিসেট করা হয়েছে। {$affected_rows} টি আবেদন পুনরায় অমীমাংসিত করা হয়েছে।";
                // Use PRG pattern to prevent resubmission on refresh
                $_SESSION['success_message'] = $message;
                header('Location: ' . $_SERVER['PHP_SELF'] . ($_GET ? '?' . http_build_query($_GET) : ''));
                exit();
            } else {
                $error_message = 'ছুটি রিসেট করতে সমস্যা হয়েছে।';
            }
        } catch (Exception $e) {
            $error_message = 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

// Get search/filter parameters
$selected_session = $_GET['session'] ?? '';
$selected_month = $_GET['month'] ?? '';
$show_rejected = isset($_GET['show_rejected']) && $_GET['show_rejected'] === '1';

// Validate parameters
if (!empty($selected_session) && !is_numeric($selected_session)) {
    $selected_session = '';
}
if (!empty($selected_month) && (!is_numeric($selected_month) || $selected_month < 1 || $selected_month > 12)) {
    $selected_month = '';
}

// Get available academic sessions
$available_sessions = [];
try {
    $stmt = $pdo->prepare("SELECT id, session_name, start_date, end_date FROM academic_sessions WHERE status = 'active' ORDER BY start_date DESC");
    $stmt->execute();
    $available_sessions = $stmt->fetchAll();
} catch (Exception $e) {
    $error_message = "সেশন লোড করতে সমস্যা হয়েছে: " . htmlspecialchars($e->getMessage());
}

// Get leave applications with filters
$status_condition = $show_rejected ? "" : " AND tl.status != 'rejected'";
$where_conditions = ["1=1{$status_condition}"];
$params = [];

if (!empty($selected_session)) {
    // Check if leave overlaps with the selected year
    $where_conditions[] = "(YEAR(tl.start_date) <= ? AND YEAR(tl.end_date) >= ?)";
    $params[] = $selected_session;
    $params[] = $selected_session;
}

if (!empty($selected_month)) {
    $current_year = !empty($selected_session) ? $selected_session : date('Y');

    // Create date range for the selected month
    $month_start = sprintf('%04d-%02d-01', $current_year, $selected_month);
    $month_end = date('Y-m-t', strtotime($month_start)); // Last day of month

    // Check if leave overlaps with the selected month
    $where_conditions[] = "(
        (tl.start_date <= ? AND tl.end_date >= ?) OR
        (tl.start_date BETWEEN ? AND ?) OR
        (tl.end_date BETWEEN ? AND ?)
    )";
    $params[] = $month_end;   // leave ends after month starts
    $params[] = $month_start; // leave starts before month ends
    $params[] = $month_start; // leave starts within month
    $params[] = $month_end;   // leave starts within month
    $params[] = $month_start; // leave ends within month
    $params[] = $month_end;   // leave ends within month
}

$where_clause = implode(" AND ", $where_conditions);
$stmt = $pdo->prepare("
    SELECT tl.*, t.first_name, t.last_name, t.employee_id
    FROM teacher_leaves tl
    LEFT JOIN teachers t ON tl.teacher_id = t.id
    WHERE {$where_clause}
    ORDER BY tl.applied_date DESC
");
$stmt->execute($params);
$leave_applications = $stmt->fetchAll();

// Group leave applications by teacher for teacher info cards (already filtered)
$teacher_leave_data = [];
foreach ($leave_applications as $leave) {
    $teacher_id = $leave['teacher_id'];
    if (!isset($teacher_leave_data[$teacher_id])) {
        $teacher_leave_data[$teacher_id] = [
            'teacher_info' => [
                'id' => $teacher_id,
                'name' => ($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? ''),
                'employee_id' => $leave['employee_id'] ?? 'N/A',
                'total_days' => 0,
                'pending_leaves' => 0,
                'approved_leaves' => 0,
                'rejected_leaves' => 0,
                'total_applications' => 0
            ],
            'leaves' => []
        ];
    }

    // Add leave to teacher's collection
    $teacher_leave_data[$teacher_id]['leaves'][] = $leave;

    // Calculate days for this leave
    $start_date = new DateTime($leave['start_date']);
    $end_date = new DateTime($leave['end_date']);
    $days = $start_date->diff($end_date)->days + 1; // +1 because inclusive

    // Update statistics
    $teacher_leave_data[$teacher_id]['teacher_info']['total_applications']++;
    $teacher_leave_data[$teacher_id]['teacher_info']['total_days'] += $days;

    switch ($leave['status']) {
        case 'pending':
            $teacher_leave_data[$teacher_id]['teacher_info']['pending_leaves']++;
            break;
        case 'approved':
            $teacher_leave_data[$teacher_id]['teacher_info']['approved_leaves']++;
            break;
        case 'rejected':
            $teacher_leave_data[$teacher_id]['teacher_info']['rejected_leaves']++;
            break;
    }
}
?>

<!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;
            direction: ltr;
            font-family: 'Noto Sans Bengali', 'Siyam Rupali', Arial, sans-serif;
            font-size: 16px;
            line-height: 1.6;
        }
        html {
            direction: ltr;
        }
        .form-control, .form-select, .btn {
            text-align: left;
        }
        .form-label {
            text-align: left;
            display: block;
        }
        .table {
            direction: ltr;
        }
        .table th, .table td {
            text-align: left;
        }
        .text-center {
            text-align: center !important;
        }
        .text-left {
            text-align: left !important;
        }
        .text-right {
            text-align: right !important;
        }
        /* LTR specific adjustments for Bengali */
        .card-header .fas {
            margin-right: 0.5rem;
            margin-left: 0;
        }
        .btn .fas {
            margin-right: 0.5rem;
            margin-left: 0;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
        }
        .status-approved {
            background-color: #d4edda;
            color: #155724;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
        }
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
        }
        .action-btn {
            margin: 0 2px;
        }

        /* Card View Styles */
        .leave-card {
            transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
            margin-bottom: 1rem;
            border: 1px solid #dee2e6;
            border-radius: 0.5rem;
            overflow: hidden;
        }

        .leave-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .card-header-custom {
            background: linear-gradient(135deg, #006747, #00875a);
            color: white;
            padding: 1rem;
            border-bottom: none;
        }

        .card-body-custom {
            padding: 1.25rem;
        }

        .card-info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
            flex-wrap: wrap;
        }

        .card-info-label {
            font-weight: 600;
            color: #495057;
            font-size: 0.875rem;
        }

        .card-info-value {
            color: #212529;
            font-size: 0.875rem;
        }

        .card-status {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
        }

        .card-actions {
            display: flex;
            gap: 0.25rem;
            flex-wrap: wrap;
            justify-content: flex-end;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #dee2e6;
        }

        .card-view-container {
            display: none;
        }

        .card-view-container.show {
            display: block;
        }

        .table-view-container {
            display: block;
        }

        .table-view-container.hide {
            display: none;
        }

        /* Responsive card layout */
        @media (max-width: 768px) {
            .card-info-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.25rem;
            }

            .card-actions {
                justify-content: center;
            }

            .card-actions .btn {
                flex: 1;
                min-width: 80px;
            }
        }

        /* Search highlight */
        .search-highlight {
            background-color: #fff3cd;
            padding: 0 2px;
            border-radius: 2px;
        }

        /* Teacher Information Cards Styles */
        .teacher-info-card {
            transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
            margin-bottom: 2rem;
            border: 2px solid #e9ecef;
            border-radius: 1rem;
            overflow: hidden;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        }

        .teacher-info-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            border-color: #006747;
        }

        .teacher-header {
            background: linear-gradient(135deg, #006747, #00875a);
            color: white;
            padding: 1.5rem;
            position: relative;
        }

        .teacher-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.3;
        }

        .teacher-header-content {
            position: relative;
            z-index: 1;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }

        .teacher-header-left {
            flex: 1;
        }

        .teacher-header-right {
            flex-shrink: 0;
            margin-left: 1rem;
        }

        .teacher-name {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .teacher-details {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            font-size: 0.9rem;
        }

        .teacher-stat {
            background: rgba(255,255,255,0.2);
            padding: 0.5rem 1rem;
            border-radius: 20px;
            backdrop-filter: blur(10px);
        }

        .leave-summary-section {
            padding: 1.5rem;
            background: #f8f9fa;
        }

        .leave-summary-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .leave-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .leave-stat-card {
            background: white;
            padding: 1rem;
            border-radius: 0.5rem;
            border-left: 4px solid;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .leave-stat-card.pending { border-left-color: #ffc107; }
        .leave-stat-card.approved { border-left-color: #28a745; }
        .leave-stat-card.rejected { border-left-color: #dc3545; }

        .leave-stat-number {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 0.25rem;
        }

        .leave-stat-label {
            font-size: 0.85rem;
            color: #6c757d;
            text-transform: uppercase;
            font-weight: 600;
        }

        .leave-details-section {
            padding: 1.5rem;
        }

        .leave-details-header {
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 0.75rem;
            margin-bottom: 1rem;
        }

        .leave-item {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 0.5rem;
            padding: 1rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s ease;
        }

        .leave-item:hover {
            box-shadow: 0 3px 8px rgba(0,0,0,0.1);
            border-color: #006747;
        }

        .leave-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
        }

        .leave-type-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 500;
            text-transform: uppercase;
        }

        .leave-type-badge.sick { background: #e7f3ff; color: #0066cc; }
        .leave-type-badge.casual { background: #f0f8e7; color: #4caf50; }
        .leave-type-badge.annual { background: #fff3e0; color: #ff9800; }
        .leave-type-badge.maternity { background: #fce4ec; color: #e91e63; }
        .leave-type-badge.medical { background: #f3e5f5; color: #9c27b0; }
        .leave-type-badge.other { background: #efebe9; color: #795548; }

        .leave-dates {
            font-weight: 600;
            color: #495057;
        }

        .leave-reason {
            color: #6c757d;
            font-style: italic;
            margin: 0.5rem 0;
        }

        .leave-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .teacher-info-view-container {
            display: none;
        }

        .teacher-info-view-container.show {
            display: block;
        }

        .teacher-info-view-container.hide {
            display: none;
        }

        /* Total leaves highlight styling */
        .total-leaves-highlight {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 0.75rem 1.25rem;
            border-radius: 25px;
            box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
            display: inline-flex;
            align-items: center;
            margin-top: 0.5rem;
            animation: pulse 2s infinite;
        }

        .total-leaves-info {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.25rem;
        }

        .leaves-count {
            font-size: 0.9rem;
            font-weight: 600;
            opacity: 0.9;
            letter-spacing: 0.3px;
        }

        .leaves-days {
            font-size: 1.3rem;
            font-weight: 700;
            letter-spacing: 0.5px;
        }

        .total-leaves-highlight i {
            font-size: 1.2rem;
        }

        @keyframes pulse {
            0% {
                box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
            }
            50% {
                box-shadow: 0 4px 20px rgba(40, 167, 69, 0.5);
            }
            100% {
                box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
            }
        }

        /* Responsive design for teacher cards */
        @media (max-width: 768px) {
            .teacher-header-content {
                flex-direction: column;
                align-items: stretch;
                gap: 1rem;
            }

            .teacher-header-left,
            .teacher-header-right {
                margin-left: 0;
            }

            .teacher-header-right {
                align-self: center;
            }

            .teacher-details {
                flex-direction: column;
                gap: 0.5rem;
            }

            .total-leaves-highlight {
                padding: 0.6rem 1rem;
                margin-top: 0;
            }

            .leaves-count {
                font-size: 0.8rem;
            }

            .leaves-days {
                font-size: 1.1rem;
            }

            .leave-stats {
                grid-template-columns: 1fr;
            }

            .leave-item-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }

            .leave-actions {
                justify-content: center;
            }
        }

        /* Print Styles for Leave Applications */
        @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,
            .btn,
            .form-check,
            .navbar,
            .sidebar,
            .mobile-toggle,
            .sidebar-toggle,
            .alert,
            .modal,
            .print-controls {
                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: 20pt;
                font-weight: bold;
                margin: 0;
            }

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

            /* Table styling for print */
            .table {
                width: 100% !important;
                margin-bottom: 20px !important;
                font-size: 10pt !important;
                border-collapse: collapse !important;
            }

            .table th,
            .table td {
                border: 1px solid #dee2e6 !important;
                padding: 6px !important;
                text-align: left !important;
                vertical-align: top !important;
            }

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

            .table .text-center {
                text-align: center !important;
            }

            /* Status badges */
            .status-pending {
                background-color: #fff3cd !important;
                color: #856404 !important;
                padding: 2px 6px !important;
                border-radius: 3px !important;
                font-size: 9pt !important;
            }

            .status-approved {
                background-color: #d4edda !important;
                color: #155724 !important;
                padding: 2px 6px !important;
                border-radius: 3px !important;
                font-size: 9pt !important;
            }

            .status-rejected {
                background-color: #f8d7da !important;
                color: #721c24 !important;
                padding: 2px 6px !important;
                border-radius: 3px !important;
                font-size: 9pt !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;
            }

            /* Container adjustments */
            .container {
                max-width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }

            /* Hide empty cells or adjust layout */
            .table-responsive {
                overflow-x: visible !important;
            }

            /* Compact layout for better fit */
            .compact-info {
                font-size: 9pt !important;
                line-height: 1.2 !important;
            }
        }
    </style>
</head>
<body>
    <!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-graduation-cap me-2"></i>
                অ্যাডমিন প্যানেল
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-file-alt me-2"></i>শিক্ষক ছুটির আবেদন</h2>
            <div>
                <!-- Reset All Leaves Button -->
                <button type="button" class="btn btn-warning btn-sm me-2" data-bs-toggle="modal" data-bs-target="#resetAllModal">
                    <i class="fas fa-refresh"></i> সকল ছুটি রিসেট
                </button>
                <!-- Print Buttons -->
                <button class="btn btn-info btn-sm me-2" onclick="printReport()">
                    <i class="fas fa-print"></i> রিপোর্ট প্রিন্ট
                </button>
                <button class="btn btn-secondary btn-sm me-2" onclick="window.print()">
                    <i class="fas fa-print"></i> সাধারণ প্রিন্ট
                </button>
                <?php
                // Build URL parameters for filter preservation
                $url_params = [];
                if (!empty($selected_session)) $url_params[] = "session={$selected_session}";
                if (!empty($selected_month)) $url_params[] = "month={$selected_month}";
                $base_url = '?' . implode('&', $url_params);
                $separator = !empty($url_params) ? '&' : '?';
                ?>

                <?php if (!$show_rejected): ?>
                    <a href="<?php echo $base_url . $separator; ?>show_rejected=1" class="btn btn-outline-secondary btn-sm">
                        <i class="fas fa-eye"></i> প্রত্যাখ্যাত দেখান
                    </a>
                <?php else: ?>
                    <a href="<?php echo $base_url; ?>" class="btn btn-outline-secondary btn-sm">
                        <i class="fas fa-eye-slash"></i> প্রত্যাখ্যাত লুকান
                    </a>
                <?php endif; ?>

                <!-- Bulk Actions -->
                <div class="card mt-3" id="bulkActionsCard" style="display: none;">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <span id="selectedCount" class="fw-bold">0</span> টি আবেদন নির্বাচিত
                            </div>
                            <div>
                                <button type="button" class="btn btn-success btn-sm me-2" id="bulkApproveBtn" disabled>
                                    <i class="fas fa-check"></i> বাল্ক অনুমোদন
                                </button>
                                <button type="button" class="btn btn-danger btn-sm" id="bulkRejectBtn" disabled>
                                    <i class="fas fa-times"></i> বাল্ক প্রত্যাখ্যান
                                </button>
                                <button type="button" class="btn btn-secondary btn-sm" id="clearSelectionBtn">
                                    <i class="fas fa-times"></i> নির্বাচন পরিষ্কার
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search and View Controls -->
        <div class="row mb-4">
            <div class="col-md-8">
                <div class="input-group">
                    <span class="input-group-text"><i class="fas fa-search"></i></span>
                    <input type="text" class="form-control" id="searchInput" placeholder="শিক্ষকের নাম, কর্মচারী আইডি, ছুটির ধরন বা স্ট্যাটাস দিয়ে অনুসন্ধান করুন...">
                    <button class="btn btn-outline-secondary" type="button" id="clearSearch">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-4">
                <div class="btn-group float-end" role="group" aria-label="View Toggle">
                    <button type="button" class="btn btn-outline-primary active" id="tableViewBtn">
                        <i class="fas fa-table"></i> টেবিল ভিউ
                    </button>
                    <button type="button" class="btn btn-outline-primary" id="cardViewBtn">
                        <i class="fas fa-th"></i> কার্ড ভিউ
                    </button>
                    <button type="button" class="btn btn-outline-primary" id="teacherInfoViewBtn">
                        <i class="fas fa-user-graduate"></i> শিক্ষক তথ্য
                    </button>
                </div>
            </div>
        </div>

        <!-- Search/Filter Form -->
        <div class="card mt-4">
            <div class="card-header bg-light">
                <h5><i class="fas fa-filter"></i> অনুসন্ধান এবং ফিল্টার</h5>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">একাডেমিক সেশন</label>
                        <select class="form-control" name="session">
                            <option value="">সব সেশন</option>
                            <?php
                            // Add current year as fallback if no sessions available
                            if (empty($available_sessions)) {
                                $current_year = date('Y');
                                echo "<option value='{$current_year}' " . ($selected_session == $current_year ? 'selected' : '') . ">{$current_year}</option>";
                            } else {
                                foreach ($available_sessions as $session):
                            ?>
                                <option value="<?php echo $session['session_name']; ?>" <?php echo ($selected_session == $session['session_name']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($session['session_name']); ?>
                                </option>
                            <?php
                                endforeach;
                            }
                            ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">মাস</label>
                        <select class="form-control" name="month">
                            <option value="">সব মাস</option>
                            <option value="1" <?php echo ($selected_month == '1') ? 'selected' : ''; ?>>জানুয়ারি</option>
                            <option value="2" <?php echo ($selected_month == '2') ? 'selected' : ''; ?>>ফেব্রুয়ারি</option>
                            <option value="3" <?php echo ($selected_month == '3') ? 'selected' : ''; ?>>মার্চ</option>
                            <option value="4" <?php echo ($selected_month == '4') ? 'selected' : ''; ?>>এপ্রিল</option>
                            <option value="5" <?php echo ($selected_month == '5') ? 'selected' : ''; ?>>মে</option>
                            <option value="6" <?php echo ($selected_month == '6') ? 'selected' : ''; ?>>জুন</option>
                            <option value="7" <?php echo ($selected_month == '7') ? 'selected' : ''; ?>>জুলাই</option>
                            <option value="8" <?php echo ($selected_month == '8') ? 'selected' : ''; ?>>আগস্ট</option>
                            <option value="9" <?php echo ($selected_month == '9') ? 'selected' : ''; ?>>সেপ্টেম্বর</option>
                            <option value="10" <?php echo ($selected_month == '10') ? 'selected' : ''; ?>>অক্টোবর</option>
                            <option value="11" <?php echo ($selected_month == '11') ? 'selected' : ''; ?>>নভেম্বর</option>
                            <option value="12" <?php echo ($selected_month == '12') ? 'selected' : ''; ?>>ডিসেম্বর</option>
                        </select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <div class="d-grid gap-2 d-md-flex">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> অনুসন্ধান
                            </button>
                            <a href="leave_applications.php" class="btn btn-secondary">
                                <i class="fas fa-times"></i> পরিষ্কার
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
        <?php endif; ?>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
        <?php endif; ?>

        <!-- Print-only Report Header -->
        <div class="print-only print-header">
            <h1>শিক্ষক ছুটির আবেদন রিপোর্ট</h1>
            <p>তৈরির তারিখ: <?php echo date('d/m/Y H:i:s'); ?> |
               মোট আবেদন: <?php echo count($leave_applications); ?> টি
               <?php
               $print_filter_info = [];
               if (!empty($selected_session)) {
                   $print_filter_info[] = "সেশন: {$selected_session}";
               }
               if (!empty($selected_month)) {
                   $month_names = [
                       1 => 'জানুয়ারি', 2 => 'ফেব্রুয়ারি', 3 => 'মার্চ', 4 => 'এপ্রিল', 5 => 'মে', 6 => 'জুন',
                       7 => 'জুলাই', 8 => 'আগস্ট', 9 => 'সেপ্টেম্বর', 10 => 'অক্টোবর', 11 => 'নভেম্বর', 12 => 'ডিসেম্বর'
                   ];
                   $print_filter_info[] = "মাস: {$month_names[$selected_month]}";
               }
               if (!empty($print_filter_info)) {
                   echo ' | ফিল্টার: ' . implode(' | ', $print_filter_info);
               }
               ?>
               <?php if (!$show_rejected): ?>
                   (প্রত্যাখ্যাত আবেদন লুকানো আছে)
               <?php else: ?>
                   (সব আবেদনসহ)
               <?php endif; ?>
            </p>
        </div>

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

        <div class="alert alert-info no-print">
            <i class="fas fa-info-circle"></i>
            <?php echo count($leave_applications); ?> টি ছুটির আবেদন
            <?php
            $filter_info = [];
            if (!empty($selected_session)) {
                $filter_info[] = "সেশন: {$selected_session}";
            }
            if (!empty($selected_month)) {
                $month_names = [
                    1 => 'জানুয়ারি', 2 => 'ফেব্রুয়ারি', 3 => 'মার্চ', 4 => 'এপ্রিল', 5 => 'মে', 6 => 'জুন',
                    7 => 'জুলাই', 8 => 'আগস্ট', 9 => 'সেপ্টেম্বর', 10 => 'অক্টোবর', 11 => 'নভেম্বর', 12 => 'ডিসেম্বর'
                ];
                $filter_info[] = "মাস: {$month_names[$selected_month]}";
            }
            if (!empty($filter_info)) {
                echo ' | ফিল্টার: ' . implode(' | ', $filter_info);
            }
            ?>
            <?php if (!$show_rejected): ?>
                (প্রত্যাখ্যাত আবেদন লুকানো আছে)
            <?php else: ?>
                (সব আবেদনসহ)
            <?php endif; ?>
        </div>

        <div class="card">
            <div class="card-body">
                <!-- Table View Container -->
                <div class="table-view-container" id="tableViewContainer">
                    <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>
                                            <input type="checkbox" id="selectAllCheckboxes" class="form-check-input">
                                        </th>
                                        <th>তারিখ</th>
                                        <th>কর্মচারী আইডি</th>
                                        <th>শিক্ষকের নাম</th>
                                        <th>ছুটির ধরন</th>
                                        <th>তারিখসমূহ</th>
                                        <th>কারণ</th>
                                        <th>অবস্থা</th>
                                        <th>কার্যক্রম</th>
                                    </tr>
                                </thead>
                            <tbody>
                                <?php if (empty($leave_applications)): ?>
                                    <tr>
                                        <td colspan="9" class="text-center">
                                            <?php if (!$show_rejected): ?>
                                                কোনো অমীমাংসিত বা অনুমোদিত ছুটির আবেদন নেই।
                                                <a href="?show_rejected=1" class="btn btn-link btn-sm">প্রত্যাখ্যাত আবেদন দেখতে এখানে ক্লিক করুন</a>
                                            <?php else: ?>
                                                কোনো ছুটির আবেদন নেই।
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php else: ?>
                            <?php foreach ($leave_applications as $leave): ?>
                            <tr class="leave-row" data-search-text="<?php echo htmlspecialchars(strtolower(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? '') . ' ' . ($leave['employee_id'] ?? '') . ' ' . $leave['leave_type'] . ' ' . $leave['status'])); ?>">
                                <td>
                                    <input type="checkbox" class="form-check-input leave-checkbox" value="<?php echo $leave['id']; ?>" data-leave-id="<?php echo $leave['id']; ?>">
                                </td>
                                <td><?php echo date('d/m/Y', strtotime($leave['applied_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($leave['employee_id'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? '')); ?></td>
                                        <td>
                                            <?php
                                            $leave_type_display = '';
                                            switch($leave['leave_type']) {
                                                case 'sick':
                                                    $leave_type_display = 'অসুস্থতা জনিত';
                                                    break;
                                                case 'casual':
                                                    $leave_type_display = 'অস্থায়ী';
                                                    break;
                                                case 'annual':
                                                    $leave_type_display = 'বার্ষিক';
                                                    break;
                                                case 'maternity':
                                                    $leave_type_display = 'মাতৃত্ব জনিত';
                                                    break;
                                                case 'medical':
                                                    $leave_type_display = 'চিকিৎসা সনদ সহ';
                                                    break;
                                                case 'other':
                                                    $leave_type_display = 'অন্যান্য';
                                                    break;
                                                default:
                                                    $leave_type_display = htmlspecialchars(ucfirst($leave['leave_type']));
                                                    break;
                                            }
                                            echo $leave_type_display;
                                            ?>
                                        </td>
                                        <td><?php echo date('d/m/Y', strtotime($leave['start_date'])); ?> - <?php echo date('d/m/Y', strtotime($leave['end_date'])); ?></td>
                                        <td><?php echo htmlspecialchars(substr($leave['reason'], 0, 50)) . (strlen($leave['reason']) > 50 ? '...' : ''); ?></td>
                                        <td>
                                            <?php
                                            $status_class = '';
                                            $status_text = '';
                                            switch($leave['status']) {
                                                case 'approved':
                                                    $status_class = 'status-approved';
                                                    $status_text = 'অনুমোদিত';
                                                    break;
                                                case 'rejected':
                                                    $status_class = 'status-rejected';
                                                    $status_text = 'প্রত্যাখ্যাত';
                                                    break;
                                                case 'pending':
                                                default:
                                                    $status_class = 'status-pending';
                                                    $status_text = 'অমীমাংসিত';
                                                    break;
                                            }
                                            ?>
                                            <span class="<?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                        </td>
                                        <td>
                                            <!-- View button - available for all applications -->
                                            <button type="button" class="btn btn-info btn-sm action-btn" data-bs-toggle="modal" data-bs-target="#viewModal"
                                                    data-leave-id="<?php echo $leave['id']; ?>"
                                                    data-teacher-id="<?php echo $leave['teacher_id']; ?>"
                                                    data-teacher-name="<?php echo htmlspecialchars(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? '')); ?>"
                                                    data-employee-id="<?php echo htmlspecialchars($leave['employee_id'] ?? 'N/A'); ?>"
                                                    data-leave-type="<?php echo $leave['leave_type']; ?>"
                                                    data-start-date="<?php echo $leave['start_date']; ?>"
                                                    data-end-date="<?php echo $leave['end_date']; ?>"
                                                    data-reason="<?php echo htmlspecialchars($leave['reason'], ENT_QUOTES); ?>"
                                                    data-status="<?php echo $leave['status']; ?>"
                                                    data-applied-date="<?php echo date('d/m/Y H:i:s', strtotime($leave['applied_date'])); ?>"
                                                    data-approved-by="<?php echo htmlspecialchars($leave['approved_by'] ? 'অ্যাডমিন' : 'N/A'); ?>"
                                                    data-approved-date="<?php echo $leave['approved_date'] ? date('d/m/Y H:i:s', strtotime($leave['approved_date'])) : 'N/A'; ?>"
                                                    data-remarks="<?php echo htmlspecialchars($leave['remarks'] ?? '', ENT_QUOTES); ?>">
                                                <i class="fas fa-eye"></i> ভিউ
                                            </button>

                                            <!-- Edit button - available for pending applications -->
                                            <button type="button" class="btn btn-primary btn-sm action-btn" data-bs-toggle="modal" data-bs-target="#editModal"
                                                    data-leave-id="<?php echo $leave['id']; ?>"
                                                    data-teacher-id="<?php echo $leave['teacher_id']; ?>"
                                                    data-teacher-name="<?php echo htmlspecialchars(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? '')); ?>"
                                                    data-leave-type="<?php echo $leave['leave_type']; ?>"
                                                    data-start-date="<?php echo $leave['start_date']; ?>"
                                                    data-end-date="<?php echo $leave['end_date']; ?>"
                                                    data-reason="<?php echo htmlspecialchars($leave['reason'], ENT_QUOTES); ?>"
                                                    data-status="<?php echo $leave['status']; ?>">
                                                <i class="fas fa-edit"></i> এডিট
                                            </button>

                                            <?php if ($leave['status'] === 'pending'): ?>
                                                <!-- Approve button -->
                                                <button type="button" class="btn btn-success btn-sm action-btn" data-bs-toggle="modal" data-bs-target="#approveModal" data-leave-id="<?php echo $leave['id']; ?>" data-teacher-name="<?php echo htmlspecialchars(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? '')); ?>" data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                    <i class="fas fa-check"></i> অনুমোদন
                                                </button>

                                                <!-- Reject button -->
                                                <button type="button" class="btn btn-danger btn-sm action-btn" data-bs-toggle="modal" data-bs-target="#rejectModal" data-leave-id="<?php echo $leave['id']; ?>" data-teacher-name="<?php echo htmlspecialchars(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? '')); ?>" data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                    <i class="fas fa-times"></i> প্রত্যাখ্যান
                                                </button>

                                                <!-- Delete button -->
                                                <button type="button" class="btn btn-warning btn-sm action-btn" data-bs-toggle="modal" data-bs-target="#deleteModal"
                                                        data-leave-id="<?php echo $leave['id']; ?>"
                                                        data-teacher-name="<?php echo htmlspecialchars(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? '')); ?>"
                                                        data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                    <i class="fas fa-trash"></i> ডিলেট
                                                </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Card View Container -->
                <div class="card-view-container" id="cardViewContainer">
                    <?php if (empty($leave_applications)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">
                                <?php if (!$show_rejected): ?>
                                    কোনো অমীমাংসিত বা অনুমোদিত ছুটির আবেদন নেই।
                                    <br><a href="?show_rejected=1" class="btn btn-link">প্রত্যাখ্যাত আবেদন দেখতে এখানে ক্লিক করুন</a>
                                <?php else: ?>
                                    কোনো ছুটির আবেদন নেই।
                                <?php endif; ?>
                            </h5>
                        </div>
                    <?php else: ?>
                        <div class="row" id="cardContainer">
                            <?php foreach ($leave_applications as $leave):
                                $leave_type_display = '';
                                switch($leave['leave_type']) {
                                    case 'sick':
                                        $leave_type_display = 'অসুস্থতা জনিত';
                                        break;
                                    case 'casual':
                                        $leave_type_display = 'অস্থায়ী';
                                        break;
                                    case 'annual':
                                        $leave_type_display = 'বার্ষিক';
                                        break;
                                    case 'maternity':
                                        $leave_type_display = 'মাতৃত্ব জনিত';
                                        break;
                                    case 'medical':
                                        $leave_type_display = 'চিকিৎসা সনদ সহ';
                                        break;
                                    case 'other':
                                        $leave_type_display = 'অন্যান্য';
                                        break;
                                    default:
                                        $leave_type_display = htmlspecialchars(ucfirst($leave['leave_type']));
                                        break;
                                }

                                $status_class = '';
                                $status_text = '';
                                $card_status_class = '';
                                switch($leave['status']) {
                                    case 'approved':
                                        $status_class = 'status-approved';
                                        $status_text = 'অনুমোদিত';
                                        $card_status_class = 'bg-success';
                                        break;
                                    case 'rejected':
                                        $status_class = 'status-rejected';
                                        $status_text = 'প্রত্যাখ্যাত';
                                        $card_status_class = 'bg-danger';
                                        break;
                                    case 'pending':
                                    default:
                                        $status_class = 'status-pending';
                                        $status_text = 'অমীমাংসিত';
                                        $card_status_class = 'bg-warning';
                                        break;
                                }

                                $teacher_name = htmlspecialchars(($leave['first_name'] ?? '') . ' ' . ($leave['last_name'] ?? ''));
                                $employee_id = htmlspecialchars($leave['employee_id'] ?? 'N/A');
                                $search_text = strtolower($teacher_name . ' ' . $employee_id . ' ' . $leave['leave_type'] . ' ' . $leave['status']);
                            ?>
                            <div class="col-lg-6 col-xl-4 leave-card-container" data-search-text="<?php echo $search_text; ?>">
                                <div class="leave-card">
                                    <div class="card-header-custom">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0">
                                                <i class="fas fa-user-graduate me-2"></i><?php echo $teacher_name; ?>
                                            </h6>
                                            <span class="badge <?php echo $card_status_class; ?> text-white"><?php echo $status_text; ?></span>
                                        </div>
                                    </div>
                                    <div class="card-body-custom">
                                        <div class="card-info-row">
                                            <span class="card-info-label">কর্মচারী আইডি:</span>
                                            <span class="card-info-value"><?php echo $employee_id; ?></span>
                                        </div>
                                        <div class="card-info-row">
                                            <span class="card-info-label">ছুটির ধরন:</span>
                                            <span class="card-info-value"><?php echo $leave_type_display; ?></span>
                                        </div>
                                        <div class="card-info-row">
                                            <span class="card-info-label">তারিখসমূহ:</span>
                                            <span class="card-info-value"><?php echo date('d/m/Y', strtotime($leave['start_date'])); ?> - <?php echo date('d/m/Y', strtotime($leave['end_date'])); ?></span>
                                        </div>
                                        <div class="card-info-row">
                                            <span class="card-info-label">আবেদন তারিখ:</span>
                                            <span class="card-info-value"><?php echo date('d/m/Y', strtotime($leave['applied_date'])); ?></span>
                                        </div>
                                        <div class="card-info-row">
                                            <span class="card-info-label">কারণ:</span>
                                            <span class="card-info-value"><?php echo htmlspecialchars(substr($leave['reason'], 0, 30)) . (strlen($leave['reason']) > 30 ? '...' : ''); ?></span>
                                        </div>

                                        <div class="card-actions">
                                            <!-- View button - available for all applications -->
                                            <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#viewModal"
                                                    data-leave-id="<?php echo $leave['id']; ?>"
                                                    data-teacher-id="<?php echo $leave['teacher_id']; ?>"
                                                    data-teacher-name="<?php echo $teacher_name; ?>"
                                                    data-employee-id="<?php echo $employee_id; ?>"
                                                    data-leave-type="<?php echo $leave['leave_type']; ?>"
                                                    data-start-date="<?php echo $leave['start_date']; ?>"
                                                    data-end-date="<?php echo $leave['end_date']; ?>"
                                                    data-reason="<?php echo htmlspecialchars($leave['reason'], ENT_QUOTES); ?>"
                                                    data-status="<?php echo $leave['status']; ?>"
                                                    data-applied-date="<?php echo date('d/m/Y H:i:s', strtotime($leave['applied_date'])); ?>"
                                                    data-approved-by="<?php echo htmlspecialchars($leave['approved_by'] ? 'অ্যাডমিন' : 'N/A'); ?>"
                                                    data-approved-date="<?php echo $leave['approved_date'] ? date('d/m/Y H:i:s', strtotime($leave['approved_date'])) : 'N/A'; ?>"
                                                    data-remarks="<?php echo htmlspecialchars($leave['remarks'] ?? '', ENT_QUOTES); ?>">
                                                <i class="fas fa-eye"></i> ভিউ
                                            </button>

                                            <!-- Edit button - available for pending applications -->
                                            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editModal"
                                                    data-leave-id="<?php echo $leave['id']; ?>"
                                                    data-teacher-id="<?php echo $leave['teacher_id']; ?>"
                                                    data-teacher-name="<?php echo $teacher_name; ?>"
                                                    data-leave-type="<?php echo $leave['leave_type']; ?>"
                                                    data-start-date="<?php echo $leave['start_date']; ?>"
                                                    data-end-date="<?php echo $leave['end_date']; ?>"
                                                    data-reason="<?php echo htmlspecialchars($leave['reason'], ENT_QUOTES); ?>"
                                                    data-status="<?php echo $leave['status']; ?>">
                                                <i class="fas fa-edit"></i> এডিট
                                            </button>

                                            <?php if ($leave['status'] === 'pending'): ?>
                                                <!-- Approve button -->
                                                <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#approveModal" data-leave-id="<?php echo $leave['id']; ?>" data-teacher-name="<?php echo $teacher_name; ?>" data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                    <i class="fas fa-check"></i> অনুমোদন
                                                </button>

                                                <!-- Reject button -->
                                                <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#rejectModal" data-leave-id="<?php echo $leave['id']; ?>" data-teacher-name="<?php echo $teacher_name; ?>" data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                    <i class="fas fa-times"></i> প্রত্যাখ্যান
                                                </button>

                                                <!-- Delete button -->
                                                <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal"
                                                        data-leave-id="<?php echo $leave['id']; ?>"
                                                        data-teacher-name="<?php echo $teacher_name; ?>"
                                                        data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                    <i class="fas fa-trash"></i> ডিলেট
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Teacher Info View Container -->
                <div class="teacher-info-view-container" id="teacherInfoViewContainer">
                    <?php if (empty($teacher_leave_data)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-users fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">
                                <?php if (!$show_rejected): ?>
                                    কোনো শিক্ষকের অমীমাংসিত বা অনুমোদিত ছুটির তথ্য নেই।
                                    <br><a href="?show_rejected=1" class="btn btn-link">প্রত্যাখ্যাত আবেদনসহ দেখতে এখানে ক্লিক করুন</a>
                                <?php else: ?>
                                    কোনো শিক্ষকের ছুটির তথ্য নেই।
                                <?php endif; ?>
                            </h5>
                        </div>
                    <?php else: ?>
                        <div class="row" id="teacherInfoContainer">
                            <?php foreach ($teacher_leave_data as $teacher_id => $teacher_data):
                                $teacher_info = $teacher_data['teacher_info'];
                                $leaves = $teacher_data['leaves'];

                                // Sort leaves by applied date (newest first)
                                usort($leaves, function($a, $b) {
                                    return strtotime($b['applied_date']) - strtotime($a['applied_date']);
                                });
                            ?>
                            <div class="col-12 teacher-info-card-container" data-search-text="<?php echo htmlspecialchars(strtolower($teacher_info['name'] . ' ' . $teacher_info['employee_id'])); ?>">
                                <div class="teacher-info-card">
                                    <!-- Teacher Header -->
                                    <div class="teacher-header">
                                        <div class="teacher-header-content">
                                            <div class="teacher-header-left">
                                                <h4 class="teacher-name">
                                                    <i class="fas fa-user-graduate me-2"></i>
                                                    <?php echo htmlspecialchars($teacher_info['name']); ?>
                                                </h4>
                                                <div class="teacher-details">
                                                    <span class="teacher-stat">
                                                        <i class="fas fa-id-badge me-1"></i>
                                                        কর্মচারী আইডি: <?php echo htmlspecialchars($teacher_info['employee_id']); ?>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="teacher-header-right">
                                                <div class="total-leaves-highlight">
                                                    <i class="fas fa-calendar-check me-2"></i>
                                                    <div class="total-leaves-info">
                                                        <div class="leaves-count"><?php echo $teacher_info['total_applications']; ?> টি আবেদন</div>
                                                        <div class="leaves-days"><?php echo $teacher_info['total_days']; ?> দিন</div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Leave Summary Section -->
                                    <div class="leave-summary-section">
                                        <div class="leave-summary-header">
                                            <h5 class="mb-0">
                                                <i class="fas fa-chart-bar me-2"></i>ছুটির সারাংশ
                                            </h5>
                                        </div>
                                        <div class="leave-stats">
                                            <div class="leave-stat-card pending">
                                                <div class="leave-stat-number"><?php echo $teacher_info['pending_leaves']; ?></div>
                                                <div class="leave-stat-label">অমীমাংসিত</div>
                                            </div>
                                            <div class="leave-stat-card approved">
                                                <div class="leave-stat-number"><?php echo $teacher_info['approved_leaves']; ?></div>
                                                <div class="leave-stat-label">অনুমোদিত</div>
                                            </div>
                                            <div class="leave-stat-card rejected">
                                                <div class="leave-stat-number"><?php echo $teacher_info['rejected_leaves']; ?></div>
                                                <div class="leave-stat-label">প্রত্যাখ্যাত</div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Leave Details Section -->
                                    <div class="leave-details-section">
                                        <div class="leave-details-header">
                                            <h6 class="mb-0">
                                                <i class="fas fa-list me-2"></i>ছুটির বিস্তারিত তথ্য
                                            </h6>
                                        </div>

                                        <?php foreach ($leaves as $leave):
                                            $leave_type_display = '';
                                            switch($leave['leave_type']) {
                                                case 'sick':
                                                    $leave_type_display = 'অসুস্থতা জনিত';
                                                    break;
                                                case 'casual':
                                                    $leave_type_display = 'অস্থায়ী';
                                                    break;
                                                case 'annual':
                                                    $leave_type_display = 'বার্ষিক';
                                                    break;
                                                case 'maternity':
                                                    $leave_type_display = 'মাতৃত্ব জনিত';
                                                    break;
                                                case 'medical':
                                                    $leave_type_display = 'চিকিৎসা সনদ সহ';
                                                    break;
                                                case 'other':
                                                    $leave_type_display = 'অন্যান্য';
                                                    break;
                                                default:
                                                    $leave_type_display = htmlspecialchars(ucfirst($leave['leave_type']));
                                                    break;
                                            }

                                            // Calculate days for this leave
                                            $start_date = new DateTime($leave['start_date']);
                                            $end_date = new DateTime($leave['end_date']);
                                            $leave_days = $start_date->diff($end_date)->days + 1;

                                            $status_class = '';
                                            $status_text = '';
                                            switch($leave['status']) {
                                                case 'approved':
                                                    $status_class = 'status-approved';
                                                    $status_text = 'অনুমোদিত (' . $leave_days . ' দিন)';
                                                    break;
                                                case 'rejected':
                                                    $status_class = 'status-rejected';
                                                    $status_text = 'প্রত্যাখ্যাত';
                                                    break;
                                                case 'pending':
                                                default:
                                                    $status_class = 'status-pending';
                                                    $status_text = 'অমীমাংসিত (' . $leave_days . ' দিন)';
                                                    break;
                                            }
                                        ?>
                                        <div class="leave-item">
                                            <div class="leave-item-header">
                                                <div>
                                                    <span class="leave-type-badge <?php echo $leave['leave_type']; ?>">
                                                        <?php echo $leave_type_display; ?>
                                                    </span>
                                                    <span class="leave-dates ms-2">
                                                        <?php echo date('d/m/Y', strtotime($leave['start_date'])); ?> - <?php echo date('d/m/Y', strtotime($leave['end_date'])); ?>
                                                    </span>
                                                </div>
                                                <span class="<?php echo $status_class; ?> badge">
                                                    <?php echo $status_text; ?>
                                                </span>
                                            </div>

                                            <div class="leave-reason">
                                                <?php echo htmlspecialchars($leave['reason']); ?>
                                            </div>

                                            <div class="leave-meta text-muted small mb-2">
                                                <i class="fas fa-calendar-plus me-1"></i>
                                                আবেদন তারিখ: <?php echo date('d/m/Y H:i', strtotime($leave['applied_date'])); ?>
                                                <?php if ($leave['approved_date']): ?>
                                                    | <i class="fas fa-check-circle me-1"></i>
                                                    অনুমোদন তারিখ: <?php echo date('d/m/Y H:i', strtotime($leave['approved_date'])); ?>
                                                <?php endif; ?>
                                            </div>

                                            <div class="leave-actions">
                                                <!-- View button - available for all applications -->
                                                <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#viewModal"
                                                        data-leave-id="<?php echo $leave['id']; ?>"
                                                        data-teacher-id="<?php echo $leave['teacher_id']; ?>"
                                                        data-teacher-name="<?php echo htmlspecialchars($teacher_info['name']); ?>"
                                                        data-employee-id="<?php echo htmlspecialchars($teacher_info['employee_id']); ?>"
                                                        data-leave-type="<?php echo $leave['leave_type']; ?>"
                                                        data-start-date="<?php echo $leave['start_date']; ?>"
                                                        data-end-date="<?php echo $leave['end_date']; ?>"
                                                        data-reason="<?php echo htmlspecialchars($leave['reason'], ENT_QUOTES); ?>"
                                                        data-status="<?php echo $leave['status']; ?>"
                                                        data-applied-date="<?php echo date('d/m/Y H:i:s', strtotime($leave['applied_date'])); ?>"
                                                        data-approved-by="<?php echo htmlspecialchars($leave['approved_by'] ? 'অ্যাডমিন' : 'N/A'); ?>"
                                                        data-approved-date="<?php echo $leave['approved_date'] ? date('d/m/Y H:i:s', strtotime($leave['approved_date'])) : 'N/A'; ?>"
                                                        data-remarks="<?php echo htmlspecialchars($leave['remarks'] ?? '', ENT_QUOTES); ?>">
                                                    <i class="fas fa-eye"></i> ভিউ
                                                </button>

                                                <!-- Edit button - available for pending applications -->
                                                <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editModal"
                                                        data-leave-id="<?php echo $leave['id']; ?>"
                                                        data-teacher-id="<?php echo $leave['teacher_id']; ?>"
                                                        data-teacher-name="<?php echo htmlspecialchars($teacher_info['name']); ?>"
                                                        data-leave-type="<?php echo $leave['leave_type']; ?>"
                                                        data-start-date="<?php echo $leave['start_date']; ?>"
                                                        data-end-date="<?php echo $leave['end_date']; ?>"
                                                        data-reason="<?php echo htmlspecialchars($leave['reason'], ENT_QUOTES); ?>"
                                                        data-status="<?php echo $leave['status']; ?>">
                                                    <i class="fas fa-edit"></i> এডিট
                                                </button>

                                                <?php if ($leave['status'] === 'pending'): ?>
                                                    <!-- Approve button -->
                                                    <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#approveModal" data-leave-id="<?php echo $leave['id']; ?>" data-teacher-name="<?php echo htmlspecialchars($teacher_info['name']); ?>" data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                        <i class="fas fa-check"></i> অনুমোদন
                                                    </button>

                                                    <!-- Reject button -->
                                                    <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#rejectModal" data-leave-id="<?php echo $leave['id']; ?>" data-teacher-name="<?php echo htmlspecialchars($teacher_info['name']); ?>" data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                        <i class="fas fa-times"></i> প্রত্যাখ্যান
                                                    </button>

                                                    <!-- Delete button -->
                                                    <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal"
                                                            data-leave-id="<?php echo $leave['id']; ?>"
                                                            data-teacher-name="<?php echo htmlspecialchars($teacher_info['name']); ?>"
                                                            data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                        <i class="fas fa-trash"></i> ডিলেট
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Approve Modal -->
    <div class="modal fade" id="approveModal" tabindex="-1" aria-labelledby="approveModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="approveModalLabel">ছুটি অনুমোদন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="approve">
                        <input type="hidden" name="leave_id" id="approve_leave_id" value="">
                        
                        <div class="mb-3">
                            <label class="form-label">শিক্ষক</label>
                            <input type="text" class="form-control" id="approve_teacher_name" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">তারিখসমূহ</label>
                            <input type="text" class="form-control" id="approve_leave_dates" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">মন্তব্য (ঐচ্ছিক)</label>
                            <textarea class="form-control" name="remarks" rows="3" placeholder="মন্তব্য লিখুন..."></textarea>
                        </div>
                        
                        <p class="text-warning">আপনি কি নিশ্চিত যে আপনি এই ছুটি অনুমোদন করতে চান?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-success">অনুমোদন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Reject Modal -->
    <div class="modal fade" id="rejectModal" tabindex="-1" aria-labelledby="rejectModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="rejectModalLabel">ছুটি প্রত্যাখ্যান</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="reject">
                        <input type="hidden" name="leave_id" id="reject_leave_id" value="">
                        
                        <div class="mb-3">
                            <label class="form-label">শিক্ষক</label>
                            <input type="text" class="form-control" id="reject_teacher_name" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">তারিখসমূহ</label>
                            <input type="text" class="form-control" id="reject_leave_dates" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">মন্তব্য (প্রয়োজনীয়)</label>
                            <textarea class="form-control" name="remarks" rows="3" placeholder="প্রত্যাখ্যানের কারণ লিখুন..." required></textarea>
                        </div>
                        
                        <p class="text-warning">আপনি কি নিশ্চিত যে আপনি এই ছুটি প্রত্যাখ্যান করতে চান?</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>

    <!-- Reset All Modal -->
    <div class="modal fade" id="resetAllModal" tabindex="-1" aria-labelledby="resetAllModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="resetAllModalLabel"><i class="fas fa-refresh text-warning"></i> সকল শিক্ষকের ছুটি রিসেট</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="reset_all">
                        <input type="hidden" name="confirm_reset" value="1">

                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong>সতর্কতা!</strong> এই অ্যাকশনটি সকল শিক্ষকের সকল ছুটির আবেদন মুছে ফেলবে এবং পুনরায় 'অমীমাংসিত' অবস্থায় রিসেট করবে।
                        </div>

                        <div class="mb-3">
                            <label class="form-label">কনফার্মেশন</label>
                            <input type="text" class="form-control" id="reset_confirmation" name="reset_confirmation" placeholder="রিসেট করতে 'RESET' লিখুন" required>
                        </div>

                        <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-warning" id="resetSubmitBtn" disabled>
                            <i class="fas fa-refresh"></i> রিসেট করুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Modal -->
    <div class="modal fade" id="viewModal" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewModalLabel"><i class="fas fa-eye text-info"></i> ছুটির আবেদনের বিস্তারিত</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-8">
                            <h6 class="text-primary mb-3"><i class="fas fa-user-graduate"></i> শিক্ষক তথ্য</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td class="fw-bold" style="width: 120px;">নাম:</td>
                                    <td id="view_teacher_name"></td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">কর্মচারী আইডি:</td>
                                    <td id="view_employee_id"></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-4">
                            <h6 class="text-primary mb-3"><i class="fas fa-calendar-alt"></i> আবেদন তথ্য</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td class="fw-bold" style="width: 100px;">আইডি:</td>
                                    <td id="view_leave_id"></td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">আবেদন তারিখ:</td>
                                    <td id="view_applied_date"></td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <hr>

                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="text-success mb-3"><i class="fas fa-calendar-check"></i> ছুটির তথ্য</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td class="fw-bold" style="width: 120px;">ছুটির ধরন:</td>
                                    <td id="view_leave_type"></td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">শুরুর তারিখ:</td>
                                    <td id="view_start_date"></td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">শেষ তারিখ:</td>
                                    <td id="view_end_date"></td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">মোট দিন:</td>
                                    <td id="view_total_days"></td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6 class="text-info mb-3"><i class="fas fa-info-circle"></i> স্ট্যাটাস তথ্য</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td class="fw-bold" style="width: 120px;">বর্তমান স্ট্যাটাস:</td>
                                    <td><span id="view_status_badge" class="badge"></span></td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">অনুমোদনকারী:</td>
                                    <td id="view_approved_by"></td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">অনুমোদন তারিখ:</td>
                                    <td id="view_approved_date"></td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <hr>

                    <div class="row">
                        <div class="col-12">
                            <h6 class="text-warning mb-3"><i class="fas fa-comment"></i> কারণ এবং মন্তব্য</h6>
                            <div class="mb-3">
                                <label class="form-label fw-bold">ছুটির কারণ:</label>
                                <div class="border p-2 rounded bg-light" id="view_reason"></div>
                            </div>
                            <div id="remarks_section" style="display: none;">
                                <label class="form-label fw-bold">অ্যাডমিন মন্তব্য:</label>
                                <div class="border p-2 rounded bg-light" id="view_remarks"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> বন্ধ করুন
                    </button>
                    <button type="button" class="btn btn-primary" onclick="printLeaveDetails()">
                        <i class="fas fa-print"></i> প্রিন্ট
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Modal -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel"><i class="fas fa-edit text-primary"></i> ছুটির আবেদন এডিট করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="edit_leave">
                    <input type="hidden" name="leave_id" id="edit_leave_id" value="">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_teacher_id" class="form-label">শিক্ষক <span class="text-danger">*</span></label>
                                    <select class="form-select" id="edit_teacher_id" name="teacher_id" required>
                                        <option value="">শিক্ষক নির্বাচন করুন</option>
                                        <?php
                                        $teacher_stmt = $pdo->query("SELECT id, first_name, last_name, employee_id FROM teachers WHERE status = 'active' ORDER BY first_name, last_name");
                                        while ($teacher = $teacher_stmt->fetch()) {
                                            echo '<option value="' . $teacher['id'] . '">' . htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name'] . ' (' . $teacher['employee_id'] . ')') . '</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_leave_type" class="form-label">ছুটির ধরন <span class="text-danger">*</span></label>
                                    <select class="form-select" id="edit_leave_type" name="leave_type" required>
                                        <option value="sick">অসুস্থতা জনিত</option>
                                        <option value="casual">অস্থায়ী</option>
                                        <option value="annual">বার্ষিক</option>
                                        <option value="maternity">মাতৃত্ব জনিত</option>
                                        <option value="medical">চিকিৎসা সনদ সহ</option>
                                        <option value="other">অন্যান্য</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_start_date" class="form-label">শুরুর তারিখ <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="edit_start_date" name="start_date" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_end_date" class="form-label">শেষ তারিখ <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="edit_end_date" name="end_date" required>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="edit_status" class="form-label">স্ট্যাটাস</label>
                            <select class="form-select" id="edit_status" name="status">
                                <option value="pending">অমীমাংসিত</option>
                                <option value="approved">অনুমোদিত</option>
                                <option value="rejected">প্রত্যাখ্যাত</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="edit_reason" class="form-label">কারণ <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="edit_reason" name="reason" rows="3" required placeholder="ছুটির কারণ লিখুন..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> আপডেট করুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel"><i class="fas fa-trash text-danger"></i> ছুটির আবেদন মুছে ফেলুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="delete_leave">
                        <input type="hidden" name="leave_id" id="delete_leave_id" value="">

                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong>সতর্কতা!</strong> এই অ্যাকশন পূর্বাবস্থায় ফেরানো যাবে না।
                        </div>

                        <p>আপনি কি নিশ্চিত যে <strong id="delete_teacher_name"></strong> এর ছুটির আবেদন (<strong id="delete_leave_dates"></strong>) মুছে ফেলতে চান?</p>

                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="confirm_delete" required>
                            <label class="form-check-label" for="confirm_delete">
                                হ্যাঁ, আমি নিশ্চিত যে এই ছুটির আবেদন মুছে ফেলতে চাই
                            </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="deleteBtn" disabled>
                            <i class="fas fa-trash"></i> মুছে ফেলুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bulk Approve Modal -->
    <div class="modal fade" id="bulkApproveModal" tabindex="-1" aria-labelledby="bulkApproveModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="bulkApproveModalLabel"><i class="fas fa-check text-success"></i> বাল্ক অনুমোদন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" id="bulkApproveForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="bulk_approve">
                        <input type="hidden" name="selected_leaves" id="bulkApproveLeaves" value="">

                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <strong id="bulkApproveCount">0</strong> টি ছুটির আবেদন অনুমোদন করা হবে।
                        </div>

                        <div class="mb-3">
                            <label class="form-label">মন্তব্য (ঐচ্ছিক)</label>
                            <textarea class="form-control" name="bulk_remarks" rows="3" placeholder="বাল্ক অনুমোদনের জন্য মন্তব্য লিখুন..."></textarea>
                        </div>

                        <p class="text-success">আপনি কি নিশ্চিত যে এই আবেদনগুলো অনুমোদন করতে চান?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-check"></i> অনুমোদন করুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bulk Reject Modal -->
    <div class="modal fade" id="bulkRejectModal" tabindex="-1" aria-labelledby="bulkRejectModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="bulkRejectModalLabel"><i class="fas fa-times text-danger"></i> বাল্ক প্রত্যাখ্যান</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" id="bulkRejectForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="bulk_reject">
                        <input type="hidden" name="selected_leaves" id="bulkRejectLeaves" value="">

                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong id="bulkRejectCount">0</strong> টি ছুটির আবেদন প্রত্যাখ্যান করা হবে।
                        </div>

                        <div class="mb-3">
                            <label class="form-label">প্রত্যাখ্যানের কারণ <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="bulk_remarks" rows="3" placeholder="প্রত্যাখ্যানের কারণ লিখুন..." required></textarea>
                        </div>

                        <p class="text-danger">আপনি কি নিশ্চিত যে এই আবেদনগুলো প্রত্যাখ্যান করতে চান?</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">
                            <i class="fas fa-times"></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>
        // 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);
        }

        // Print leave details function
        function printLeaveDetails() {
            const modalContent = document.querySelector('#viewModal .modal-content');
            const originalContent = modalContent.innerHTML;

            // Create print header
            const printHeader = `
                <div style="text-align: center; border-bottom: 2px solid #006747; padding-bottom: 10px; margin-bottom: 20px;">
                    <h2 style="color: #006747; margin: 0;">শিক্ষক ছুটির আবেদন - বিস্তারিত</h2>
                    <p style="margin: 5px 0; color: #666;">প্রিন্ট তারিখ: ${new Date().toLocaleDateString('bn-BD')} ${new Date().toLocaleTimeString('bn-BD')}</p>
                </div>
            `;

            // Temporarily modify modal content for printing
            modalContent.innerHTML = printHeader + '<div style="padding: 20px;">' + modalContent.innerHTML + '</div>';

            // Hide modal elements for print
            const modalElements = modalContent.querySelectorAll('.modal-header, .modal-footer');
            modalElements.forEach(el => el.style.display = 'none');

            // Print
            window.print();

            // Restore original content
            setTimeout(() => {
                modalContent.innerHTML = originalContent;
            }, 1000);
        }

        // Handle modal data passing
        document.querySelectorAll('[data-bs-toggle="modal"]').forEach(button => {
            button.addEventListener('click', function() {
                const leaveId = this.getAttribute('data-leave-id');
                const teacherName = this.getAttribute('data-teacher-name');
                const leaveDates = this.getAttribute('data-leave-dates');

                if (this.getAttribute('data-bs-target') === '#viewModal') {
                    // Populate view modal
                    const leaveType = this.getAttribute('data-leave-type');
                    const startDate = this.getAttribute('data-start-date');
                    const endDate = this.getAttribute('data-end-date');
                    const reason = this.getAttribute('data-reason').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#039;/g, "'");
                    const status = this.getAttribute('data-status');
                    const appliedDate = this.getAttribute('data-applied-date');
                    const approvedBy = this.getAttribute('data-approved-by');
                    const approvedDate = this.getAttribute('data-approved-date');
                    const remarks = this.getAttribute('data-remarks').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#039;/g, "'");

                    // Calculate total days
                    const start = new Date(startDate);
                    const end = new Date(endDate);
                    const totalDays = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;

                    // Set leave type display
                    const leaveTypeMap = {
                        'sick': 'অসুস্থতা জনিত',
                        'casual': 'অস্থায়ী',
                        'annual': 'বার্ষিক',
                        'maternity': 'মাতৃত্ব জনিত',
                        'medical': 'চিকিূসা সনদ সহ',
                        'other': 'অন্যান্য'
                    };
                    const leaveTypeDisplay = leaveTypeMap[leaveType] || leaveType;

                    // Set status badge
                    const statusMap = {
                        'pending': { text: 'অমীমাংসিত', class: 'bg-warning text-dark' },
                        'approved': { text: 'অনুমোদিত', class: 'bg-success' },
                        'rejected': { text: 'প্রত্যাখ্যাত', class: 'bg-danger' }
                    };
                    const statusInfo = statusMap[status] || { text: status, class: 'bg-secondary' };

                    // Populate modal fields
                    document.getElementById('view_leave_id').textContent = leaveId;
                    document.getElementById('view_teacher_name').textContent = teacherName;
                    document.getElementById('view_employee_id').textContent = this.getAttribute('data-employee-id');
                    document.getElementById('view_leave_type').textContent = leaveTypeDisplay;
                    document.getElementById('view_start_date').textContent = new Date(startDate).toLocaleDateString('bn-BD');
                    document.getElementById('view_end_date').textContent = new Date(endDate).toLocaleDateString('bn-BD');
                    document.getElementById('view_total_days').textContent = totalDays + ' দিন';
                    document.getElementById('view_applied_date').textContent = appliedDate;
                    document.getElementById('view_approved_by').textContent = approvedBy;
                    document.getElementById('view_approved_date').textContent = approvedDate;
                    document.getElementById('view_reason').textContent = reason || 'কোন কারণ উল্লেখ করা হয়নি';

                    const statusBadge = document.getElementById('view_status_badge');
                    statusBadge.textContent = statusInfo.text;
                    statusBadge.className = `badge ${statusInfo.class}`;

                    const remarksSection = document.getElementById('remarks_section');
                    const remarksDiv = document.getElementById('view_remarks');

                    if (remarks) {
                        remarksDiv.textContent = remarks;
                        remarksSection.style.display = 'block';
                    } else {
                        remarksSection.style.display = 'none';
                    }

                    // Set modal title
                    document.querySelector('#viewModal .modal-title').innerHTML = '<i class="fas fa-eye text-info"></i> ' + teacherName + ' এর ছুটির বিস্তারিত';

                } else if (this.getAttribute('data-bs-target') === '#approveModal') {
                    document.getElementById('approve_leave_id').value = leaveId;
                    document.getElementById('approve_teacher_name').value = teacherName;
                    document.getElementById('approve_leave_dates').value = leaveDates;
                } else if (this.getAttribute('data-bs-target') === '#rejectModal') {
                    document.getElementById('reject_leave_id').value = leaveId;
                    document.getElementById('reject_teacher_name').value = teacherName;
                    document.getElementById('reject_leave_dates').value = leaveDates;
                } else if (this.getAttribute('data-bs-target') === '#editModal') {
                    // Populate edit modal
                    document.getElementById('edit_leave_id').value = leaveId;
                    document.getElementById('edit_teacher_id').value = this.getAttribute('data-teacher-id');
                    document.getElementById('edit_leave_type').value = this.getAttribute('data-leave-type');
                    document.getElementById('edit_start_date').value = this.getAttribute('data-start-date');
                    document.getElementById('edit_end_date').value = this.getAttribute('data-end-date');
                    document.getElementById('edit_reason').value = this.getAttribute('data-reason').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#039;/g, "'");
                    document.getElementById('edit_status').value = this.getAttribute('data-status');

                    // Set modal title
                    const teacherName = this.getAttribute('data-teacher-name');
                    document.querySelector('#editModal .modal-title').innerHTML = '<i class="fas fa-edit text-primary"></i> ' + teacherName + ' এর ছুটি এডিট করুন';
                } else if (this.getAttribute('data-bs-target') === '#deleteModal') {
                    // Populate delete modal
                    document.getElementById('delete_leave_id').value = leaveId;
                    document.getElementById('delete_teacher_name').textContent = teacherName;
                    document.getElementById('delete_leave_dates').textContent = leaveDates;
                    document.getElementById('confirm_delete').checked = false;
                    document.getElementById('deleteBtn').disabled = true;
                } else if (this.getAttribute('data-bs-target') === '#resetAllModal') {
                    // Clear the confirmation input when modal opens
                    document.getElementById('reset_confirmation').value = '';
                    document.getElementById('resetSubmitBtn').disabled = true;
                }
            });
        });

        // Handle reset confirmation input
        document.getElementById('reset_confirmation').addEventListener('input', function() {
            const resetBtn = document.getElementById('resetSubmitBtn');
            const inputValue = this.value.trim().toUpperCase();

            if (inputValue === 'RESET') {
                resetBtn.disabled = false;
                resetBtn.innerHTML = '<i class="fas fa-refresh"></i> রিসেট করুন';
            } else {
                resetBtn.disabled = true;
                resetBtn.innerHTML = '<i class="fas fa-refresh"></i> রিসেট করুন';
            }
        });

        // Handle delete confirmation checkbox
        document.getElementById('confirm_delete').addEventListener('change', function() {
            document.getElementById('deleteBtn').disabled = !this.checked;
        });

        // Clear delete confirmation when modal is closed
        document.getElementById('deleteModal').addEventListener('hidden.bs.modal', function() {
            document.getElementById('confirm_delete').checked = false;
            document.getElementById('deleteBtn').disabled = true;
        });

        // Clear confirmation input when modal is closed
        document.getElementById('resetAllModal').addEventListener('hidden.bs.modal', function() {
            document.getElementById('reset_confirmation').value = '';
            document.getElementById('resetSubmitBtn').disabled = true;
        });

        // Search functionality
        const searchInput = document.getElementById('searchInput');
        const clearSearchBtn = document.getElementById('clearSearch');

        function performSearch() {
            const searchTerm = searchInput.value.toLowerCase().trim();

            // Search in table view
            const tableRows = document.querySelectorAll('.leave-row');
            tableRows.forEach(row => {
                const searchText = row.getAttribute('data-search-text') || '';
                const shouldShow = searchText.includes(searchTerm);
                row.style.display = shouldShow ? '' : 'none';
            });

            // Search in card view
            const cardContainers = document.querySelectorAll('.leave-card-container');
            cardContainers.forEach(card => {
                const searchText = card.getAttribute('data-search-text') || '';
                const shouldShow = searchText.includes(searchTerm);
                card.style.display = shouldShow ? '' : 'none';
            });

            // Search in teacher info view
            const teacherInfoContainers = document.querySelectorAll('.teacher-info-card-container');
            teacherInfoContainers.forEach(card => {
                const searchText = card.getAttribute('data-search-text') || '';
                const shouldShow = searchText.includes(searchTerm);
                card.style.display = shouldShow ? '' : 'none';
            });
        }

        // Search input event listener
        searchInput.addEventListener('input', performSearch);

        // Clear search button
        clearSearchBtn.addEventListener('click', function() {
            searchInput.value = '';
            performSearch();
            searchInput.focus();
        });

        // View toggle functionality
        const tableViewBtn = document.getElementById('tableViewBtn');
        const cardViewBtn = document.getElementById('cardViewBtn');
        const teacherInfoViewBtn = document.getElementById('teacherInfoViewBtn');
        const tableViewContainer = document.getElementById('tableViewContainer');
        const cardViewContainer = document.getElementById('cardViewContainer');
        const teacherInfoViewContainer = document.getElementById('teacherInfoViewContainer');

        function setView(viewType) {
            // Reset all buttons
            tableViewBtn.classList.remove('active');
            cardViewBtn.classList.remove('active');
            teacherInfoViewBtn.classList.remove('active');

            // Hide all containers
            tableViewContainer.classList.remove('show');
            tableViewContainer.classList.add('hide');
            cardViewContainer.classList.remove('show');
            cardViewContainer.classList.add('hide');
            teacherInfoViewContainer.classList.remove('show');
            teacherInfoViewContainer.classList.add('hide');

            if (viewType === 'table') {
                tableViewBtn.classList.add('active');
                tableViewContainer.classList.remove('hide');
                tableViewContainer.classList.add('show');
                localStorage.setItem('leaveViewPreference', 'table');
            } else if (viewType === 'card') {
                cardViewBtn.classList.add('active');
                cardViewContainer.classList.remove('hide');
                cardViewContainer.classList.add('show');
                localStorage.setItem('leaveViewPreference', 'card');
            } else if (viewType === 'teacher') {
                teacherInfoViewBtn.classList.add('active');
                teacherInfoViewContainer.classList.remove('hide');
                teacherInfoViewContainer.classList.add('show');
                localStorage.setItem('leaveViewPreference', 'teacher');
            }
        }

        // View button click handlers
        tableViewBtn.addEventListener('click', function() {
            setView('table');
        });

        cardViewBtn.addEventListener('click', function() {
            setView('card');
        });

        teacherInfoViewBtn.addEventListener('click', function() {
            setView('teacher');
        });

        // Load saved view preference on page load
        document.addEventListener('DOMContentLoaded', function() {
            const savedView = localStorage.getItem('leaveViewPreference') || 'table';
            setView(savedView);
        });

        // Enter key support for search
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                performSearch();
            }
        });

        // Bulk selection functionality
        const selectAllCheckbox = document.getElementById('selectAllCheckboxes');
        const leaveCheckboxes = document.querySelectorAll('.leave-checkbox');
        const bulkActionsCard = document.getElementById('bulkActionsCard');
        const selectedCount = document.getElementById('selectedCount');
        const bulkApproveBtn = document.getElementById('bulkApproveBtn');
        const bulkRejectBtn = document.getElementById('bulkRejectBtn');
        const clearSelectionBtn = document.getElementById('clearSelectionBtn');

        // Select All functionality
        selectAllCheckbox.addEventListener('change', function() {
            const isChecked = this.checked;
            leaveCheckboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            updateBulkActions();
        });

        // Individual checkbox change
        leaveCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateBulkActions();
                updateSelectAllState();
            });
        });

        // Update bulk actions visibility and state
        function updateBulkActions() {
            const checkedBoxes = document.querySelectorAll('.leave-checkbox:checked');
            const count = checkedBoxes.length;

            selectedCount.textContent = count;

            if (count > 0) {
                bulkActionsCard.style.display = 'block';
                bulkApproveBtn.disabled = false;
                bulkRejectBtn.disabled = false;
            } else {
                bulkActionsCard.style.display = 'none';
                bulkApproveBtn.disabled = true;
                bulkRejectBtn.disabled = true;
            }
        }

        // Update select all checkbox state
        function updateSelectAllState() {
            const totalCheckboxes = leaveCheckboxes.length;
            const checkedBoxes = document.querySelectorAll('.leave-checkbox:checked').length;

            if (checkedBoxes === 0) {
                selectAllCheckbox.indeterminate = false;
                selectAllCheckbox.checked = false;
            } else if (checkedBoxes === totalCheckboxes) {
                selectAllCheckbox.indeterminate = false;
                selectAllCheckbox.checked = true;
            } else {
                selectAllCheckbox.indeterminate = true;
                selectAllCheckbox.checked = false;
            }
        }

        // Clear selection
        clearSelectionBtn.addEventListener('click', function() {
            leaveCheckboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
            updateBulkActions();
        });

        // Bulk approve
        bulkApproveBtn.addEventListener('click', function() {
            const selectedLeaves = Array.from(document.querySelectorAll('.leave-checkbox:checked')).map(cb => parseInt(cb.value));
            if (selectedLeaves.length > 0) {
                document.getElementById('bulkApproveLeaves').value = JSON.stringify(selectedLeaves);
                document.getElementById('bulkApproveCount').textContent = selectedLeaves.length;
                new bootstrap.Modal(document.getElementById('bulkApproveModal')).show();
            }
        });

        // Bulk reject
        bulkRejectBtn.addEventListener('click', function() {
            const selectedLeaves = Array.from(document.querySelectorAll('.leave-checkbox:checked')).map(cb => parseInt(cb.value));
            if (selectedLeaves.length > 0) {
                document.getElementById('bulkRejectLeaves').value = JSON.stringify(selectedLeaves);
                document.getElementById('bulkRejectCount').textContent = selectedLeaves.length;
                new bootstrap.Modal(document.getElementById('bulkRejectModal')).show();
            }
        });

        // Clear selection when view changes
        document.querySelectorAll('[id$="ViewBtn"]').forEach(btn => {
            btn.addEventListener('click', function() {
                setTimeout(() => {
                    clearSelectionBtn.click();
                }, 100);
            });
        });
    </script>
</body>
</html>