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

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

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$offset = ($page - 1) * $limit;

// Update overdue status for fees that are past due date
try {
    $update_overdue = $pdo->prepare("
        UPDATE fees 
        SET status = 'overdue' 
        WHERE status IN ('pending', 'partial') 
        AND due_date < CURDATE() 
        AND amount > paid_amount
    ");
    $update_overdue->execute();
} catch (Exception $e) {
    // Silently handle error to not break the page
}

// Get filter parameters
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? '';
$group_name = $_GET['group_name'] ?? '';
$fee_type = $_GET['fee_type'] ?? '';
$month = $_GET['month'] ?? '';
$academic_year = $_GET['academic_year'] ?? '';
$status_filter = $_GET['status_filter'] ?? '';

// Get dropdown data
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
$groups = $pdo->query("SELECT group_name FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();
$fee_types = $pdo->query("SELECT DISTINCT fee_type FROM fees ORDER BY fee_type")->fetchAll();
$academic_years = $pdo->query("SELECT DISTINCT academic_year FROM fees WHERE academic_year IS NOT NULL ORDER BY academic_year DESC")->fetchAll();

// Build query conditions
$where_conditions = ["s.status = 'active'"];
$params = [];
$param_counter = 1;

if (!empty($class_id)) {
    $where_conditions[] = "s.class_id = :param{$param_counter}";
    $params[":param{$param_counter}"] = $class_id;
    $param_counter++;
}

if (!empty($session)) {
    $where_conditions[] = "s.session = :param{$param_counter}";
    $params[":param{$param_counter}"] = $session;
    $param_counter++;
}

if ($group_name !== '') {
    $where_conditions[] = "COALESCE(s.group_name, '') = :param{$param_counter}";
    $params[":param{$param_counter}"] = $group_name;
    $param_counter++;
}

// Fee-specific filters
$fee_conditions = [];
if (!empty($fee_type)) {
    $fee_conditions[] = "f.fee_type = :param{$param_counter}";
    $params[":param{$param_counter}"] = $fee_type;
    $param_counter++;
}

if (!empty($month)) {
    $fee_conditions[] = "f.month = :param{$param_counter}";
    $params[":param{$param_counter}"] = $month;
    $param_counter++;
}

if (!empty($academic_year)) {
    $fee_conditions[] = "f.academic_year = :param{$param_counter}";
    $params[":param{$param_counter}"] = $academic_year;
    $param_counter++;
}

if (!empty($status_filter)) {
    if ($status_filter === 'overdue') {
        // For overdue, check both status and due date
        $fee_conditions[] = "(f.status = :param{$param_counter} OR (f.status IN ('pending', 'partial') AND f.due_date < CURDATE()))";
        $params[":param{$param_counter}"] = 'overdue';
        $param_counter++;
    } else {
        $fee_conditions[] = "f.status = :param{$param_counter}";
        $params[":param{$param_counter}"] = $status_filter;
        $param_counter++;
    }
}

$where_clause = implode(' AND ', $where_conditions);
$fee_where = !empty($fee_conditions) ? 'AND ' . implode(' AND ', $fee_conditions) : '';

// Count total records for pagination
if (!empty($status_filter) || !empty($fee_type) || !empty($month) || !empty($academic_year)) {
    // If we have fee-specific filters, use INNER JOIN to only show students with fees
    $count_sql = "
        SELECT COUNT(DISTINCT s.id) as total_records
        FROM students s
        JOIN classes c ON s.class_id = c.id
        INNER JOIN fees f ON s.id = f.student_id
        WHERE $where_clause $fee_where
    ";
} else {
    // If no fee-specific filters, show all students with their fees (if any)
    $count_sql = "
        SELECT COUNT(DISTINCT s.id) as total_records
        FROM students s
        JOIN classes c ON s.class_id = c.id
        LEFT JOIN fees f ON s.id = f.student_id
        WHERE $where_clause
    ";
}

$count_stmt = $pdo->prepare($count_sql);
// Bind parameters for count query
foreach ($params as $key => $value) {
    $count_stmt->bindValue($key, $value);
}
$count_stmt->execute();
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// Main query for detailed report with pagination
if (!empty($status_filter) || !empty($fee_type) || !empty($month) || !empty($academic_year)) {
    // If we have fee-specific filters, use INNER JOIN to only show students with fees
    $sql = "
        SELECT 
            s.id as student_id,
            s.student_id as student_code,
            s.first_name,
            s.last_name,
            s.roll_number,
            s.session,
            s.group_name,
            c.name as class_name,
            c.section as class_section,
            f.id as fee_id,
            f.fee_type,
            f.amount,
            f.paid_amount,
            (f.amount - f.paid_amount) as due_amount,
            f.due_date,
            f.status,
            f.academic_year,
            f.month,
            f.created_at,
            f.paid_date
        FROM students s
        JOIN classes c ON s.class_id = c.id
        INNER JOIN fees f ON s.id = f.student_id
        WHERE $where_clause $fee_where
        ORDER BY s.roll_number, f.due_date ASC
        LIMIT :limit OFFSET :offset
    ";
} else {
    // If no fee-specific filters, show all students with their fees (if any)
    $sql = "
        SELECT 
            s.id as student_id,
            s.student_id as student_code,
            s.first_name,
            s.last_name,
            s.roll_number,
            s.session,
            s.group_name,
            c.name as class_name,
            c.section as class_section,
            f.id as fee_id,
            f.fee_type,
            f.amount,
            f.paid_amount,
            (f.amount - f.paid_amount) as due_amount,
            f.due_date,
            f.status,
            f.academic_year,
            f.month,
            f.created_at,
            f.paid_date
        FROM students s
        JOIN classes c ON s.class_id = c.id
        LEFT JOIN fees f ON s.id = f.student_id
        WHERE $where_clause
        ORDER BY s.roll_number, f.due_date ASC
        LIMIT :limit OFFSET :offset
    ";
}

// Debug information (remove in production)
$debug_mode = isset($_GET['debug']) && $_GET['debug'] == '1';
if ($debug_mode) {
    echo "<div class='alert alert-info'>";
    echo "<h5>Debug Information:</h5>";
    echo "<p><strong>SQL:</strong> " . htmlspecialchars($sql) . "</p>";
    echo "<p><strong>Parameters:</strong> " . htmlspecialchars(json_encode($params)) . "</p>";
    echo "<p><strong>Status Filter:</strong> " . htmlspecialchars($status_filter) . "</p>";
    
    // Check if there are any overdue fees at all
    $test_sql = "SELECT COUNT(*) as overdue_count FROM fees WHERE status = 'overdue' OR (status IN ('pending', 'partial') AND due_date < CURDATE())";
    $test_result = $pdo->query($test_sql)->fetch();
    echo "<p><strong>Total Overdue Fees in DB:</strong> " . $test_result['overdue_count'] . "</p>";
    
    // Check fees for specific class
    if (!empty($class_id)) {
        $class_test_sql = "SELECT COUNT(*) as class_overdue FROM fees f JOIN students s ON f.student_id = s.id WHERE s.class_id = :class_id AND (f.status = 'overdue' OR (f.status IN ('pending', 'partial') AND f.due_date < CURDATE()))";
        $class_test_stmt = $pdo->prepare($class_test_sql);
        $class_test_stmt->bindValue(':class_id', $class_id);
        $class_test_stmt->execute();
        $class_test_result = $class_test_stmt->fetch();
        echo "<p><strong>Overdue Fees for Class ID $class_id:</strong> " . $class_test_result['class_overdue'] . "</p>";
    }
    echo "</div>";
}

$stmt = $pdo->prepare($sql);
// Bind parameters using named parameters for consistency
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$detailed_data = $stmt->fetchAll();

// Summary statistics - use same logic as main query (without pagination)
if (!empty($status_filter) || !empty($fee_type) || !empty($month) || !empty($academic_year)) {
    $summary_sql = "
        SELECT 
            COUNT(DISTINCT s.id) as total_students,
            COUNT(f.id) as total_fees,
            SUM(f.amount) as total_amount,
            SUM(f.paid_amount) as total_paid,
            SUM(f.amount - f.paid_amount) as total_due,
            SUM(CASE WHEN f.status = 'paid' THEN 1 ELSE 0 END) as paid_count,
            SUM(CASE WHEN f.status = 'pending' THEN 1 ELSE 0 END) as pending_count,
            SUM(CASE WHEN f.status = 'partial' THEN 1 ELSE 0 END) as partial_count,
            SUM(CASE WHEN f.status = 'overdue' OR (f.status IN ('pending', 'partial') AND f.due_date < CURDATE()) THEN 1 ELSE 0 END) as overdue_count
        FROM students s
        JOIN classes c ON s.class_id = c.id
        INNER JOIN fees f ON s.id = f.student_id
        WHERE $where_clause $fee_where
    ";
} else {
    $summary_sql = "
        SELECT 
            COUNT(DISTINCT s.id) as total_students,
            COUNT(f.id) as total_fees,
            SUM(f.amount) as total_amount,
            SUM(f.paid_amount) as total_paid,
            SUM(f.amount - f.paid_amount) as total_due,
            SUM(CASE WHEN f.status = 'paid' THEN 1 ELSE 0 END) as paid_count,
            SUM(CASE WHEN f.status = 'pending' THEN 1 ELSE 0 END) as pending_count,
            SUM(CASE WHEN f.status = 'partial' THEN 1 ELSE 0 END) as partial_count,
            SUM(CASE WHEN f.status = 'overdue' OR (f.status IN ('pending', 'partial') AND f.due_date < CURDATE()) THEN 1 ELSE 0 END) as overdue_count
        FROM students s
        JOIN classes c ON s.class_id = c.id
        LEFT JOIN fees f ON s.id = f.student_id
        WHERE $where_clause
    ";
}

$stmt = $pdo->prepare($summary_sql);
// Bind parameters for summary query
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$summary = $stmt->fetch();

// Group data by student for better display
$students_data = [];
foreach ($detailed_data as $row) {
    $student_id = $row['student_id'];
    if (!isset($students_data[$student_id])) {
        $students_data[$student_id] = [
            'info' => [
                'student_code' => $row['student_code'],
                'name' => $row['first_name'] . ' ' . $row['last_name'],
                'roll_number' => $row['roll_number'],
                'class' => $row['class_name'] . ' - ' . $row['class_section'],
                'session' => $row['session'],
                'group_name' => $row['group_name']
            ],
            'fees' => [],
            'totals' => ['amount' => 0, 'paid' => 0, 'due' => 0]
        ];
    }
    
    if ($row['fee_id']) {
        $students_data[$student_id]['fees'][] = $row;
        $students_data[$student_id]['totals']['amount'] += $row['amount'];
        $students_data[$student_id]['totals']['paid'] += $row['paid_amount'];
        $students_data[$student_id]['totals']['due'] += $row['due_amount'];
    }
}
?>

<!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="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 1.5rem;
        }
        .stats-card {
            border-radius: 15px;
            transition: transform 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .student-section {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        .student-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 1rem;
            border-bottom: 1px solid #dee2e6;
        }
        .fee-row.paid {
            background-color: #d4edda;
        }
        .fee-row.pending {
            background-color: #fff3cd;
        }
        .fee-row.partial {
            background-color: #cce7ff;
        }
        .fee-row.overdue {
            background-color: #f8d7da;
        }
        
        /* Print Styles */
        @media print {
            body {
                background: white !important;
                font-size: 12px;
                line-height: 1.4;
                color: black !important;
            }
            
            .no-print, .screen-only {
                display: none !important;
            }
            
            .print-only, .print-header, .print-footer {
                display: block !important;
            }
            
            .container-fluid {
                max-width: none !important;
                padding: 0 !important;
            }
            
            .card {
                border: none !important;
                box-shadow: none !important;
                margin: 0 !important;
                page-break-inside: avoid;
            }
            
            .card-header {
                background: white !important;
                color: black !important;
                border: 2px solid black !important;
                border-bottom: 1px solid black !important;
                text-align: center;
                padding: 20px !important;
            }
            
            .card-body {
                padding: 0 !important;
            }
            
            /* Print Header */
            .print-header {
                text-align: center;
                margin-bottom: 30px;
                border-bottom: 2px solid black;
                padding-bottom: 20px;
            }
            
            .print-header h1 {
                font-size: 24px;
                font-weight: bold;
                margin-bottom: 5px;
            }
            
            .print-header h2 {
                font-size: 18px;
                margin-bottom: 10px;
            }
            
            .print-header .report-info {
                font-size: 14px;
                margin-top: 10px;
            }
            
            /* Print Table */
            .print-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
                font-size: 11px;
            }
            
            .print-table th,
            .print-table td {
                border: 1px solid black;
                padding: 8px 4px;
                text-align: left;
                vertical-align: top;
            }
            
            .print-table th {
                background-color: #f0f0f0 !important;
                font-weight: bold;
                text-align: center;
            }
            
            .print-table .student-name {
                font-weight: bold;
                background-color: #f8f9fa !important;
            }
            
            .print-table .amount {
                text-align: right;
            }
            
            .print-table .status-paid {
                background-color: #d4edda !important;
            }
            
            .print-table .status-pending {
                background-color: #fff3cd !important;
            }
            
            .print-table .status-partial {
                background-color: #cce7ff !important;
            }
            
            .print-table .status-overdue {
                background-color: #f8d7da !important;
            }
            
            /* Summary Section */
            .print-summary {
                margin-top: 30px;
                border-top: 2px solid black;
                padding-top: 15px;
            }
            
            .print-summary table {
                width: 100%;
                border-collapse: collapse;
            }
            
            .print-summary th,
            .print-summary td {
                border: 1px solid black;
                padding: 8px;
                text-align: center;
            }
            
            .print-summary th {
                background-color: #f0f0f0 !important;
                font-weight: bold;
            }
            
            /* Page break */
            .page-break {
                page-break-before: always;
            }
            
            /* Footer */
            .print-footer {
                position: fixed;
                bottom: 0;
                width: 100%;
                text-align: center;
                font-size: 10px;
                border-top: 1px solid black;
                padding-top: 10px;
            }
        }
    </style>
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        .filter-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        .filter-section .form-label {
            color: white;
            font-weight: 600;
        }
        .stats-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .student-section {
            border: 1px solid #dee2e6;
            border-radius: 10px;
            margin-bottom: 1rem;
            background: white;
        }
        .student-header {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px 10px 0 0;
        }
        .fee-row.overdue {
            background-color: #fff5f5;
            border-left: 4px solid #dc3545;
        }
        .fee-row.paid {
            background-color: #f0fff4;
            border-left: 4px solid #28a745;
        }
        .fee-row.partial {
            background-color: #fff8e1;
            border-left: 4px solid #ffc107;
        }
        @media print {
            .no-print { display: none !important; }
            .student-section { page-break-inside: avoid; }
            body { background: white !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="manage.php">
                    <i class="fas fa-cog"></i> ফি ম্যানেজ
                </a>
                <a class="nav-link" href="student_fees.php">
                    <i class="fas fa-money-bill-wave"></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">
        <!-- Filter Section -->
        <div class="filter-section no-print">
            <h4 class="text-white mb-3"><i class="fas fa-filter"></i> রিপোর্ট ফিল্টার</h4>
            <form method="GET" action="">
                <div class="row g-3">
                    <div class="col-md-2">
                        <label for="session" class="form-label">সেশন</label>
                        <select class="form-select" name="session" id="session">
                            <option value="">সব সেশন</option>
                            <?php foreach ($sessions as $s): ?>
                                <option value="<?php echo htmlspecialchars($s['session_name']); ?>" 
                                        <?php echo $session == $s['session_name'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($s['session_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="class_id" class="form-label">ক্লাস</label>
                        <select class="form-select" name="class_id" id="class_id">
                            <option value="">সব ক্লাস</option>
                            <?php foreach ($classes as $c): ?>
                                <option value="<?php echo $c['id']; ?>" 
                                        <?php echo $class_id == $c['id'] ? 'selected' : ''; ?>>
                                    <?php echo $c['name'] . ' - ' . $c['section']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="group_name" class="form-label">গ্রুপ</label>
                        <select class="form-select" name="group_name" id="group_name">
                            <option value="">সব গ্রুপ</option>
                            <option value="" <?php echo $group_name === '' ? 'selected' : ''; ?>>কোন গ্রুপ নেই</option>
                            <?php foreach ($groups as $g): ?>
                                <option value="<?php echo htmlspecialchars($g['group_name']); ?>" 
                                        <?php echo $group_name == $g['group_name'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($g['group_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="fee_type" class="form-label">ফি এর ধরন</label>
                        <select class="form-select" name="fee_type" id="fee_type">
                            <option value="">সব ধরন</option>
                            <?php foreach ($fee_types as $ft): ?>
                                <option value="<?php echo htmlspecialchars($ft['fee_type']); ?>" 
                                        <?php echo $fee_type == $ft['fee_type'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($ft['fee_type']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="academic_year" class="form-label">শিক্ষাবর্ষ</label>
                        <select class="form-select" name="academic_year" id="academic_year">
                            <option value="">সব বছর</option>
                            <?php foreach ($academic_years as $ay): ?>
                                <option value="<?php echo htmlspecialchars($ay['academic_year']); ?>" 
                                        <?php echo $academic_year == $ay['academic_year'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($ay['academic_year']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="status_filter" class="form-label">স্ট্যাটাস</label>
                        <select class="form-select" name="status_filter" id="status_filter">
                            <option value="">সব স্ট্যাটাস</option>
                            <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>অপেক্ষমান</option>
                            <option value="partial" <?php echo $status_filter == 'partial' ? 'selected' : ''; ?>>আংশিক</option>
                            <option value="paid" <?php echo $status_filter == 'paid' ? 'selected' : ''; ?>>পরিশোধিত</option>
                            <option value="overdue" <?php echo $status_filter == 'overdue' ? 'selected' : ''; ?>>বকেয়া</option>
                        </select>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-md-12">
                        <button type="submit" class="btn btn-light me-2">
                            <i class="fas fa-search"></i> রিপোর্ট দেখুন
                        </button>
                        <button type="button" class="btn btn-outline-light me-2" onclick="printReport()">
                            <i class="fas fa-print"></i> প্রিন্ট করুন
                        </button>
                        <a href="?" class="btn btn-outline-light">
                            <i class="fas fa-refresh"></i> রিসেট
                        </a>
                    </div>
                </div>
            </form>
        </div>

        <!-- Summary Statistics -->
        <div class="row mb-4 no-print">
            <div class="col-md-2">
                <div class="card stats-card bg-primary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $summary['total_students'] ?: 0; ?></h4>
                        <p class="mb-0">মোট শিক্ষার্থী</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stats-card bg-info text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $summary['total_fees'] ?: 0; ?></h4>
                        <p class="mb-0">মোট ফি এন্ট্রি</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stats-card bg-purple text-white" style="background-color: #6f42c1 !important;">
                    <div class="card-body text-center">
                        <h4>৳<?php echo number_format($summary['total_amount'] ?: 0, 2); ?></h4>
                        <p class="mb-0">মোট পরিমাণ</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stats-card bg-success text-white">
                    <div class="card-body text-center">
                        <h4>৳<?php echo number_format($summary['total_paid'] ?: 0, 2); ?></h4>
                        <p class="mb-0">মোট পরিশোধিত</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stats-card bg-danger text-white">
                    <div class="card-body text-center">
                        <h4>৳<?php echo number_format($summary['total_due'] ?: 0, 2); ?></h4>
                        <p class="mb-0">মোট বকেয়া</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card stats-card bg-warning text-white">
                    <div class="card-body text-center">
                        <h4><?php echo round((($summary['total_paid'] ?: 0) / ($summary['total_amount'] ?: 1)) * 100, 1); ?>%</h4>
                        <p class="mb-0">সংগ্রহের হার</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Print Header (Only visible when printing) -->
        <div class="print-header" style="display: none;">
            <h1>শিক্ষা প্রতিষ্ঠানের নাম</h1>
            <h2>ফি রিপোর্ট</h2>
            <div class="report-info">
                <p>
                    <?php if (!empty($session)): ?>
                        <strong>সেশন:</strong> <?php echo htmlspecialchars($session); ?> |
                    <?php endif; ?>
                    <?php if (!empty($class_id)): ?>
                        <?php 
                        $selected_class = array_filter($classes, function($c) use ($class_id) {
                            return $c['id'] == $class_id;
                        });
                        if (!empty($selected_class)) {
                            $class_info = reset($selected_class);
                            echo "<strong>ক্লাস:</strong> " . htmlspecialchars($class_info['name'] . ' - ' . $class_info['section']) . " | ";
                        }
                        ?>
                    <?php endif; ?>
                    <?php if (!empty($group_name)): ?>
                        <strong>গ্রুপ:</strong> <?php echo htmlspecialchars($group_name); ?> |
                    <?php endif; ?>
                    <?php if (!empty($status_filter)): ?>
                        <strong>স্ট্যাটাস:</strong> 
                        <?php 
                        $status_names = [
                            'pending' => 'অপেক্ষমান',
                            'partial' => 'আংশিক',
                            'paid' => 'পরিশোধিত',
                            'overdue' => 'বকেয়া'
                        ];
                        echo $status_names[$status_filter] ?? $status_filter;
                        ?> |
                    <?php endif; ?>
                    <strong>তারিখ:</strong> <?php echo date('d/m/Y'); ?>
                </p>
            </div>
        </div>

        <!-- Detailed Report -->
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-chart-bar"></i> বিস্তারিত ফি রিপোর্ট</h5>
            </div>
            <div class="card-body">
                <?php if (empty($students_data)): ?>
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-search fa-3x mb-3"></i>
                        <p>কোন ডাটা পাওয়া যায়নি।</p>
                        <?php if ($status_filter == 'overdue'): ?>
                            <div class="alert alert-info mt-3">
                                <h6><i class="fas fa-info-circle"></i> বকেয়া ফি খুঁজে পাওয়া যায়নি</h6>
                                <p class="mb-2">সম্ভাব্য কারণসমূহ:</p>
                                <ul class="text-start">
                                    <li>নির্বাচিত ক্লাসে কোন বকেয়া ফি নেই</li>
                                    <li>সব ফি পরিশোধ করা হয়ে গেছে</li>
                                    <li>এখনো কোন ফি নির্ধারণ করা হয়নি</li>
                                </ul>
                                <a href="?debug=1&<?php echo http_build_query($_GET); ?>" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-bug"></i> ডিবাগ তথ্য দেখুন
                                </a>
                            </div>
                        <?php else: ?>
                            <p>ফিল্টার পরিবর্তন করে আবার চেষ্টা করুন।</p>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <!-- Print Version Table (Only visible when printing) -->
                    <div class="print-only" style="display: none;">
                        <table class="print-table">
                            <thead>
                                <tr>
                                    <th style="width: 5%;">ক্রমিক</th>
                                    <th style="width: 20%;">শিক্ষার্থীর নাম</th>
                                    <th style="width: 8%;">রোল</th>
                                    <th style="width: 12%;">ক্লাস</th>
                                    <th style="width: 15%;">ফি এর ধরন</th>
                                    <th style="width: 8%;">মাস/বছর</th>
                                    <th style="width: 8%;">মোট (৳)</th>
                                    <th style="width: 8%;">পরিশোধিত (৳)</th>
                                    <th style="width: 8%;">বকেয়া (৳)</th>
                                    <th style="width: 8%;">স্ট্যাটাস</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $serial = 1;
                                foreach ($students_data as $student_id => $data): 
                                    $student_fees = $data['fees'];
                                    $fee_count = count($student_fees);
                                    
                                    if ($fee_count > 0):
                                        foreach ($student_fees as $index => $fee):
                                ?>
                                    <tr class="status-<?php echo $fee['status']; ?>">
                                        <?php if ($index == 0): ?>
                                            <td rowspan="<?php echo $fee_count; ?>" class="student-name"><?php echo $serial++; ?></td>
                                            <td rowspan="<?php echo $fee_count; ?>" class="student-name">
                                                <?php echo htmlspecialchars($data['info']['name']); ?>
                                            </td>
                                            <td rowspan="<?php echo $fee_count; ?>" class="student-name">
                                                <?php echo $data['info']['roll_number']; ?>
                                            </td>
                                            <td rowspan="<?php echo $fee_count; ?>" class="student-name">
                                                <?php echo $data['info']['class']; ?>
                                            </td>
                                        <?php endif; ?>
                                        <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                        <td>
                                            <?php 
                                            echo ($fee['month'] ? $fee['month'] . ' ' : '') . 
                                                 ($fee['academic_year'] ? $fee['academic_year'] : ''); 
                                            ?>
                                        </td>
                                        <td class="amount"><?php echo number_format($fee['amount'], 2); ?></td>
                                        <td class="amount"><?php echo number_format($fee['paid_amount'], 2); ?></td>
                                        <td class="amount"><?php echo number_format($fee['due_amount'], 2); ?></td>
                                        <td>
                                            <?php
                                            $status_names = [
                                                'pending' => 'অপেক্ষমান',
                                                'partial' => 'আংশিক',
                                                'paid' => 'পরিশোধিত',
                                                'overdue' => 'বকেয়া'
                                            ];
                                            echo $status_names[$fee['status']] ?? $fee['status'];
                                            ?>
                                        </td>
                                    </tr>
                                <?php 
                                        endforeach;
                                    else:
                                ?>
                                    <tr>
                                        <td><?php echo $serial++; ?></td>
                                        <td class="student-name"><?php echo htmlspecialchars($data['info']['name']); ?></td>
                                        <td><?php echo $data['info']['roll_number']; ?></td>
                                        <td><?php echo $data['info']['class']; ?></td>
                                        <td colspan="6" class="text-center">কোন ফি নির্ধারণ করা হয়নি</td>
                                    </tr>
                                <?php 
                                    endif;
                                endforeach; 
                                ?>
                            </tbody>
                        </table>
                        
                        <!-- Print Summary -->
                        <div class="print-summary">
                            <h4>সারসংক্ষেপ</h4>
                            <table>
                                <tr>
                                    <th>মোট শিক্ষার্থী</th>
                                    <th>মোট ফি এন্ট্রি</th>
                                    <th>মোট পরিমাণ (৳)</th>
                                    <th>মোট পরিশোধিত (৳)</th>
                                    <th>মোট বকেয়া (৳)</th>
                                    <th>সংগ্রহের হার</th>
                                </tr>
                                <tr>
                                    <td><?php echo $summary['total_students'] ?: 0; ?></td>
                                    <td><?php echo $summary['total_fees'] ?: 0; ?></td>
                                    <td><?php echo number_format($summary['total_amount'] ?: 0, 2); ?></td>
                                    <td><?php echo number_format($summary['total_paid'] ?: 0, 2); ?></td>
                                    <td><?php echo number_format($summary['total_due'] ?: 0, 2); ?></td>
                                    <td>
                                        <?php 
                                        $collection_rate = ($summary['total_amount'] > 0) ? 
                                            (($summary['total_paid'] / $summary['total_amount']) * 100) : 0;
                                        echo number_format($collection_rate, 1) . '%';
                                        ?>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <!-- Screen Version (Hidden when printing) -->
                    <div class="screen-only">
                    <?php foreach ($students_data as $student_id => $data): ?>
                        <div class="student-section">
                            <div class="student-header">
                                <div class="row">
                                    <div class="col-md-8">
                                        <h6 class="mb-1"><?php echo htmlspecialchars($data['info']['name']); ?></h6>
                                        <small>
                                            রোল: <?php echo $data['info']['roll_number']; ?> | 
                                            ক্লাস: <?php echo $data['info']['class']; ?> | 
                                            সেশন: <?php echo $data['info']['session']; ?>
                                            <?php if ($data['info']['group_name']): ?>
                                                | গ্রুপ: <?php echo $data['info']['group_name']; ?>
                                            <?php endif; ?>
                                        </small>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <div><strong>মোট: ৳<?php echo number_format($data['totals']['amount'], 2); ?></strong></div>
                                        <div><small>পরিশোধিত: ৳<?php echo number_format($data['totals']['paid'], 2); ?> | বকেয়া: ৳<?php echo number_format($data['totals']['due'], 2); ?></small></div>
                                    </div>
                                </div>
                            </div>
                            
                            <?php if (!empty($data['fees'])): ?>
                                <div class="table-responsive">
                                    <table class="table table-sm mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th>ফি এর ধরন</th>
                                                <th>মাস/বছর</th>
                                                <th>মোট পরিমাণ</th>
                                                <th>পরিশোধিত</th>
                                                <th>বকেয়া</th>
                                                <th>শেষ তারিখ</th>
                                                <th>স্ট্যাটাস</th>
                                                <th>পরিশোধের তারিখ</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($data['fees'] as $fee): ?>
                                                <tr class="fee-row <?php echo $fee['status']; ?>">
                                                    <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                                    <td>
                                                        <?php 
                                                        echo ($fee['month'] ? $fee['month'] . ' ' : '') . 
                                                             ($fee['academic_year'] ? $fee['academic_year'] : ''); 
                                                        ?>
                                                    </td>
                                                    <td>৳<?php echo number_format($fee['amount'], 2); ?></td>
                                                    <td>৳<?php echo number_format($fee['paid_amount'], 2); ?></td>
                                                    <td>৳<?php echo number_format($fee['due_amount'], 2); ?></td>
                                                    <td><?php echo date('d/m/Y', strtotime($fee['due_date'])); ?></td>
                                                    <td>
                                                        <?php
                                                        $status_labels = [
                                                            'pending' => '<span class="badge bg-warning">অপেক্ষমান</span>',
                                                            'partial' => '<span class="badge bg-info">আংশিক</span>',
                                                            'paid' => '<span class="badge bg-success">পরিশোধিত</span>',
                                                            'overdue' => '<span class="badge bg-danger">বকেয়া</span>'
                                                        ];
                                                        echo $status_labels[$fee['status']] ?? $fee['status'];
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <?php echo $fee['paid_date'] ? date('d/m/Y', strtotime($fee['paid_date'])) : '-'; ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php else: ?>
                                <div class="p-3 text-center text-muted">
                                    <i class="fas fa-info-circle"></i> এই শিক্ষার্থীর জন্য কোন ফি নির্ধারণ করা হয়নি
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                    </div> <!-- End screen-only -->
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Print Footer (Only visible when printing) -->
        <div class="print-footer" style="display: none;">
            <p>প্রিন্ট তারিখ: <?php echo date('d/m/Y H:i:s'); ?> | পৃষ্ঠা: <span class="page-number"></span></p>
        </div>
    </div>

    <?php if ($total_pages > 1): ?>
        <div class="row mt-4 no-print">
            <div class="col-12">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center">
                        <!-- First page -->
                        <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>">
                                    <i class="fas fa-angle-double-left"></i> প্রথম
                                </a>
                            </li>
                        <?php endif; ?>
                        
                        <!-- Previous page -->
                        <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                                    <i class="fas fa-chevron-left"></i> পূর্ববর্তী
                                </a>
                            </li>
                        <?php endif; ?>
                        
                        <!-- Page numbers -->
                        <?php
                        // Calculate start and end page numbers to display
                        $start_page = max(1, $page - 5);
                        $end_page = min($total_pages, $page + 4);
                        
                        // Adjust if we don't have enough pages to show
                        if ($end_page - $start_page < 9 && $total_pages > 10) {
                            if ($start_page == 1) {
                                $end_page = min(10, $total_pages);
                            } else {
                                $start_page = max(1, $end_page - 9);
                            }
                        }
                        
                        // Show first page if not in range
                        if ($start_page > 1) {
                            echo '<li class="page-item"><a class="page-link" href="?' . http_build_query(array_merge($_GET, ['page' => 1])) . '">1</a></li>';
                            if ($start_page > 2) {
                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                            }
                        }
                        
                        // Show page numbers
                        for ($i = $start_page; $i <= $end_page; $i++): ?>
                            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>
                        
                        <!-- Show last page if not in range -->
                        <?php if ($end_page < $total_pages) {
                            if ($end_page < $total_pages - 1) {
                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                            }
                            echo '<li class="page-item"><a class="page-link" href="?' . http_build_query(array_merge($_GET, ['page' => $total_pages])) . '">' . $total_pages . '</a></li>';
                        } ?>
                        
                        <!-- Next page -->
                        <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                                    পরবর্তী <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                        
                        <!-- Last page -->
                        <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>">
                                    শেষ <i class="fas fa-angle-double-right"></i>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        </div>
        
        <!-- Items per page selector -->
        <div class="row mt-3 no-print">
            <div class="col-12 text-center">
                <div class="d-inline-block">
                    <label for="itemsPerPage" class="me-2">প্রতি পৃষ্ঠায় আইটেম:</label>
                    <select id="itemsPerPage" class="form-select d-inline-block w-auto" onchange="changeItemsPerPage(this.value)">
                        <option value="10" <?php echo $limit == 10 ? 'selected' : ''; ?>>10</option>
                        <option value="25" <?php echo $limit == 25 ? 'selected' : ''; ?>>25</option>
                        <option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>50</option>
                        <option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>100</option>
                    </select>
                </div>
                <div class="d-inline-block ms-4">
                    <span>মোট রেকর্ড: <?php echo $total_records; ?></span>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Print functionality
        function printReport() {
            // Set page numbers
            const pageNumbers = document.querySelectorAll('.page-number');
            pageNumbers.forEach(el => el.textContent = '1');
            
            // Print
            window.print();
        }
        
        // Change items per page
        function changeItemsPerPage(limit) {
            const url = new URL(window.location);
            url.searchParams.set('limit', limit);
            url.searchParams.set('page', '1');
            window.location = url;
        }
        
        // Override default print button behavior
        document.addEventListener('DOMContentLoaded', function() {
            const printButtons = document.querySelectorAll('[onclick*="window.print"]');
            printButtons.forEach(button => {
                button.onclick = function(e) {
                    e.preventDefault();
                    printReport();
                };
            });
        });
    </script>
</body>
</html>