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

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

// Get all classes for filter dropdown
$classes_stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name");
$classes = $classes_stmt->fetchAll();

// Get all unique sessions from students table
$sessions_stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC");
$sessions = $sessions_stmt->fetchAll();

// Get filter parameters
$class_id = isset($_GET['class_id']) ? $_GET['class_id'] : '';
$status_filter = isset($_GET['status_filter']) ? $_GET['status_filter'] : '';
$gender_filter = isset($_GET['gender_filter']) ? $_GET['gender_filter'] : '';
$session_filter = isset($_GET['session_filter']) ? trim($_GET['session_filter']) : '';
$search_text = isset($_GET['search_text']) ? trim($_GET['search_text']) : '';
$search_by = isset($_GET['search_by']) ? $_GET['search_by'] : 'name';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$show_results = isset($_GET['search']);

$students = [];
$total_students = 0;

if ($show_results) {
    // Build SQL query with filters
    $sql = "
        SELECT s.*, 
               c.name as class_name, 
               c.section as class_section,
               s.session,
               (SELECT COUNT(*) FROM attendance a WHERE a.student_id = s.id AND a.status = 'present') as total_present,
               (SELECT COUNT(*) FROM attendance a WHERE a.student_id = s.id) as total_attendance,
               (SELECT SUM(amount - paid_amount) FROM fees WHERE student_id = s.id AND status != 'paid') as total_due
        FROM students s
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE 1=1
    ";
    $params = [];
    
    // Apply filters
    if (!empty($class_id)) {
        $sql .= " AND s.class_id = ?";
        $params[] = $class_id;
    }
    
    if (!empty($status_filter)) {
        $sql .= " AND s.status = ?";
        $params[] = $status_filter;
    }
    
    if (!empty($gender_filter)) {
        $sql .= " AND s.gender = ?";
        $params[] = $gender_filter;
    }
    
    if (!empty($session_filter)) {
        $sql .= " AND s.session = ?";
        $params[] = $session_filter;
    }
    
    if (!empty($search_text)) {
        switch ($search_by) {
            case 'name':
                $sql .= " AND (s.first_name LIKE ? OR s.last_name LIKE ? OR CONCAT(s.first_name, ' ', s.last_name) LIKE ?)";
                $search_param = '%' . $search_text . '%';
                $params[] = $search_param;
                $params[] = $search_param;
                $params[] = $search_param;
                break;
            case 'student_id':
                $sql .= " AND s.student_id LIKE ?";
                $params[] = '%' . $search_text . '%';
                break;
            case 'roll':
                $sql .= " AND s.roll_number LIKE ?";
                $params[] = '%' . $search_text . '%';
                break;
            case 'phone':
                $sql .= " AND (s.phone LIKE ? OR s.guardian_phone LIKE ?)";
                $search_param = '%' . $search_text . '%';
                $params[] = $search_param;
                $params[] = $search_param;
                break;
            case 'email':
                $sql .= " AND (s.email LIKE ? OR s.guardian_email LIKE ?)";
                $search_param = '%' . $search_text . '%';
                $params[] = $search_param;
                $params[] = $search_param;
                break;
        }
    }
    
    if (!empty($date_from)) {
        $sql .= " AND s.admission_date >= ?";
        $params[] = $date_from;
    }
    
    if (!empty($date_to)) {
        $sql .= " AND s.admission_date <= ?";
        $params[] = $date_to;
    }
    
    $sql .= " ORDER BY c.name, s.roll_number";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
    $total_students = count($students);
}

// Get statistics for display
$stats = [];
if ($show_results && !empty($students)) {
    $stats = [
        'total' => count($students),
        'male' => count(array_filter($students, fn($s) => $s['gender'] == 'male')),
        'female' => count(array_filter($students, fn($s) => $s['gender'] == 'female')),
        'active' => count(array_filter($students, fn($s) => $s['status'] == 'active')),
        'inactive' => count(array_filter($students, fn($s) => $s['status'] == 'inactive')),
        'total_due' => array_sum(array_column($students, 'total_due'))
    ];
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষার্থী রিপোর্ট - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link 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">
    <style>
        .search-panel {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .report-header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .stats-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .report-table {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .report-table table {
            margin-bottom: 0;
        }
        
        .report-table th {
            background: #0d6efd;
            color: white;
            font-weight: 600;
            white-space: nowrap;
        }
        
        .report-table td {
            vertical-align: middle;
        }
        
        .badge-custom {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.85rem;
        }
        
        .student-photo {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 5px;
            border: 2px solid #ddd;
        }
        
        .no-photo {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f0f0f0;
            border-radius: 5px;
            border: 2px solid #ddd;
            color: #999;
            font-size: 24px;
        }
        
        .photo-toggle {
            margin-left: auto;
        }
        
        .hide-photos .student-photo,
        .hide-photos .no-photo {
            display: none !important;
        }
        
        /* Column hiding classes */
        .hide-column-serial .col-serial,
        .hide-column-photo .col-photo,
        .hide-column-id .col-student-id,
        .hide-column-name .col-name,
        .hide-column-class .col-class,
        .hide-column-roll .col-roll,
        .hide-column-session .col-session,
        .hide-column-gender .col-gender,
        .hide-column-phone .col-phone,
        .hide-column-guardian-phone .col-guardian-phone,
        .hide-column-admission-date .col-admission-date,
        .hide-column-status .col-status,
        .hide-column-attendance .col-attendance,
        .hide-column-due .col-due {
            display: none !important;
        }
        
        /* Print styles */
        @media print {
            .no-print {
                display: none !important;
            }
            
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
            
            html, body {
                height: auto;
                overflow: visible;
                margin: 0;
                padding: 0;
            }
            
            body {
                font-size: 11px;
                margin: 0;
                padding: 10px;
                background: white;
                color: black;
            }
            
            .container-fluid {
                width: 100% !important;
                max-width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            /* Optimize photo size for print */
            .student-photo,
            .no-photo {
                width: 30px;
                height: 30px;
                border-width: 1px;
            }
            
            .report-header {
                box-shadow: none;
                border: 1px solid #000;
                margin: 0 0 15px 0;
                padding: 10px;
                page-break-inside: avoid;
            }
            
            .report-table {
                box-shadow: none;
                overflow: visible !important;
                page-break-inside: auto;
            }
            
            .report-table th {
                background: #e9ecef !important;
                color: black !important;
                border: 1px solid #000 !important;
                padding: 8px !important;
                font-size: 10px;
            }
            
            .report-table td {
                border: 1px solid #000 !important;
                padding: 6px !important;
                font-size: 10px;
            }
            
            .stats-card {
                box-shadow: none;
                border: 1px solid #ddd;
                page-break-inside: avoid;
            }
            
            .row {
                display: flex;
                flex-wrap: wrap;
            }
            
            .col-md-2 {
                flex: 0 0 16.666667%;
                max-width: 16.666667%;
            }
            
            table {
                page-break-inside: auto;
                width: 100% !important;
                table-layout: auto;
                margin-bottom: 20px;
            }
            
            thead {
                display: table-header-group;
            }
            
            tfoot {
                display: table-footer-group;
            }
            
            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }
            
            /* Ensure all content is visible */
            .table-responsive {
                overflow: visible !important;
            }
            
            /* Print all columns */
            th, td {
                white-space: normal !important;
                word-wrap: break-word;
                word-break: break-word;
            }
            
            /* Prevent cutting off content */
            .mt-4 {
                margin-top: 0 !important;
            }
            
            /* Ensure statistics cards don't break */
            .row.mb-4 {
                page-break-inside: avoid;
            }
            
            /* Hide columns in print based on classes */
            .hide-column-serial.print-hide-serial .col-serial,
            .hide-column-photo.print-hide-photo .col-photo,
            .hide-column-id.print-hide-id .col-student-id,
            .hide-column-name.print-hide-name .col-name,
            .hide-column-class.print-hide-class .col-class,
            .hide-column-roll.print-hide-roll .col-roll,
            .hide-column-session.print-hide-session .col-session,
            .hide-column-gender.print-hide-gender .col-gender,
            .hide-column-phone.print-hide-phone .col-phone,
            .hide-column-guardian-phone.print-hide-guardian-phone .col-guardian-phone,
            .hide-column-admission-date.print-hide-admission-date .col-admission-date,
            .hide-column-status.print-hide-status .col-status,
            .hide-column-attendance.print-hide-attendance .col-attendance,
            .hide-column-due.print-hide-due .col-due {
                display: none !important;
            }
            
            /* Ensure due column is visible by default in print */
            .col-due {
                display: table-cell !important;
            }
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../admin/users.php">
                    <i class="fas fa-users"></i> ইউজার
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <!-- Search Panel -->
        <div class="search-panel no-print">
            <h4 class="mb-3"><i class="fas fa-search"></i> উন্নত অনুসন্ধান বিকল্প</h4>
            <form method="GET" action="" id="searchForm">
                <input type="hidden" name="search" value="1">
                
                <div class="row g-3">
                    <!-- Class Filter -->
                    <div class="col-md-3">
                        <label class="form-label">শ্রেণী</label>
                        <select name="class_id" class="form-select">
                            <option value="">সকল শ্রেণী</option>
                            <?php foreach ($classes as $class): ?>
                                <option value="<?php echo $class['id']; ?>" 
                                    <?php echo ($class_id == $class['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Status Filter -->
                    <div class="col-md-2">
                        <label class="form-label">স্ট্যাটাস</label>
                        <select name="status_filter" class="form-select">
                            <option value="">সকল স্ট্যাটাস</option>
                            <option value="active" <?php echo ($status_filter == 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                            <option value="inactive" <?php echo ($status_filter == 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                            <option value="graduated" <?php echo ($status_filter == 'graduated') ? 'selected' : ''; ?>>উত্তীর্ণ</option>
                            <option value="transferred" <?php echo ($status_filter == 'transferred') ? 'selected' : ''; ?>>বদলি</option>
                        </select>
                    </div>
                    
                    <!-- Gender Filter -->
                    <div class="col-md-2">
                        <label class="form-label">লিঙ্গ</label>
                        <select name="gender_filter" class="form-select">
                            <option value="">সকল লিঙ্গ</option>
                            <option value="male" <?php echo ($gender_filter == 'male') ? 'selected' : ''; ?>>ছেলে</option>
                            <option value="female" <?php echo ($gender_filter == 'female') ? 'selected' : ''; ?>>মেয়ে</option>
                            <option value="other" <?php echo ($gender_filter == 'other') ? 'selected' : ''; ?>>অন্যান্য</option>
                        </select>
                    </div>
                    
                    <!-- Session Filter -->
                    <div class="col-md-2">
                        <label class="form-label">সেশন</label>
                        <select name="session_filter" class="form-select">
                            <option value="">সকল সেশন</option>
                            <?php foreach ($sessions as $session): ?>
                                <option value="<?php echo htmlspecialchars($session['session']); ?>" 
                                    <?php echo ($session_filter == $session['session']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($session['session']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Search By -->
                    <div class="col-md-1.5">
                        <label class="form-label">অনুসন্ধান করুন</label>
                        <select name="search_by" class="form-select">
                            <option value="name" <?php echo ($search_by == 'name') ? 'selected' : ''; ?>>নাম</option>
                            <option value="student_id" <?php echo ($search_by == 'student_id') ? 'selected' : ''; ?>>শিক্ষার্থী আইডি</option>
                            <option value="roll" <?php echo ($search_by == 'roll') ? 'selected' : ''; ?>>রোল নম্বর</option>
                            <option value="phone" <?php echo ($search_by == 'phone') ? 'selected' : ''; ?>>ফোন</option>
                            <option value="email" <?php echo ($search_by == 'email') ? 'selected' : ''; ?>>ইমেইল</option>
                        </select>
                    </div>
                    
                    <!-- Search Text -->
                    <div class="col-md-2.5">
                        <label class="form-label">অনুসন্ধান টেক্সট</label>
                        <input type="text" name="search_text" class="form-control" 
                               value="<?php echo htmlspecialchars($search_text); ?>"
                               placeholder="অনুসন্ধান করুন...">
                    </div>
                </div>
                
                <div class="row g-3 mt-2">
                    <!-- Date From -->
                    <div class="col-md-3">
                        <label class="form-label">ভর্তির তারিখ (থেকে)</label>
                        <input type="date" name="date_from" class="form-control" 
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    
                    <!-- Date To -->
                    <div class="col-md-3">
                        <label class="form-label">ভর্তির তারিখ (পর্যন্ত)</label>
                        <input type="date" name="date_to" class="form-control" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                    
                    <!-- Buttons -->
                    <div class="col-md-6 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-search"></i> অনুসন্ধান করুন
                        </button>
                        <a href="students_report.php" class="btn btn-secondary me-2">
                            <i class="fas fa-redo"></i> রিসেট
                        </a>
                        <?php if ($show_results): ?>
                        <button type="button" class="btn btn-info me-2" onclick="togglePhotos()" id="photoToggleBtn">
                            <i class="fas fa-image"></i> ছবি লুকান
                        </button>
                        <button type="button" class="btn btn-warning me-2" onclick="toggleColumnSelector()" id="columnSelectorBtn">
                            <i class="fas fa-columns"></i> কলাম নির্বাচন
                        </button>
                        <button type="button" class="btn btn-success me-2" onclick="preparePrint()">
                            <i class="fas fa-print"></i> প্রিন্ট প্রস্তুতি
                        </button>
                        <button type="button" class="btn btn-success" onclick="window.print()">
                            <i class="fas fa-print"></i> প্রিন্ট করুন
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Column Selector Panel -->
                <?php if ($show_results): ?>
                <div class="row g-3 mt-2 no-print" id="columnSelectorPanel" style="display: none; background: #e9ecef; padding: 15px; border-radius: 5px;">
                    <div class="col-12">
                        <h5><i class="fas fa-columns"></i> প্রিন্টের জন্য কলাম নির্বাচন করুন</h5>
                        <p>নিচের চেকবক্সগুলি টিক করে প্রিন্টের সময় কোন কোন কলাম লুকানো হবে তা নির্বাচন করুন:</p>
                    </div>
                    <div class="col-md-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideSerial" onchange="toggleColumn('serial', this.checked)">
                            <label class="form-check-label" for="hideSerial">ক্রমিক লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hidePhoto" onchange="toggleColumn('photo', this.checked)">
                            <label class="form-check-label" for="hidePhoto">ছবি লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideStudentId" onchange="toggleColumn('id', this.checked)">
                            <label class="form-check-label" for="hideStudentId">শিক্ষার্থী আইডি লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideName" onchange="toggleColumn('name', this.checked)">
                            <label class="form-check-label" for="hideName">নাম লুকান</label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideClass" onchange="toggleColumn('class', this.checked)">
                            <label class="form-check-label" for="hideClass">শ্রেণী লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideRoll" onchange="toggleColumn('roll', this.checked)">
                            <label class="form-check-label" for="hideRoll">রোল লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideSession" onchange="toggleColumn('session', this.checked)">
                            <label class="form-check-label" for="hideSession">সেশন লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideGender" onchange="toggleColumn('gender', this.checked)">
                            <label class="form-check-label" for="hideGender">লিঙ্গ লুকান</label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hidePhone" onchange="toggleColumn('phone', this.checked)">
                            <label class="form-check-label" for="hidePhone">ফোন লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideGuardianPhone" onchange="toggleColumn('guardian-phone', this.checked)">
                            <label class="form-check-label" for="hideGuardianPhone">অভিভাবকের ফোন লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideAdmissionDate" onchange="toggleColumn('admission-date', this.checked)">
                            <label class="form-check-label" for="hideAdmissionDate">ভর্তির তারিখ লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideStatus" onchange="toggleColumn('status', this.checked)">
                            <label class="form-check-label" for="hideStatus">স্ট্যাটাস লুকান</label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideAttendance" onchange="toggleColumn('attendance', this.checked)" checked>
                            <label class="form-check-label" for="hideAttendance">উপস্থিতি লুকান</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="hideDue" onchange="toggleColumn('due', this.checked)">
                            <label class="form-check-label" for="hideDue">বকেয়া লুকান</label>
                        </div>
                        <div class="mt-3">
                            <button type="button" class="btn btn-sm btn-secondary" onclick="resetColumnSelection()">রিসেট</button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </form>
        </div>

        <?php if ($show_results): ?>
        
        <!-- Report Header -->
        <div class="report-header">
            <h2>শিক্ষার্থী তথ্য রিপোর্ট</h2>
            <p class="mb-0">প্রতিবেদনের তারিখ: <?php echo date('d/m/Y'); ?></p>
            <?php if (!empty($class_id)): 
                $selected_class = array_filter($classes, fn($c) => $c['id'] == $class_id);
                $selected_class = reset($selected_class);
            ?>
            <p class="mb-0"><strong>শ্রেণী:</strong> <?php echo htmlspecialchars($selected_class['name'] . ' - ' . $selected_class['section']); ?></p>
            <?php endif; ?>
            <?php if (!empty($session_filter)): ?>
            <p class="mb-0"><strong>সেশন:</strong> <?php echo htmlspecialchars($session_filter); ?></p>
            <?php endif; ?>
        </div>

        <!-- Statistics Cards -->
        <?php if (!empty($stats)): ?>
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-primary"><?php echo $stats['total']; ?></h4>
                    <p class="mb-0">মোট শিক্ষার্থী</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-info"><?php echo $stats['male']; ?></h4>
                    <p class="mb-0">ছেলে</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-danger"><?php echo $stats['female']; ?></h4>
                    <p class="mb-0">মেয়ে</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-success"><?php echo $stats['active']; ?></h4>
                    <p class="mb-0">সক্রিয়</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-warning"><?php echo $stats['inactive']; ?></h4>
                    <p class="mb-0">নিষ্ক্রিয়</p>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stats-card text-center">
                    <h4 class="text-danger">৳<?php echo number_format($stats['total_due'], 2); ?></h4>
                    <p class="mb-0">মোট বকেয়া</p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Results Table -->
        <?php if (!empty($students)): ?>
        <div class="report-table" id="reportTable">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th style="width: 3%;" class="col-serial">ক্রমিক</th>
                            <th style="width: 5%;" class="col-photo">ছবি</th>
                            <th style="width: 8%;" class="col-student-id">শিক্ষার্থী আইডি</th>
                            <th style="width: 12%;" class="col-name">নাম</th>
                            <th style="width: 10%;" class="col-class">শ্রেণী</th>
                            <th style="width: 5%;" class="col-roll">রোল</th>
                            <th style="width: 7%;" class="col-session">সেশন</th>
                            <th style="width: 5%;" class="col-gender">লিঙ্গ</th>
                            <th style="width: 8%;" class="col-phone">ফোন</th>
                            <th style="width: 10%;" class="col-guardian-phone">অভিভাবকের ফোন</th>
                            <th style="width: 8%;" class="col-admission-date">ভর্তির তারিখ</th>
                            <th style="width: 7%;" class="col-status">স্ট্যাটাস</th>
                            <th style="width: 6%;" class="col-attendance no-print">উপস্থিতি</th>
                            <th style="width: 6%;" class="col-due">বকেয়া</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($students as $index => $student): ?>
                        <tr>
                            <td class="col-serial"><?php echo $index + 1; ?></td>
                            <td class="col-photo">
                                <?php if (!empty($student['photo']) && file_exists(__DIR__ . '/' . $student['photo'])): ?>
                                    <img src="<?php echo htmlspecialchars($student['photo']); ?>" 
                                         alt="<?php echo htmlspecialchars($student['first_name']); ?>" 
                                         class="student-photo">
                                <?php else: ?>
                                    <div class="no-photo">
                                        <i class="fas fa-user"></i>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="col-student-id"><?php echo htmlspecialchars($student['student_id']); ?></td>
                            <td class="col-name">
                                <strong><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></strong>
                            </td>
                            <td class="col-class"><?php echo htmlspecialchars($student['class_name'] . ' - ' . $student['class_section']); ?></td>
                            <td class="col-roll"><?php echo htmlspecialchars($student['roll_number']); ?></td>
                            <td class="col-session"><?php echo htmlspecialchars($student['session'] ?? 'N/A'); ?></td>
                            <td class="col-gender">
                                <?php 
                                $gender_text = ['male' => 'ছেলে', 'female' => 'মেয়ে', 'other' => 'অন্যান্য'];
                                echo $gender_text[$student['gender']] ?? '';
                                ?>
                            </td>
                            <td class="col-phone"><?php echo htmlspecialchars($student['phone'] ?? 'N/A'); ?></td>
                            <td class="col-guardian-phone"><?php echo htmlspecialchars($student['guardian_phone'] ?? 'N/A'); ?></td>
                            <td class="col-admission-date"><?php echo $student['admission_date'] ? date('d/m/Y', strtotime($student['admission_date'])) : 'N/A'; ?></td>
                            <td class="col-status">
                                <?php
                                $status_badges = [
                                    'active' => '<span class="badge bg-success">সক্রিয়</span>',
                                    'inactive' => '<span class="badge bg-warning">নিষ্ক্রিয়</span>',
                                    'graduated' => '<span class="badge bg-info">উত্তীর্ণ</span>',
                                    'transferred' => '<span class="badge bg-secondary">বদলি</span>'
                                ];
                                echo $status_badges[$student['status']] ?? '';
                                ?>
                            </td>
                            <td class="col-attendance no-print">
                                <?php 
                                if ($student['total_attendance'] > 0) {
                                    $percentage = round(($student['total_present'] / $student['total_attendance']) * 100);
                                    echo $percentage . '%';
                                } else {
                                    echo 'N/A';
                                }
                                ?>
                            </td>
                            <td class="col-due">
                                <?php 
                                $due = $student['total_due'] ?? 0;
                                if ($due > 0) {
                                    echo '<span class="text-danger">৳' . number_format($due, 2) . '</span>';
                                } else {
                                    echo '<span class="text-success">৳0.00</span>';
                                }
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="mt-3 text-center no-print">
            <p><strong>মোট শিক্ষার্থী সংখ্যা: <?php echo $total_students; ?></strong></p>
        </div>
        
        <?php elseif ($show_results): ?>
        <div class="alert alert-info no-print">
            <i class="fas fa-info-circle"></i> কোনো শিক্ষার্থী খুঁজে পাওয়া যায়নি। অনুগ্রহ করে অনুসন্ধান শর্ত পরিবর্তন করুন।
        </div>
        <?php endif; ?>
        
        <?php else: ?>
        <div class="alert alert-info text-center">
            <i class="fas fa-info-circle"></i> শিক্ষার্থী রিপোর্ট দেখতে উপরের ফিল্টার ব্যবহার করে অনুসন্ধান করুন।
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function togglePhotos() {
            const reportTable = document.querySelector('.report-table');
            const toggleBtn = document.getElementById('photoToggleBtn');
            
            if (reportTable.classList.contains('hide-photos')) {
                reportTable.classList.remove('hide-photos');
                toggleBtn.innerHTML = '<i class="fas fa-image"></i> ছবি লুকান';
            } else {
                reportTable.classList.add('hide-photos');
                toggleBtn.innerHTML = '<i class="fas fa-image"></i> ছবি দেখান';
            }
        }
        
        function preparePrint() {
            // Show all photos if they were hidden
            const reportTable = document.querySelector('.report-table');
            reportTable.classList.remove('hide-photos');
            
            // Update photo toggle button text
            const toggleBtn = document.getElementById('photoToggleBtn');
            toggleBtn.innerHTML = '<i class="fas fa-image"></i> ছবি লুকান';
            
            // Apply print-specific column hiding
            document.body.classList.add('print-prepared');
            
            // Show alert to user
            alert('পেজটি এখন প্রিন্টের জন্য প্রস্তুত। প্রিন্ট করতে "প্রিন্ট করুন" বাটনে ক্লিক করুন।');
        }
        
        function toggleColumnSelector() {
            const panel = document.getElementById('columnSelectorPanel');
            const btn = document.getElementById('columnSelectorBtn');
            
            if (panel.style.display === 'none') {
                panel.style.display = 'flex';
                btn.innerHTML = '<i class="fas fa-columns"></i> কলাম নির্বাচন বন্ধ করুন';
            } else {
                panel.style.display = 'none';
                btn.innerHTML = '<i class="fas fa-columns"></i> কলাম নির্বাচন';
            }
        }
        
        function toggleColumn(columnName, hide) {
            const table = document.getElementById('reportTable');
            
            if (hide) {
                table.classList.add('hide-column-' + columnName);
                // Also add print-specific class
                document.body.classList.add('print-hide-' + columnName);
            } else {
                table.classList.remove('hide-column-' + columnName);
                // Also remove print-specific class
                document.body.classList.remove('print-hide-' + columnName);
            }
        }
        
        function resetColumnSelection() {
            // Reset all checkboxes
            document.getElementById('hideSerial').checked = false;
            document.getElementById('hidePhoto').checked = false;
            document.getElementById('hideStudentId').checked = false;
            document.getElementById('hideName').checked = false;
            document.getElementById('hideClass').checked = false;
            document.getElementById('hideRoll').checked = false;
            document.getElementById('hideSession').checked = false;
            document.getElementById('hideGender').checked = false;
            document.getElementById('hidePhone').checked = false;
            document.getElementById('hideGuardianPhone').checked = false;
            document.getElementById('hideAdmissionDate').checked = false;
            document.getElementById('hideStatus').checked = false;
            document.getElementById('hideAttendance').checked = true; // Keep attendance hidden by default
            document.getElementById('hideDue').checked = false; // Due column visible by default
            
            // Remove all column hiding classes
            const table = document.getElementById('reportTable');
            table.classList.remove('hide-column-serial', 'hide-column-photo', 'hide-column-id', 
                                 'hide-column-name', 'hide-column-class', 'hide-column-roll',
                                 'hide-column-session', 'hide-column-gender', 'hide-column-phone',
                                 'hide-column-guardian-phone', 'hide-column-admission-date', 
                                 'hide-column-status', 'hide-column-attendance', 'hide-column-due');
            
            // Remove all print-specific classes
            document.body.classList.remove('print-hide-serial', 'print-hide-photo', 'print-hide-id', 
                                          'print-hide-name', 'print-hide-class', 'print-hide-roll',
                                          'print-hide-session', 'print-hide-gender', 'print-hide-phone',
                                          'print-hide-guardian-phone', 'print-hide-admission-date', 
                                          'print-hide-status', 'print-hide-attendance', 'print-hide-due');
        }
        
        // Handle before print event to optimize layout
        window.addEventListener('beforeprint', function() {
            // Make sure all content is visible
            document.body.style.zoom = "100%";
        });
        
        // Handle after print event to restore layout
        window.addEventListener('afterprint', function() {
            // Restore any changes made for printing
        });
    </script>
</body>
</html>
