<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';
require_once '../includes/sidebar_layout.php';

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

// Get system name for branding
$system_name = get_system_name($pdo);

// Get site settings for institutional information
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['site_address'] ?? 'ঠিকানা: গ্রাম/থানা, জেলা, বাংলাদেশ';
$logo_image = $settings['logo_image'] ?? null;
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;
$logo_opacity = isset($settings['logo_opacity']) ? floatval($settings['logo_opacity']) : 0.9;

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

// Test database connection and basic data
try {
    $test_stmt = $pdo->query("SELECT COUNT(*) as total FROM attendance");
    $attendance_count = $test_stmt->fetch();
    error_log("Total attendance records: " . $attendance_count['total']);
} catch (Exception $e) {
    error_log("Database test error: " . $e->getMessage());
}

// Get holiday data for the current period
$holidays = [];
try {
    $holiday_sql = "SELECT event_date, end_date, title FROM academic_calendar WHERE event_type = 'holiday' AND status = 'active'";
    
    // Add date range filtering based on report type
    if ($report_type == 'monthly') {
        $start_of_month = date('Y-m-01', strtotime($month_filter . '-01'));
        $end_of_month = date('Y-m-t', strtotime($month_filter . '-01'));
        $holiday_sql .= " AND ((event_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?) OR (event_date <= ? AND end_date >= ?))";
        $holiday_stmt = $pdo->prepare($holiday_sql);
        $holiday_stmt->execute([$start_of_month, $end_of_month, $start_of_month, $end_of_month, $start_of_month, $end_of_month]);
    } elseif ($report_type == 'yearly') {
        $start_of_year = $year_filter . '-01-01';
        $end_of_year = $year_filter . '-12-31';
        $holiday_sql .= " AND ((event_date BETWEEN ? AND ?) OR (end_date BETWEEN ? AND ?) OR (event_date <= ? AND end_date >= ?))";
        $holiday_stmt = $pdo->prepare($holiday_sql);
        $holiday_stmt->execute([$start_of_year, $end_of_year, $start_of_year, $end_of_year, $start_of_year, $end_of_year]);
    } else {
        $holiday_stmt = $pdo->prepare($holiday_sql);
        $holiday_stmt->execute();
    }
    
    $holidays = $holiday_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Convert to date array for easy checking
    $local_holiday_dates = [];
    foreach ($holidays as $holiday) {
        if ($holiday['end_date']) {
            // Multi-day holiday
            $start = new DateTime($holiday['event_date']);
            $end = new DateTime($holiday['end_date']);
            $interval = DateInterval::createFromDateString('1 day');
            $period = new DatePeriod($start, $interval, $end->modify('+1 day'));
            
            foreach ($period as $date) {
                $local_holiday_dates[] = $date->format('Y-m-d');
            }
        } else {
            // Single day holiday
            $local_holiday_dates[] = $holiday['event_date'];
        }
    }
    $holiday_dates = array_unique($local_holiday_dates);
    
} catch (Exception $e) {
    error_log("Holiday data fetch error: " . $e->getMessage());
    $holidays = [];
    $holiday_dates = [];
}

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

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

// Process form submission
$report_data = [
    'students' => [],
    'teachers' => [],
    'filters' => []
];
$report_type = isset($_GET['report_type']) ? $_GET['report_type'] : 'daily';
$date_filter = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$week_filter = isset($_GET['week']) ? $_GET['week'] : date('Y-W');
$month_filter = isset($_GET['month']) ? $_GET['month'] : date('Y-m');
$year_filter = isset($_GET['year']) ? $_GET['year'] : date('Y');
$class_filter = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
$session_filter = isset($_GET['session']) ? $_GET['session'] : (isset($sessions[0]) ? $sessions[0] : '');
$search_filter = isset($_GET['search']) ? trim($_GET['search']) : '';

// Initialize holiday dates array
$holiday_dates = [];

// Prepare SQL based on report type
// Generate report if explicit generate flag is set OR if any meaningful filter parameters are present
$has_filters = (isset($_GET['report_type']) && !empty($_GET['report_type'])) || 
                (isset($_GET['date']) && !empty($_GET['date'])) || 
                (isset($_GET['week']) && !empty($_GET['week'])) || 
                (isset($_GET['month']) && !empty($_GET['month'])) || 
                (isset($_GET['year']) && !empty($_GET['year'])) || 
                (isset($_GET['class_id']) && $_GET['class_id'] > 0) || 
                (isset($_GET['session']) && !empty($_GET['session'])) || 
                (isset($_GET['search']) && !empty(trim($_GET['search'])));

if (isset($_GET['generate']) || isset($_POST['generate']) || $has_filters) {
    $sql_params = [];
    $where_conditions = [];
    
    // Add filters based on report type
    switch ($report_type) {
        case 'daily':
            if (!empty($date_filter)) {
                $where_conditions[] = "a.date = ?";
                $sql_params[] = $date_filter;
            }
            break;
        case 'weekly':
            if (!empty($week_filter)) {
                $start_date = date('Y-m-d', strtotime($week_filter . '-1'));
                $end_date = date('Y-m-d', strtotime($week_filter . '-7'));
                $where_conditions[] = "a.date BETWEEN ? AND ?";
                $sql_params[] = $start_date;
                $sql_params[] = $end_date;
            }
            break;
        case 'monthly':
            if (!empty($month_filter)) {
                $where_conditions[] = "DATE_FORMAT(a.date, '%Y-%m') = ?";
                $sql_params[] = $month_filter;
            }
            break;
        case 'yearly':
            if (!empty($year_filter)) {
                $where_conditions[] = "YEAR(a.date) = ?";
                $sql_params[] = $year_filter;
            }
            break;
    }
    
    // Class filter
    if (isset($_GET['class_id']) && $class_filter > 0) {
        $where_conditions[] = "s.class_id = ?";
        $sql_params[] = $class_filter;
    }
    
    // Session filter
    if (isset($_GET['session']) && !empty($session_filter)) {
        $where_conditions[] = "s.session = ?";
        $sql_params[] = $session_filter;
    }
    
    // Search filter
    if (isset($_GET['search']) && !empty($search_filter)) {
        $where_conditions[] = "(CONCAT(s.first_name, ' ', s.last_name) LIKE ? OR s.student_id LIKE ? OR s.roll_number LIKE ?)";
        $search_param = '%' . $search_filter . '%';
        $sql_params[] = $search_param;
        $sql_params[] = $search_param;
        $sql_params[] = $search_param;
    }
    
    // Build separate where clauses for students and teachers
    
    // For students - include all filters
    $student_where_conditions = $where_conditions;
    $student_sql_params = $sql_params;
    
    $student_where_clause = '';
    if (!empty($student_where_conditions)) {
        $student_where_clause = 'WHERE ' . implode(' AND ', $student_where_conditions);
    }
    
    // For teachers - exclude class and session filters since teachers don't have these
    $teacher_where_conditions = [];
    $teacher_sql_params = [];
    
    // Copy date-related conditions
    foreach ($where_conditions as $index => $condition) {
        if (strpos($condition, 'a.date') === 0) {
            $teacher_where_conditions[] = $condition;
            $teacher_sql_params[] = $sql_params[$index];
        }
        // Skip class_id and session conditions for teachers
    }
    
    $teacher_where_clause = '';
    if (!empty($teacher_where_conditions)) {
        $teacher_where_clause = 'WHERE ' . implode(' AND ', $teacher_where_conditions);
    }
    
    // Query for student attendance
    $sql = "
        SELECT 
            a.date,
            a.status,
            a.remarks,
            s.id as student_id,
            s.first_name,
            s.last_name,
            s.student_id as student_std_id,
            s.roll_number,
            s.photo,
            c.name as class_name,
            c.section as class_section
        FROM attendance a
        INNER JOIN students s ON a.student_id = s.id
        LEFT JOIN classes c ON s.class_id = c.id
        $student_where_clause
        ORDER BY s.class_id, s.roll_number, a.date
    ";
    
    // Debug: Log the actual SQL query and parameters
    error_log("Student SQL Query: " . $sql);
    error_log("Student SQL Params: " . json_encode($student_sql_params));
    error_log("Report Type: " . $report_type);
    error_log("Date Filter: " . $date_filter);
    error_log("Class Filter: " . $class_filter);
    error_log("Session Filter: " . $session_filter);
    error_log("Search Filter: " . $search_filter);
    
    $stmt = $pdo->prepare($sql);
    try {
        $stmt->execute($student_sql_params);
        $student_data = $stmt->fetchAll();
        error_log("Student query executed successfully. Rows found: " . count($student_data));
        
        // Log sample data if available
        if (!empty($student_data)) {
            error_log("Sample student record: " . json_encode($student_data[0]));
        }
    } catch (Exception $e) {
        error_log("Student query error: " . $e->getMessage());
        error_log("SQL Error Code: " . $e->getCode());
        $student_data = [];
    }
    
    // Query for teacher attendance
    $sql = "
        SELECT 
            a.date,
            a.status,
            a.remarks,
            t.id as teacher_id,
            t.first_name,
            t.last_name,
            t.employee_id,
            t.photo
        FROM attendance a
        INNER JOIN teachers t ON a.teacher_id = t.id
        $teacher_where_clause
        ORDER BY a.date
    ";
    
    // Debug: Log the actual SQL query and parameters
    error_log("Teacher SQL Query: " . $sql);
    error_log("Teacher SQL Params: " . json_encode($teacher_sql_params));
    
    $stmt = $pdo->prepare($sql);
    try {
        $stmt->execute($teacher_sql_params);
        $teacher_data = $stmt->fetchAll();
        error_log("Teacher query executed successfully. Rows found: " . count($teacher_data));
    } catch (Exception $e) {
        error_log("Teacher query error: " . $e->getMessage());
        $teacher_data = [];
    }
    
    $report_data = [
        'students' => $student_data,
        'teachers' => $teacher_data,
        'filters' => [
            'report_type' => $report_type,
            'date' => $date_filter,
            'week' => $week_filter,
            'month' => $month_filter,
            'year' => $year_filter,
            'class_id' => $class_filter,
            'session' => $session_filter,
            'search' => $search_filter
        ]
    ];
    
    // Debug: Log the data counts
    error_log("Student data count: " . count($student_data));
    error_log("Teacher data count: " . count($teacher_data));
    error_log("Total report data count: " . (count($student_data) + count($teacher_data)));
}

// Get user info for sidebar
$user_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'User';
if (isset($_SESSION['user_id'])) {
    if ($_SESSION['user_role'] == 'teacher') {
        $stmt = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) as name FROM teachers WHERE user_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $result = $stmt->fetch();
        if ($result) {
            $user_name = $result['name'];
        }
    }
}

$current_page = basename($_SERVER['PHP_SELF']);
$sidebar_html = renderSidebar($current_page, $_SESSION['user_role'], $user_name);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>উপস্থিতি রিপোর্ট - <?php echo htmlspecialchars($system_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print {
            /* Override Bootstrap print styles */
            *, *:before, *:after {
                color: #000 !important;
                text-shadow: none !important;
                background: transparent !important;
                box-shadow: none !important;
            }
            a, a:visited {
                text-decoration: underline;
            }
            a[href]:after {
                content: " (" attr(href) ")";
            }
            abbr[title]:after {
                content: " (" attr(title) ")";
            }
            a[href^="#"]:after, a[href^="javascript:"]:after {
                content: "";
            }
            pre {
                white-space: pre-wrap !important;
            }
            pre, blockquote {
                border: 1px solid #999;
                page-break-inside: avoid;
            }
            thead {
                display: table-header-group;
            }
            tr, img {
                page-break-inside: avoid;
            }
            p, h2, h3 {
                orphans: 3;
                widows: 3;
            }
            h2, h3 {
                page-break-after: avoid;
            }
        }
    </style>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        @media print {
            @page {
                size: A4;
                margin: 0.5in;
                margin-top: 0.25in;
                margin-bottom: 0.25in;
            }
            .no-print {
                display: none !important;
            }
            .no-screen {
                display: block !important;
                visibility: visible !important;
            }
            .card {
                border: none;
                box-shadow: none;
                margin: 0;
                padding: 0;
                background-color: white !important;
            }
            .card-header {
                padding: 10px 0;
            }
            .row {
                display: flex;
                align-items: center;
                width: 100%;
            }
            .col-auto {
                flex: 0 0 auto;
            }
            .col {
                flex: 1;
            }
            .text-center {
                text-align: center !important;
            }
            .content-header,
            .card.mb-4:not(.report-card),
            .sidebar-container,
            .main-content .content-header,
            .floating-button {
                display: none !important;
            }
            
            body {
                font-size: 12px;
                margin: 0.5in;
                margin-top: 0.25in;
                margin-bottom: 0.25in;
                background-color: white !important;
                color: black !important;
                line-height: 1.4;
            }
            .table {
                background-color: white !important;
                color: black !important;
            }
            .table th, .table td {
                padding: 0.15rem;
                font-size: 10px;
                page-break-inside: avoid;
                background-color: white !important;
                color: black !important;
                border: 1px solid #000 !important;
                vertical-align: top;
            }
            
            .table th {
                font-weight: bold;
                background-color: #f2f2f2 !important;
                color: black !important;
            }
            
            .table {
                width: 100%;
                max-width: 100%;
                margin-bottom: 1rem;
                background-color: white !important;
                border-collapse: collapse;
            }
            
            .table-bordered th,
            .table-bordered td {
                border: 1px solid #000 !important;
            }
            
            .table-responsive {
                overflow-x: visible;
                overflow-y: visible;
            }
            .table-dark {
                background-color: #f8f9fa !important;
                color: black !important;
            }
            .print-header {
                margin-bottom: 15px;
                page-break-after: avoid;
                background-color: white !important;
                color: black !important;
                border: none !important;
                box-shadow: none !important;
                padding: 10px 0 !important;
            }
            
            .print-header .row {
                width: 100%;
                display: flex;
                margin: 0;
            }
            
            .print-header .col-2,
            .print-header .col-8 {
                padding: 0 10px;
            }
            
            .print-header h3 {
                font-size: 18px;
                margin: 5px 0;
                color: black !important;
            }
            
            .print-header p {
                font-size: 14px;
                margin: 3px 0;
                color: black !important;
            }
            
            .print-header h4 {
                font-size: 16px;
                margin: 5px 0;
                color: black !important;
            }
            
            /* Ensure content visibility in print */
            .report-card, .card.report-card {
                display: block !important;
                visibility: visible !important;
                opacity: 1 !important;
            }
            
            /* Ensure print header visibility in print mode */
            .print-header {
                display: block !important;
                visibility: visible !important;
                opacity: 1 !important;
            }
            
            /* Ensure all content is visible during print */
            .table-container {
                overflow: visible;
                page-break-inside: auto;
            }
            .attendance-badge {
                font-size: 9px;
                padding: 0.1rem 0.2rem;
            }
            .photo-cell {
                width: 25px;
                height: 25px;
                min-width: 25px;
                min-height: 25px;
            }
            
            /* Specific styling for print table */
            table#print-student-attendance-table, table#student-attendance-table {
                font-size: 10px;
                width: 100%;
                table-layout: fixed;
            }
                
                table#print-student-attendance-table th,
                table#print-student-attendance-table td,
                table#student-attendance-table th,
                table#student-attendance-table td {
                    padding: 4px;
                    word-wrap: break-word;
                    overflow-wrap: break-word;
                }
                
                /* Ensure proper column widths for print */
                table#print-student-attendance-table th:nth-child(1),
                table#print-student-attendance-table td:nth-child(1),
                table#student-attendance-table th:nth-child(1),
                table#student-attendance-table td:nth-child(1) {
                    width: 8%;
                }
                
                table#print-student-attendance-table th:nth-child(2),
                table#print-student-attendance-table td:nth-child(2),
                table#student-attendance-table th:nth-child(2),
                table#student-attendance-table td:nth-child(2) {
                    width: 15%;
                }
                
                table#print-student-attendance-table th:nth-child(3),
                table#print-student-attendance-table td:nth-child(3),
                table#student-attendance-table th:nth-child(3),
                table#student-attendance-table td:nth-child(3) {
                    width: 10%;
                }
                
                table#print-student-attendance-table th:nth-child(4),
                table#print-student-attendance-table td:nth-child(4),
                table#student-attendance-table th:nth-child(4),
                table#student-attendance-table td:nth-child(4) {
                    width: 8%;
                }
                
                table#print-student-attendance-table th:nth-child(5),
                table#print-student-attendance-table td:nth-child(5),
                table#student-attendance-table th:nth-child(5),
                table#student-attendance-table td:nth-child(5) {
                    width: 12%;
                }
                
                table#print-student-attendance-table th:nth-child(6),
                table#print-student-attendance-table td:nth-child(6),
                table#student-attendance-table th:nth-child(6),
                table#student-attendance-table td:nth-child(6) {
                    width: 10%;
                }
                
                table#print-student-attendance-table th:nth-child(7),
                table#print-student-attendance-table td:nth-child(7),
                table#student-attendance-table th:nth-child(7),
                table#student-attendance-table td:nth-child(7) {
                    width: 12%;
                }
                
                table#print-student-attendance-table th:nth-child(8),
                table#print-student-attendance-table td:nth-child(8),
                table#student-attendance-table th:nth-child(8),
                table#student-attendance-table td:nth-child(8) {
                    width: 15%;
                }
            /* Force text colors for print */
            h1, h2, h3, h4, h5, h6, p, div {
                color: black !important;
            }
            .bg-success, .bg-danger, .bg-warning, .bg-info {
                color: black !important;
                background-color: transparent !important;
            }
        }
        
        @media screen {
            .no-screen {
                display: none !important;
            }
        }
        .attendance-badge {
            padding: 0.25em 0.4em;
            font-size: 0.75em;
        }
        .photo-cell {
            width: 40px;
            height: 40px;
        }
        .photo-cell img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <div class="sidebar-container">
        <?php echo $sidebar_html; ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-file-alt me-2"></i>
                    উপস্থিতি রিপোর্ট
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / উপস্থিতি রিপোর্ট
                    <span class="ms-3 text-muted">
                        <i class="fas fa-clock me-1"></i>
                        <?php echo date('d F Y, l'); ?>
                    </span>
                </p>
            </div>
            
            <!-- Floating Sidebar Toggle Button -->
            <button class="sidebar-toggle-float" onclick="toggleSidebar()" title="সাইডবার টগল করুন">
                <i class="fas fa-bars"></i>
            </button>
            
            <!-- Content Body -->
            <div class="content-body">
                <div class="container-fluid mt-4">
                    
                    <!-- Message to guide user when no report has been generated yet -->
                    <?php if (!isset($_GET['generate']) && !$has_filters): ?>
                    <div class="alert alert-info mb-4">
                        <i class="fas fa-info-circle me-2"></i>
                        প্রথমে রিপোর্ট তৈরি করুন। ফিল্টার সেট করে "রিপোর্ট তৈরি" বাটনে ক্লিক করুন।
                    </div>
                    <?php endif; ?>
                    
                    <!-- Report Filters -->
                    <div class="card mb-4">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="fas fa-filter me-2"></i> রিপোর্ট ফিল্টার</h5>
                        </div>
                        <div class="card-body">
                            <form method="GET" id="reportForm">
                                <input type="hidden" name="generate" value="1">
                                
                                <div class="row mb-3">
                                    <div class="col-md-3">
                                        <label class="form-label">রিপোর্টের ধরন</label>
                                        <select class="form-select" name="report_type" id="reportType">
                                            <option value="daily" <?php echo $report_type == 'daily' ? 'selected' : ''; ?>>দৈনিক</option>
                                            <option value="weekly" <?php echo $report_type == 'weekly' ? 'selected' : ''; ?>>সাপ্তাহিক</option>
                                            <option value="monthly" <?php echo $report_type == 'monthly' ? 'selected' : ''; ?>>মাসিক</option>
                                            <option value="yearly" <?php echo $report_type == 'yearly' ? 'selected' : ''; ?>>বার্ষিক</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-3" id="dateContainer">
                                        <label class="form-label">তারিখ</label>
                                        <input type="date" class="form-control" name="date" value="<?php echo $date_filter; ?>">
                                    </div>
                                    
                                    <div class="col-md-3" id="weekContainer" style="display: none;">
                                        <label class="form-label">সপ্তাহ</label>
                                        <input type="week" class="form-control" name="week" value="<?php echo $week_filter; ?>">
                                    </div>
                                    
                                    <div class="col-md-3" id="monthContainer" style="display: none;">
                                        <label class="form-label">মাস</label>
                                        <input type="month" class="form-control" name="month" value="<?php echo $month_filter; ?>">
                                    </div>
                                    
                                    <div class="col-md-3" id="yearContainer" style="display: none;">
                                        <label class="form-label">বছর</label>
                                        <input type="number" class="form-control" name="year" value="<?php echo $year_filter; ?>" min="2000" max="2100">
                                    </div>
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-md-3">
                                        <label class="form-label">ক্লাস</label>
                                        <select class="form-select" name="class_id">
                                            <option value="0">সব ক্লাস</option>
                                            <?php foreach ($classes as $class): ?>
                                                <option value="<?php echo $class['id']; ?>" <?php echo $class_filter == $class['id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-3">
                                        <label class="form-label">সেশন</label>
                                        <select class="form-select" name="session">
                                            <option value="">সব সেশন</option>
                                            <?php foreach ($sessions as $session): ?>
                                                <option value="<?php echo htmlspecialchars($session); ?>" <?php echo $session_filter == $session ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($session); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <label class="form-label">খুঁজুন (নাম, আইডি, রোল)</label>
                                        <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search_filter); ?>" placeholder="নাম, আইডি বা রোল দিয়ে অনুসন্ধান...">
                                    </div>
                                    
                                    <div class="col-md-2">
                                        <label class="form-label">&nbsp;</label>
                                        <div class="d-grid">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-search me-1"></i> রিপোর্ট তৈরি
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-12 text-center">
                                        <button type="submit" class="btn btn-success me-2">
                                            <i class="fas fa-sync-alt me-1"></i> রিপোর্ট তৈরি
                                        </button>
                                        <button type="button" class="btn btn-primary" onclick="generateAndPrint()">
                                            <i class="fas fa-print me-1"></i> প্রিন্ট করুন
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Report Results -->
                    <?php if (isset($_GET['generate']) || !empty($report_data) || $has_filters): ?>
                    <div class="card report-card">
                        <!-- Print Header with Institution Information -->
                        <div class="card-header bg-light text-dark print-header no-screen">
                            <div class="container-fluid">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <div class="logo-container">
                                            <?php if (!empty($logo_image) && file_exists(__DIR__ . '/../' . ltrim($logo_image, '/'))): ?>
                                                <img src="../<?php echo $logo_image; ?>" 
                                                     alt="Institution Logo" 
                                                     style="height: <?php echo $logo_size; ?>px; opacity: <?php echo $logo_opacity; ?>; max-width: 100%;">
                                            <?php else: ?>
                                                <div style="height: <?php echo $logo_size; ?>px; width: <?php echo $logo_size; ?>px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 1px solid #ddd;">
                                                    <i class="fas fa-school" style="font-size: 24px; color: #6c757d;"></i>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="col text-center">
                                        <h3 class="mb-1" style="font-weight: bold; color: #2c3e50;"><?php echo htmlspecialchars($site_name); ?></h3>
                                        <p class="mb-1" style="font-size: 14px; color: #34495e;"><?php echo htmlspecialchars($site_address); ?></p>
                                        <h4 class="mb-1 text-success" style="font-weight: bold; color: #27ae60;">উপস্থিতি রিপোর্ট</h4>
                                        <?php 
                                        $report_period = '';
                                        switch ($report_type) {
                                            case 'daily':
                                                $report_period = 'দিনঃ ' . date('d-m-Y', strtotime($date_filter));
                                                break;
                                            case 'weekly':
                                                $start_date = date('d-m-Y', strtotime($week_filter . '-1'));
                                                $end_date = date('d-m-Y', strtotime($week_filter . '-7'));
                                                $report_period = 'সপ্তাহঃ ' . $start_date . ' থেকে ' . $end_date;
                                                break;
                                            case 'monthly':
                                                $report_period = 'মাসঃ ' . date('F Y', strtotime($month_filter . '-01'));
                                                break;
                                            case 'yearly':
                                                $report_period = 'বছরঃ ' . $year_filter;
                                                break;
                                        }
                                        ?>
                                        <p class="mb-0" style="font-size: 13px; color: #7f8c8d;">(<?php echo $report_period; ?>)</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Screen Header -->
                        <div class="card-header bg-success text-white no-print">
                            <h5 class="mb-0">
                                <i class="fas fa-chart-bar me-2"></i>
                                উপস্থিতি রিপোর্ট 
                                <small class="float-end">
                                    <?php echo $report_period; ?>
                                </small>
                            </h5>
                        </div>
                        <div class="card-body">
                            <!-- Attendance Summary Chart -->
                            <?php if (!empty($report_data['students']) || !empty($report_data['teachers'])): ?>
                            <div class="table-responsive mb-4">
                                <h6 class="mt-2 mb-3">উপস্থিতি সারাংশ চার্ট (ছুটির দিন বাদে)</h6>
                                
                                <?php
                                // Calculate attendance summary
                                $attendance_summary = [];
                                $total_working_days = 0;
                                
                                // Determine date range based on report type
                                if ($report_type == 'monthly') {
                                    $year = date('Y', strtotime($month_filter . '-01'));
                                    $month = date('m', strtotime($month_filter . '-01'));
                                    $days_in_month = date('t', strtotime($month_filter . '-01'));
                                    $start_date = "$year-$month-01";
                                    $end_date = "$year-$month-$days_in_month";
                                } elseif ($report_type == 'yearly') {
                                    $start_date = "$year_filter-01-01";
                                    $end_date = "$year_filter-12-31";
                                    $days_in_month = 365;
                                } else {
                                    // For daily/weekly reports, use a 30-day range
                                    $start_date = date('Y-m-01');
                                    $end_date = date('Y-m-t');
                                    $days_in_month = 30;
                                }
                                
                                // Count working days (exclude holidays and weekends)
                                $current_date = new DateTime($start_date);
                                $end_datetime = new DateTime($end_date);
                                
                                while ($current_date <= $end_datetime) {
                                    $date_str = $current_date->format('Y-m-d');
                                    $day_of_week = $current_date->format('N'); // 1=Monday, 7=Sunday
                                    
                                    // Skip weekends (Friday=5, Saturday=6 in some calendars, but typically 6=Saturday, 7=Sunday)
                                    // Also skip holidays
                                    if ($day_of_week != 6 && $day_of_week != 7 && !in_array($date_str, $holiday_dates)) {
                                        $total_working_days++;
                                    }
                                    
                                    $current_date->modify('+1 day');
                                }
                                
                                // Calculate student attendance summary
                                if (!empty($report_data['students'])) {
                                    $student_attendance_stats = [];
                                    
                                    // First, collect all unique students and initialize stats
                                    $unique_students = [];
                                    foreach ($report_data['students'] as $record) {
                                        $student_id = $record['student_id'];
                                        if (!isset($unique_students[$student_id])) {
                                            $unique_students[$student_id] = [
                                                'name' => $record['first_name'] . ' ' . $record['last_name'],
                                                'present' => 0,
                                                'absent' => 0,
                                                'late' => 0,
                                                'excused' => 0,
                                                'dates' => []
                                            ];
                                        }
                                        
                                        switch ($record['status']) {
                                            case 'present':
                                                $unique_students[$student_id]['present']++;
                                                $unique_students[$student_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                            case 'absent':
                                                $unique_students[$student_id]['absent']++;
                                                $unique_students[$student_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                            case 'late':
                                                $unique_students[$student_id]['late']++;
                                                $unique_students[$student_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                            case 'excused':
                                                $unique_students[$student_id]['excused']++;
                                                $unique_students[$student_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                        }
                                    }
                                    
                                    // Calculate absent days based on total working days minus days with attendance records
                                    foreach ($unique_students as $student_id => $data) {
                                        $days_with_records = count($data['dates']);
                                        $calculated_absent_days = max(0, $total_working_days - $days_with_records);
                                        
                                        // Add calculated absent days to actual absent days
                                        $actual_absent = $data['absent'];
                                        $total_absent = $calculated_absent_days + $actual_absent;
                                        
                                        $student_attendance_stats[$student_id] = [
                                            'name' => $data['name'],
                                            'present' => $data['present'],
                                            'absent' => $total_absent,
                                            'late' => $data['late'],
                                            'excused' => $data['excused']
                                        ];
                                    }
                                }
                                
                                // Calculate teacher attendance summary
                                if (!empty($report_data['teachers'])) {
                                    $teacher_attendance_stats = [];
                                    
                                    // First, collect all unique teachers and initialize stats
                                    $unique_teachers = [];
                                    foreach ($report_data['teachers'] as $record) {
                                        $teacher_id = $record['teacher_id'];
                                        if (!isset($unique_teachers[$teacher_id])) {
                                            $unique_teachers[$teacher_id] = [
                                                'name' => $record['first_name'] . ' ' . $record['last_name'],
                                                'present' => 0,
                                                'absent' => 0,
                                                'late' => 0,
                                                'excused' => 0,
                                                'dates' => []
                                            ];
                                        }
                                        
                                        switch ($record['status']) {
                                            case 'present':
                                                $unique_teachers[$teacher_id]['present']++;
                                                $unique_teachers[$teacher_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                            case 'absent':
                                                $unique_teachers[$teacher_id]['absent']++;
                                                $unique_teachers[$teacher_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                            case 'late':
                                                $unique_teachers[$teacher_id]['late']++;
                                                $unique_teachers[$teacher_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                            case 'excused':
                                                $unique_teachers[$teacher_id]['excused']++;
                                                $unique_teachers[$teacher_id]['dates'][$record['date']] = $record['status'];
                                                break;
                                        }
                                    }
                                    
                                    // Calculate absent days based on total working days minus days with attendance records
                                    foreach ($unique_teachers as $teacher_id => $data) {
                                        $days_with_records = count($data['dates']);
                                        $calculated_absent_days = max(0, $total_working_days - $days_with_records);
                                        
                                        // Add calculated absent days to actual absent days
                                        $actual_absent = $data['absent'];
                                        $total_absent = $calculated_absent_days + $actual_absent;
                                        
                                        $teacher_attendance_stats[$teacher_id] = [
                                            'name' => $data['name'],
                                            'present' => $data['present'],
                                            'absent' => $total_absent,
                                            'late' => $data['late'],
                                            'excused' => $data['excused']
                                        ];
                                    }
                                }
                                ?>
                                
                                <!-- Display working days info -->
                                <div class="alert alert-info mb-3">
                                    <strong>রিপোর্ট পিরিয়ড:</strong> <?php echo date('d-m-Y', strtotime($start_date)); ?> থেকে <?php echo date('d-m-Y', strtotime($end_date)); ?><br>
                                    <strong>মোট কার্যদিবস:</strong> <?php echo $total_working_days; ?> দিন<br>
                                    <strong>ছুটির দিন:</strong> <?php echo count($holiday_dates); ?> দিন
                                    <?php if (!empty($holidays)): ?>
                                        (<em><?php 
                                        $holiday_titles = array_column($holidays, 'title');
                                        echo implode(', ', array_slice($holiday_titles, 0, 3));
                                        if (count($holiday_titles) > 3) echo ' এবং আরও ' . (count($holiday_titles) - 3) . 'টি';
                                        ?></em>)
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Student Attendance Summary Table -->
                                <?php if (!empty($student_attendance_stats)): ?>
                                <h6 class="mb-2">ছাত্র/ছাত্রীদের উপস্থিতি সারাংশ</h6>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-sm">
                                        <thead class="table-dark">
                                            <tr>
                                                <th>নাম</th>
                                                <th>উপস্থিত</th>
                                                <th>অনুপস্থিত</th>
                                                <th>দেরি</th>
                                                <th>ছুটি</th>
                                                <th>উপস্থিতির হার (%)</th>
                                                <th>উপস্থিতির তারিখ সমূহ</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($student_attendance_stats as $student_id => $stats): 
                                                $total_attendance = $stats['present'] + $stats['absent'] + $stats['late'] + $stats['excused'];
                                                $attendance_rate = $total_working_days > 0 ? round((($stats['present'] + $stats['late']) / $total_working_days) * 100, 2) : 0;
                                                $rate_class = $attendance_rate >= 90 ? 'success' : ($attendance_rate >= 75 ? 'warning' : 'danger');
                                                
                                                // Collect attendance dates for this student
                                                $present_dates = [];
                                                $absent_dates = [];
                                                $student_recorded_dates = [];
                                                
                                                // First, collect recorded attendance dates
                                                foreach ($report_data['students'] as $record) {
                                                    if ($record['student_id'] == $student_id) {
                                                        $date_num = date('d', strtotime($record['date']));
                                                        $full_date = date('Y-m-d', strtotime($record['date']));
                                                        $student_recorded_dates[] = $full_date;
                                                        
                                                        if ($record['status'] == 'present' || $record['status'] == 'late') {
                                                            $present_dates[] = $date_num;
                                                        } elseif ($record['status'] == 'absent') {
                                                            $absent_dates[] = $date_num;
                                                        }
                                                    }
                                                }
                                                
                                                // Now calculate the missing dates (should be absent) within the working days
                                                $current_date = new DateTime($start_date);
                                                $end_datetime = new DateTime($end_date);
                                                
                                                while ($current_date <= $end_datetime) {
                                                    $date_str = $current_date->format('Y-m-d');
                                                    $day_of_week = $current_date->format('N'); // 1=Monday, 7=Sunday
                                                    
                                                    // Check if it's a working day (not weekend and not holiday)
                                                    if ($day_of_week != 6 && $day_of_week != 7 && !in_array($date_str, $holiday_dates)) {
                                                        // If this working day is not in the recorded dates, it should be marked as absent
                                                        if (!in_array($date_str, $student_recorded_dates)) {
                                                            $missing_date_num = $current_date->format('d');
                                                            if (!in_array($missing_date_num, $absent_dates)) {
                                                                $absent_dates[] = $missing_date_num;
                                                            }
                                                        }
                                                    }
                                                    
                                                    $current_date->modify('+1 day');
                                                }
                                                
                                                // Sort dates numerically
                                                sort($present_dates, SORT_NUMERIC);
                                                sort($absent_dates, SORT_NUMERIC);
                                            ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($stats['name']); ?></td>
                                                <td class="text-success"><?php echo $stats['present']; ?></td>
                                                <td class="text-danger"><?php echo $stats['absent']; ?></td>
                                                <td class="text-warning"><?php echo $stats['late']; ?></td>
                                                <td class="text-info"><?php echo $stats['excused']; ?></td>
                                                <td class="fw-bold text-<?php echo $rate_class; ?>"><?php echo $attendance_rate; ?>%</td>
                                                <td>
                                                    <?php if (!empty($present_dates) || !empty($absent_dates)): ?>
                                                        <small>
                                                            <?php 
                                                            $date_parts = [];
                                                            if (!empty($present_dates)) {
                                                                $date_parts[] = 'উপস্থিত: ' . implode(', ', $present_dates);
                                                            }
                                                            if (!empty($absent_dates)) {
                                                                $date_parts[] = 'অনুপস্থিত: ' . implode(', ', $absent_dates);
                                                            }
                                                            echo implode('<br>', $date_parts);
                                                            ?>
                                                        </small>
                                                    <?php else: ?>
                                                        <small class="text-muted">কোন উপস্থিতি রেকর্ড নেই</small>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Teacher Attendance Summary Table -->
                                <?php if (!empty($teacher_attendance_stats)): ?>
                                <h6 class="mt-4 mb-2">শিক্ষকদের উপস্থিতি সারাংশ</h6>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-sm">
                                        <thead class="table-dark">
                                            <tr>
                                                <th>নাম</th>
                                                <th>উপস্থিত</th>
                                                <th>অনুপস্থিত</th>
                                                <th>দেরি</th>
                                                <th>ছুটি</th>
                                                <th>উপস্থিতির হার (%)</th>
                                                <th>উপস্থিতির তারিখ সমূহ</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($teacher_attendance_stats as $teacher_id => $stats): 
                                                $total_attendance = $stats['present'] + $stats['absent'] + $stats['late'] + $stats['excused'];
                                                $attendance_rate = $total_working_days > 0 ? round((($stats['present'] + $stats['late']) / $total_working_days) * 100, 2) : 0;
                                                $rate_class = $attendance_rate >= 90 ? 'success' : ($attendance_rate >= 75 ? 'warning' : 'danger');
                                                
                                                // Collect attendance dates for this teacher
                                                $present_dates = [];
                                                $absent_dates = [];
                                                $teacher_recorded_dates = [];
                                                
                                                // First, collect recorded attendance dates
                                                foreach ($report_data['teachers'] as $record) {
                                                    if ($record['teacher_id'] == $teacher_id) {
                                                        $date_num = date('d', strtotime($record['date']));
                                                        $full_date = date('Y-m-d', strtotime($record['date']));
                                                        $teacher_recorded_dates[] = $full_date;
                                                        
                                                        if ($record['status'] == 'present' || $record['status'] == 'late') {
                                                            $present_dates[] = $date_num;
                                                        } elseif ($record['status'] == 'absent') {
                                                            $absent_dates[] = $date_num;
                                                        }
                                                    }
                                                }
                                                
                                                // Now calculate the missing dates (should be absent) within the working days
                                                $current_date = new DateTime($start_date);
                                                $end_datetime = new DateTime($end_date);
                                                
                                                while ($current_date <= $end_datetime) {
                                                    $date_str = $current_date->format('Y-m-d');
                                                    $day_of_week = $current_date->format('N'); // 1=Monday, 7=Sunday
                                                    
                                                    // Check if it's a working day (not weekend and not holiday)
                                                    if ($day_of_week != 6 && $day_of_week != 7 && !in_array($date_str, $holiday_dates)) {
                                                        // If this working day is not in the recorded dates, it should be marked as absent
                                                        if (!in_array($date_str, $teacher_recorded_dates)) {
                                                            $missing_date_num = $current_date->format('d');
                                                            if (!in_array($missing_date_num, $absent_dates)) {
                                                                $absent_dates[] = $missing_date_num;
                                                            }
                                                        }
                                                    }
                                                    
                                                    $current_date->modify('+1 day');
                                                }
                                                
                                                // Sort dates numerically
                                                sort($present_dates, SORT_NUMERIC);
                                                sort($absent_dates, SORT_NUMERIC);
                                            ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($stats['name']); ?></td>
                                                <td class="text-success"><?php echo $stats['present']; ?></td>
                                                <td class="text-danger"><?php echo $stats['absent']; ?></td>
                                                <td class="text-warning"><?php echo $stats['late']; ?></td>
                                                <td class="text-info"><?php echo $stats['excused']; ?></td>
                                                <td class="fw-bold text-<?php echo $rate_class; ?>"><?php echo $attendance_rate; ?>%</td>
                                                <td>
                                                    <?php if (!empty($present_dates) || !empty($absent_dates)): ?>
                                                        <small>
                                                            <?php 
                                                            $date_parts = [];
                                                            if (!empty($present_dates)) {
                                                                $date_parts[] = 'উপস্থিত: ' . implode(', ', $present_dates);
                                                            }
                                                            if (!empty($absent_dates)) {
                                                                $date_parts[] = 'অনুপস্থিত: ' . implode(', ', $absent_dates);
                                                            }
                                                            echo implode('<br>', $date_parts);
                                                            ?>
                                                        </small>
                                                    <?php else: ?>
                                                        <small class="text-muted">কোন উপস্থিতি রেকর্ড নেই</small>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Legend -->
                                <div class="mt-3">
                                    <small class="text-muted">
                                        <strong>উপস্থিতির হার:</strong> 
                                        <span class="badge bg-success">90%+</span> খুব ভালো | 
                                        <span class="badge bg-warning">75-89%</span> ভালো | 
                                        <span class="badge bg-danger">&lt;75%</span> উন্নতির প্রয়োজন
                                    </small>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Student Attendance Table -->
                            <?php if (!empty($report_data['students'])): ?>
                            <div class="table-responsive">
                                <h6 class="mt-4 mb-3">ছাত্র/ছাত্রীদের উপস্থিতি</h6>
                                <table id="student-attendance-table" class="table table-bordered table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>ছবি</th>
                                            <th>নাম</th>
                                            <th>ছাত্র আইডি</th>
                                            <th>রোল</th>
                                            <th>ক্লাস</th>
                                            <th>তারিখ</th>
                                            <th>অবস্থা</th>
                                            <th>মন্তব্য</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($report_data['students'] as $record): ?>
                                        <tr>
                                            <td class="photo-cell">
                                                <?php if (!empty($record['photo']) && file_exists(__DIR__ . '/../' . ltrim($record['photo'], '/'))): ?>
                                                    <img src="../<?php echo $record['photo']; ?>" alt="Photo" class="img-fluid rounded-circle">
                                                <?php else: ?>
                                                    <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-user text-white"></i>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td><a href="#student_<?php echo $record['student_id']; ?>" onclick="showStudentAttendance(<?php echo $record['student_id']; ?>, '<?php echo addslashes(htmlspecialchars($record['first_name'] . ' ' . $record['last_name'])); ?>', 'student')" style="cursor:pointer;text-decoration:underline;"><?php echo htmlspecialchars($record['first_name'] . ' ' . $record['last_name']); ?></a></td>
                                            <td><?php echo htmlspecialchars($record['student_std_id']); ?></td>
                                            <td><?php echo htmlspecialchars($record['roll_number']); ?></td>
                                            <td><?php echo htmlspecialchars($record['class_name'] . ' - ' . $record['class_section']); ?></td>
                                            <td><?php echo date('d-m-Y', strtotime($record['date'])); ?></td>
                                            <td>
                                                <?php
                                                $status_class = '';
                                                $status_icon = '';
                                                switch ($record['status']) {
                                                    case 'present':
                                                        $status_class = 'bg-success';
                                                        $status_icon = 'fa-check';
                                                        break;
                                                    case 'absent':
                                                        $status_class = 'bg-danger';
                                                        $status_icon = 'fa-times';
                                                        break;
                                                    case 'late':
                                                        $status_class = 'bg-warning';
                                                        $status_icon = 'fa-clock';
                                                        break;
                                                    case 'excused':
                                                        $status_class = 'bg-info';
                                                        $status_icon = 'fa-user-clock';
                                                        break;
                                                    default:
                                                        $status_class = 'bg-secondary';
                                                        $status_icon = 'fa-question';
                                                }
                                                ?>
                                                <span class="badge <?php echo $status_class; ?> attendance-badge">
                                                    <i class="fas <?php echo $status_icon; ?> me-1"></i>
                                                    <?php 
                                                    switch ($record['status']) {
                                                        case 'present': echo 'উপস্থিত'; break;
                                                        case 'absent': echo 'অনুপস্থিত'; break;
                                                        case 'late': echo 'দেরি'; break;
                                                        case 'excused': echo 'ছুটি'; break;
                                                        default: echo 'অজানা';
                                                    }
                                                    ?>
                                                </span>
                                            </td>
                                            <td><?php echo htmlspecialchars($record['remarks']); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Teacher Attendance Table -->
                            <?php if (!empty($report_data['teachers'])): ?>
                            <div class="table-responsive mt-4">
                                <h6 class="mt-4 mb-3">শিক্ষকদের উপস্থিতি</h6>
                                <table id="teacher-attendance-table" class="table table-bordered table-sm">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>ছবি</th>
                                            <th>নাম</th>
                                            <th>কর্মচারী আইডি</th>
                                            <th>তারিখ</th>
                                            <th>অবস্থা</th>
                                            <th>মন্তব্য</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($report_data['teachers'] as $record): ?>
                                        <tr>
                                            <td class="photo-cell">
                                                <?php if (!empty($record['photo']) && file_exists(__DIR__ . '/../' . ltrim($record['photo'], '/'))): ?>
                                                    <img src="../<?php echo $record['photo']; ?>" alt="Photo" class="img-fluid rounded-circle">
                                                <?php else: ?>
                                                    <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <i class="fas fa-user text-white"></i>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td><a href="#teacher_<?php echo $record['teacher_id']; ?>" onclick="showStudentAttendance(<?php echo $record['teacher_id']; ?>, '<?php echo addslashes(htmlspecialchars($record['first_name'] . ' ' . $record['last_name'])); ?>', 'teacher')" style="cursor:pointer;text-decoration:underline;"><?php echo htmlspecialchars($record['first_name'] . ' ' . $record['last_name']); ?></a></td>
                                            <td><?php echo htmlspecialchars($record['employee_id']); ?></td>
                                            <td><?php echo date('d-m-Y', strtotime($record['date'])); ?></td>
                                            <td>
                                                <?php
                                                $status_class = '';
                                                $status_icon = '';
                                                switch ($record['status']) {
                                                    case 'present':
                                                        $status_class = 'bg-success';
                                                        $status_icon = 'fa-check';
                                                        break;
                                                    case 'absent':
                                                        $status_class = 'bg-danger';
                                                        $status_icon = 'fa-times';
                                                        break;
                                                    case 'late':
                                                        $status_class = 'bg-warning';
                                                        $status_icon = 'fa-clock';
                                                        break;
                                                    case 'excused':
                                                        $status_class = 'bg-info';
                                                        $status_icon = 'fa-user-clock';
                                                        break;
                                                    default:
                                                        $status_class = 'bg-secondary';
                                                        $status_icon = 'fa-question';
                                                }
                                                ?>
                                                <span class="badge <?php echo $status_class; ?> attendance-badge">
                                                    <i class="fas <?php echo $status_icon; ?> me-1"></i>
                                                    <?php 
                                                    switch ($record['status']) {
                                                        case 'present': echo 'উপস্থিত'; break;
                                                        case 'absent': echo 'অনুপস্থিত'; break;
                                                        case 'late': echo 'দেরি'; break;
                                                        case 'excused': echo 'ছুটি'; break;
                                                        default: echo 'অজানা';
                                                    }
                                                    ?>
                                                </span>
                                            </td>
                                            <td><?php echo htmlspecialchars($record['remarks']); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (empty($report_data['students']) && empty($report_data['teachers'])): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-exclamation-triangle fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">কোন উপস্থিতি রেকর্ড পাওয়া যায়নি</h5>
                                <p class="text-muted">নির্বাচিত ফিল্টারের জন্য কোন উপস্থিতি রেকর্ড পাওয়া যায়নি।</p>
                                <div class="alert alert-info mt-3">
                                    <strong>Debug Info:</strong><br>
                                    Students: <?php echo count($report_data['students']); ?><br>
                                    Teachers: <?php echo count($report_data['teachers']); ?><br>
                                    Total: <?php echo (count($report_data['students']) + count($report_data['teachers'])); ?><br>
                                    Has Filters: <?php echo $has_filters ? 'Yes' : 'No'; ?><br>
                                    Report Type: <?php echo htmlspecialchars($report_type); ?><br>
                                    Date Filter: <?php echo htmlspecialchars($date_filter); ?><br>
                                    Class Filter: <?php echo $class_filter; ?><br>
                                    Session Filter: <?php echo htmlspecialchars($session_filter); ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        
                        <!-- Print and Export Buttons for Generated Report -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <button class="btn btn-success me-2 no-print" onclick="generateAndPrint()">
                                    <i class="fas fa-print me-1"></i> প্রিন্ট করুন
                                </button>
                                <button class="btn btn-primary me-2 no-print" onclick="comprehensivePrint()">
                                    <i class="fas fa-file-alt me-1"></i> কমপ্রিহেন্সিভ প্রিন্ট
                                </button>
                                <button class="btn btn-info no-print" onclick="exportToPDF()">
                                    <i class="fas fa-file-pdf me-1"></i> PDF এ সংরক্ষণ
                                </button>
                            </div>
                        </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="../assets/js/script.js"></script>
    <script>
        // Toggle date inputs based on report type
        document.getElementById('reportType').addEventListener('change', function() {
            const type = this.value;
            
            document.getElementById('dateContainer').style.display = type === 'daily' ? 'block' : 'none';
            document.getElementById('weekContainer').style.display = type === 'weekly' ? 'block' : 'none';
            document.getElementById('monthContainer').style.display = type === 'monthly' ? 'block' : 'none';
            document.getElementById('yearContainer').style.display = type === 'yearly' ? 'block' : 'none';
        });
        
        // Initialize the form based on current selection
        document.getElementById('reportType').dispatchEvent(new Event('change'));
        
        function exportToPDF() {
            // Check if report has been generated
            const reportCard = document.querySelector('.report-card');
            
            if (!reportCard) {
                alert('পিডিএফ এক্সপোর্টের জন্য প্রথমে রিপোর্ট তৈরি করুন।');
                return;
            }
            
            // Show loading message
            const originalButtonText = event.target.innerHTML;
            event.target.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> পিডিএফ তৈরি হচ্ছে...';
            event.target.disabled = true;
            
            try {
                // Initialize jsPDF
                const { jsPDF } = window.jspdf;
                
                // Use html2canvas and jsPDF for PDF generation
                html2canvas(reportCard, {
                    scale: 2,
                    useCORS: true,
                    logging: false,
                    backgroundColor: '#ffffff',
                    onclone: function(clonedDoc) {
                        // Ensure all elements are visible in the clone
                        const elements = clonedDoc.querySelectorAll('*');
                        elements.forEach(el => {
                            el.style.visibility = 'visible';
                            el.style.display = 'block';
                        });
                    }
                }).then(canvas => {
                    const imgData = canvas.toDataURL('image/png');
                    const pdf = new jsPDF('p', 'mm', 'a4');
                    
                    // Calculate dimensions
                    const imgWidth = 210; // A4 width in mm
                    const pageHeight = 297; // A4 height in mm
                    const imgHeight = canvas.height * imgWidth / canvas.width;
                    let heightLeft = imgHeight;
                    
                    let position = 0;
                    
                    // Add image to PDF
                    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                    heightLeft -= pageHeight;
                    
                    // Add additional pages if needed
                    while (heightLeft >= 0) {
                        position = heightLeft - imgHeight;
                        pdf.addPage();
                        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                        heightLeft -= pageHeight;
                    }
                    
                    // Generate filename
                    const now = new Date();
                    const dateString = now.toISOString().split('T')[0];
                    const fileName = `attendance_report_${dateString}.pdf`;
                    
                    // Save PDF
                    pdf.save(fileName);
                    
                    // Restore button
                    event.target.innerHTML = originalButtonText;
                    event.target.disabled = false;
                    
                    alert('পিডিএফ সফলভাবে ডাউনলোড হয়েছে!');
                }).catch(error => {
                    console.error('PDF generation error:', error);
                    alert('পিডিএফ তৈরিতে সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।');
                    event.target.innerHTML = originalButtonText;
                    event.target.disabled = false;
                });
            } catch (error) {
                console.error('PDF generation error:', error);
                alert('পিডিএফ তৈরিতে সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।');
                event.target.innerHTML = originalButtonText;
                event.target.disabled = false;
            }
        }
        
        <?php if (isset($_GET['generate']) || $has_filters): ?>
        function showStudentAttendance(studentId, studentName, type) {
            // Create modal or expandable section to show individual student attendance
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.id = 'studentAttendanceModal';
            modal.tabIndex = -1;
            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">\${studentName} - ব্যক্তিগত উপস্থিতি রিপোর্ট</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body" id="studentAttendanceContent">
                            <p>লোড হচ্ছে...</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                            <button type="button" class="btn btn-primary" onclick="printStudentAttendance(\${studentId}, '\${studentName.replace(/'/g, "\\'")}', '\${type}')">প্রিন্ট করুন</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            // Fetch and display student attendance data
            fetchIndividualAttendance(studentId, studentName, type);
            
            // Show the modal
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            
            // Remove modal from DOM when hidden
            modal.addEventListener('hidden.bs.modal', function () {
                modal.remove();
            });
        }
        
        function fetchIndividualAttendance(personId, personName, type) {
            // Since we already have the data, filter and display it based on type
            let attendanceData = [];
            if(type === 'student') {
                const allStudents = <?php echo json_encode($student_data); ?>;
                attendanceData = allStudents.filter(record => record.student_id == personId);
            } else if(type === 'teacher') {
                const allTeachers = <?php echo json_encode($teacher_data); ?>;
                attendanceData = allTeachers.filter(record => record.teacher_id == personId);
            }
            
            if (attendanceData.length === 0) {
                document.getElementById('studentAttendanceContent').innerHTML = '<p>এই ব্যক্তির জন্য কোন উপস্থিতি রেকর্ড পাওয়া যায়নি।</p>';
                return;
            }
            
            let content = `
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-dark">
                            <tr>
                                <th>তারিখ</th>
                                <th>অবস্থা</th>
                                <th>মন্তব্য</th>
                            </tr>
                        </thead>
                        <tbody>`;
            
            attendanceData.forEach(record => {
                const statusText = getStatusText(record.status);
                const statusClass = getStatusClass(record.status);
                content += `
                    <tr>
                        <td>\${formatDate(record.date)}</td>
                        <td><span class="badge \${statusClass}">\${statusText}</span></td>
                        <td>\${record.remarks || ''}</td>
                    </tr>`;
            });
            
            content += `</tbody></table></div>`;
            
            document.getElementById('studentAttendanceContent').innerHTML = content;
        }
        
        function getStatusText(status) {
            switch(status) {
                case 'present': return 'উপস্থিত';
                case 'absent': return 'অনুপস্থিত';
                case 'late': return 'দেরি';
                case 'excused': return 'ছুটি';
                default: return 'অজানা';
            }
        }
        
        function getStatusClass(status) {
            switch(status) {
                case 'present': return 'bg-success';
                case 'absent': return 'bg-danger';
                case 'late': return 'bg-warning';
                case 'excused': return 'bg-info';
                default: return 'bg-secondary';
            }
        }
        
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('bn-BD', { day: 'numeric', month: 'short', year: 'numeric' });
        }
        
        function printStudentAttendance(personId, personName, type) {
            // Create a new window with just the person's attendance for printing
            const printWindow = window.open('', '_blank');
            
            // Prepare the data based on type
            let attendanceData = [];
            if(type === 'student') {
                const allStudents = <?php echo json_encode($student_data); ?>;
                attendanceData = allStudents.filter(record => record.student_id == personId);
            } else if(type === 'teacher') {
                const allTeachers = <?php echo json_encode($teacher_data); ?>;
                attendanceData = allTeachers.filter(record => record.teacher_id == personId);
            }
            
            // Prepare report type text based on the current report type
            let reportTypeText = '';
            <?php 
            switch ($report_type) {
                case 'daily': 
                    echo "reportTypeText = 'দৈনিক (" . date('d-m-Y', strtotime($date_filter)) . ")';";
                    break;
                case 'weekly': 
                    $start_date = date('d-m-Y', strtotime($week_filter . '-1')); 
                    $end_date = date('d-m-Y', strtotime($week_filter . '-7')); 
                    echo "reportTypeText = 'সাপ্তাহিক (" . $start_date . " থেকে " . $end_date . ")';";
                    break;
                case 'monthly': 
                    echo "reportTypeText = 'মাসিক (" . date('F Y', strtotime($month_filter . '-01')) . ")';";
                    break;
                case 'yearly': 
                    echo "reportTypeText = 'বার্ষিক (" . $year_filter . ")';";
                    break;
            }
            ?>
            
            // Get institutional information
            const siteName = `<?php echo addslashes(htmlspecialchars($site_name)); ?>`;
            const siteAddress = `<?php echo addslashes(htmlspecialchars($site_address)); ?>`;
            const logoImage = `<?php echo addslashes($logo_image ? '../' . $logo_image : ''); ?>`;
            const logoSize = <?php echo $logo_size; ?>;
            const logoOpacity = <?php echo $logo_opacity; ?>;
            
            // Build the HTML content with institutional header
            let content = `
                <html>
                <head>
                    <title>\${personName} - উপস্থিতি রিপোর্ট</title>
                    <style>
                        body { font-family: Arial, sans-serif; margin: 20px; }
                        table { width: 100%; border-collapse: collapse; }
                        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                        th { background-color: #f2f2f2; }
                        .header { text-align: center; margin-bottom: 20px; }
                        .institution-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; border-bottom: 2px solid #333; padding-bottom: 10px; }
                        .logo-container { text-align: center; width: 100px; }
                        .logo-container img { height: \${logoSize}px; opacity: \${logoOpacity}; max-width: 100%; }
                        .logo-placeholder { height: \${logoSize}px; width: \${logoSize}px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 1px solid #ddd; }
                        .institution-info { flex-grow: 1; text-align: center; }
                        .institution-name { font-size: 18px; font-weight: bold; margin-bottom: 5px; }
                        .institution-address { font-size: 14px; margin-bottom: 5px; }
                        .report-title { font-size: 16px; font-weight: bold; color: #28a745; margin-bottom: 5px; }
                        .report-period { font-size: 14px; }
                        .status-badge { padding: 4px 8px; border-radius: 4px; color: white; }
                        .bg-success { background-color: #28a745; }
                        .bg-danger { background-color: #dc3545; }
                        .bg-warning { background-color: #ffc107; color: black; }
                        .bg-info { background-color: #17a2b8; }
                        .bg-secondary { background-color: #6c757d; }
                    </style>
                </head>
                <body>`;
            
            // Add institutional header
            const logoHtml = logoImage ? 
                `<img src="\${logoImage}" alt="Institution Logo">` : 
                `<div class="logo-placeholder"><i class="fas fa-school" style="font-size: 24px; color: #6c757d;"></i></div>`;
            
            content += `
                <div class="institution-header">
                    <div class="logo-container">
                        \${logoHtml}
                    </div>
                    <div class="institution-info">
                        <div class="institution-name">\${siteName}</div>
                        <div class="institution-address">\${siteAddress}</div>
                        <div class="report-title">ব্যক্তিগত উপস্থিতি রিপোর্ট</div>
                        <div class="report-period">(\${personName} - \${reportTypeText})</div>
                    </div>
                    <div style="width: 100px;"></div>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>তারিখ</th>
                            <th>অবস্থা</th>
                            <th>মন্তব্য</th>
                        </tr>
                    </thead>
                    <tbody>`;
            
            attendanceData.forEach(record => {
                const statusText = getStatusText(record.status);
                const statusClass = getStatusClass(record.status).replace('bg-', '');
                content += `
                    <tr>
                        <td>\${formatDate(record.date)}</td>
                        <td><span class="status-badge \${statusClass}">\${statusText}</span></td>
                        <td>\${record.remarks || ''}</td>
                    </tr>`;
            });
            
            content += `</tbody></table></body></html>`;
            
            printWindow.document.write(content);
            printWindow.document.close();
            printWindow.focus();
            
            setTimeout(() => {
                // Small delay to ensure content is rendered before printing
                printWindow.print();
                printWindow.close();
            }, 500);
        }
        
        function generateAndPrint() {
            // First check if report has been generated
            const reportCard = document.querySelector('.report-card');
                            
            if (!reportCard) {
                // If no report card exists, submit the form to generate the report
                const reportForm = document.getElementById('reportForm');
                if (reportForm) {
                    // Add the generate parameter if it doesn't exist
                    let generateInput = reportForm.querySelector('input[name="generate"]');
                    if (!generateInput) {
                        generateInput = document.createElement('input');
                        generateInput.type = 'hidden';
                        generateInput.name = 'generate';
                        generateInput.value = '1';
                        reportForm.appendChild(generateInput);
                    }
                            
                    // Submit the form to generate the report
                    reportForm.submit();
                } else {
                    alert('রিপোর্ট ফর্ম পাওয়া যায়নি। পৃষ্ঠাটি রিফ্রেশ করুন এবং আবার চেষ্টা করুন।');
                }
            } else {
                // Report exists, proceed with printing
                console.log('✓ Found report card - proceeding to print');
                        
                // Ensure all content is visible before printing
                setTimeout(function() {
                    // Force visibility of all report elements
                    if (reportCard) {
                        reportCard.style.display = 'block !important';
                        reportCard.style.visibility = 'visible !important';
                        reportCard.style.opacity = '1 !important';
                                
                        // Also make sure print header is visible
                        const printHeader = reportCard.querySelector('.print-header');
                        if (printHeader) {
                            printHeader.style.display = 'block !important';
                            printHeader.style.visibility = 'visible !important';
                        }
                                
                        // Make sure all print-related elements are visible
                        const printElements = reportCard.querySelectorAll('.no-print');
                        printElements.forEach(element => {
                            element.style.display = 'block !important';
                        });
                                
                        // Force all table elements to be visible
                        const tableElements = reportCard.querySelectorAll('table, thead, tbody, tr, th, td');
                        tableElements.forEach(element => {
                            element.style.display = 'table !important';
                            element.style.visibility = 'visible !important';
                        });
                                
                        // Force all text elements to be visible
                        const textElements = reportCard.querySelectorAll('h1, h2, h3, h4, h5, h6, p, div, span, i, strong, b, em');
                        textElements.forEach(element => {
                            element.style.visibility = 'visible !important';
                            element.style.display = 'inline-block !important';
                        });
                    }
                            
                    // Trigger print after a brief delay to ensure everything renders
                    setTimeout(function() {
                        // Scroll to the report card to ensure it's loaded
                        reportCard?.scrollIntoView({behavior: 'auto'});
                                
                        // Force a redraw before printing
                        window.dispatchEvent(new Event('resize'));
                                
                        // Give a little more time for rendering
                        window.print();
                    }, 1000);
                }, 300); // Delay to ensure everything renders
            }
        }
        
        // Final function to ensure all content prints
        function ensurePrintContent() {
            // Force all elements to be visible for printing
            const allElements = document.querySelectorAll('*');
            allElements.forEach(el => {
                if (el.classList.contains('no-print')) {
                    el.style.display = 'block !important';
                }
            });
            
            // Make sure all tables are properly formatted
            const tables = document.querySelectorAll('table');
            tables.forEach(table => {
                table.style.width = '100%';
                table.style.borderCollapse = 'collapse';
            });
            
            // Force print after ensuring all content is visible
            setTimeout(() => {
                window.print();
            }, 500);
        }
        
        // New comprehensive print function that ensures all content prints
        function comprehensivePrint() {
            // Get the report card
            const reportCard = document.querySelector('.report-card');
            
            if (!reportCard) {
                alert('প্রিন্টের জন্য রিপোর্ট খুঁজে পাওয়া যায়নি। প্রথমে রিপোর্ট তৈরি করুন।');
                return;
            }
            
            // Create a new window for printing
            const printWindow = window.open('', '_blank');
            
            // Clone the report card and prepare print content
            const reportClone = reportCard.cloneNode(true);
            
            // Create print-friendly HTML
            const printContent = `
                <!DOCTYPE html>
                <html lang="bn">
                <head>
                    <meta charset="UTF-8">
                    <title>উপস্থিতি রিপোর্ট - প্রিন্ট</title>
                    <style>
                        @page {
                            size: A4;
                            margin: 0.5in;
                            margin-top: 0.25in;
                            margin-bottom: 0.25in;
                        }
                        body { 
                            font-family: Arial, sans-serif; 
                            font-size: 12px; 
                            margin: 0.5in; 
                            margin-top: 0.25in;
                            margin-bottom: 0.25in;
                            color: black !important; 
                            background: white !important; 
                            line-height: 1.4;
                        }
                        .card { 
                            border: none; 
                            box-shadow: none; 
                            margin: 0; 
                            padding: 0; 
                            background: white !important; 
                            color: black !important; 
                        }
                        .card-header { 
                            padding: 10px 0;
                        }
                        .row { 
                            display: flex; 
                            align-items: center; 
                            width: 100%;
                        }
                        .col-auto { 
                            flex: 0 0 auto; 
                        }
                        .col { 
                            flex: 1;
                        }
                        .text-center { 
                            text-align: center !important; 
                        }
                        .logo-container { 
                            text-align: left; 
                        }
                        .table { 
                            width: 100%; 
                            border-collapse: collapse; 
                            background: white !important; 
                            color: black !important; 
                            margin: 20px 0;
                        }
                        .table th, .table td { 
                            border: 1px solid #000; 
                            padding: 6px; 
                            font-size: 11px; 
                            background: white !important; 
                            color: black !important; 
                            vertical-align: top;
                        }
                        .table th { 
                            background-color: #f2f2f2 !important; 
                            font-weight: bold; 
                            text-align: center;
                        }
                        h1, h2, h3, h4, h5, h6, p, div, span, a { 
                            color: black !important; 
                            background: transparent !important; 
                            margin: 5px 0;
                        }
                        h3 {
                            font-weight: bold !important;
                            color: #2c3e50 !important;
                        }
                        h4 {
                            font-weight: bold !important;
                            color: #27ae60 !important;
                        }
                        p {
                            color: #34495e !important;
                        }
                        img { 
                            max-width: 50px; 
                            max-height: 50px; 
                            display: block;
                        }
                        @media print {
                            @page { size: A4; margin: 0.5in; margin-top: 0.25in; margin-bottom: 0.25in; }
                            body { 
                                margin: 0.5in; 
                                margin-top: 0.25in;
                                margin-bottom: 0.25in;
                                font-size: 12px;
                                line-height: 1.4;
                            }
                            * { 
                                color: black !important; 
                                background: transparent !important; 
                                box-shadow: none !important; 
                                -webkit-print-color-adjust: exact !important;
                                color-adjust: exact !important;
                            }
                            .no-print { display: none !important; }
                        }
                    </style>
                </head>
                <body>` + reportClone.outerHTML + `</body>
                </html>
            `;
            
            // Write the content to the new window
            printWindow.document.write(printContent);
            printWindow.document.close();
            
            // Wait for content to load and then print
            printWindow.onload = function() {
                setTimeout(() => {
                    printWindow.focus();
                    printWindow.print();
                    printWindow.close();
                }, 1000);
            };
        }
        
        <?php endif; ?>
    </script>
</body>
</html>