<?php
// admin_financial_dashboard.php
// This page provides administrators and instructors with a financial dashboard,
// displaying payment history, summaries, and filtering by date range, course, modality, and bank, AND payment type.

// Ensure session is started.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in OR not an admin/instructor.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$message = '';
$is_error = false;
$all_payments = [];
$monthly_summary = [];
$bank_summary = [];
$overall_summary = [
    'total_verified_amount' => 0,
    'total_uploaded_amount' => 0,
    'total_rejected_amount' => 0,
    'total_pending_count' => 0
];

// NEW: Separate summaries for Verified amounts
$enrollment_summary = ['total_verified' => 0];
$monthly_installment_summary = ['total_verified' => 0];

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

// --- FETCH DATA FOR FILTERS ---
$all_courses = [];
$all_banks = [];
$all_modalities = ['online', 'physical'];

try {
    // Fetch all courses for the dropdown
    $stmt_courses = $pdo->query("SELECT id, course_name FROM courses ORDER BY course_name ASC");
    $all_courses = $stmt_courses->fetchAll(PDO::FETCH_ASSOC);

    // Fetch unique bank names for the dropdown from both tables
    $sql_banks = "
        SELECT DISTINCT bank_name FROM monthly_payments WHERE bank_name IS NOT NULL AND bank_name != ''
        UNION
        SELECT DISTINCT bank_name FROM payments WHERE bank_name IS NOT NULL AND bank_name != ''
        ORDER BY bank_name ASC
    ";
    $stmt_banks = $pdo->query($sql_banks);
    $all_banks = $stmt_banks->fetchAll(PDO::FETCH_COLUMN);

} catch (PDOException $e) {
    $message = "Error fetching filter data: " . $e->getMessage();
    $is_error = true;
    error_log("Admin Financial Dashboard Filter Fetch Error: " . $e->getMessage());
}

// Get date range and filter parameters from GET, or set defaults
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$filter_course_id = isset($_GET['course_id']) && $_GET['course_id'] !== '' ? $_GET['course_id'] : null;
$filter_modality = isset($_GET['modality']) && $_GET['modality'] !== '' ? $_GET['modality'] : null;
$filter_bank = isset($_GET['bank_name']) && $_GET['bank_name'] !== '' ? $_GET['bank_name'] : null;
// NEW: Payment Source Filter
$filter_payment_source = isset($_GET['payment_source']) && $_GET['payment_source'] !== '' ? $_GET['payment_source'] : null;


// Validate date format
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $start_date) || !preg_match("/^\d{4}-\d{2}-\d{2}$/", $end_date)) {
    $message = "Invalid date format. Please use YYYY-MM-DD.";
    $is_error = true;
} elseif (new DateTime($start_date) > new DateTime($end_date)) {
    $message = "Start date cannot be after end date.";
    $is_error = true;
}

try {
    if (!$is_error) {

        // --- BASE QUERY FOR MONTHLY PAYMENTS (Source: monthly) ---
        $sql_monthly_payments = "
            SELECT
                mp.id AS payment_id,
                mp.enrollment_id,
                mp.status,
                mp.paid_amount AS amount,
                mp.bank_name,
                mp.slip_number,
                mp.payment_date,
                mp.slip_path,
                'Monthly Installment' AS payment_type,
                'monthly' AS payment_source,
                u.full_name AS student_name,
                c.course_name,
                b.batch_name,
                b.modality,
                b.course_id, -- Used for filtering
                b.instructor_id -- Used for filtering
            FROM monthly_payments mp
            JOIN course_enrollments ce ON mp.enrollment_id = ce.id
            JOIN users u ON ce.student_id = u.id
            JOIN batches b ON ce.batch_id = b.id
            JOIN courses c ON b.course_id = c.id
            WHERE mp.payment_date BETWEEN ? AND ?
        ";

        // --- BASE QUERY FOR INITIAL ENROLLMENT PAYMENTS (Source: enrollment) ---
        $sql_enrollment_payments = "
            SELECT
                p.id AS payment_id,
                p.enrollment_id,
                'verified' AS status,
                p.payment_amount AS amount,
                p.bank_name,
                p.slip_number,
                p.payment_date,
                p.slip_path,
                p.payment_reason AS payment_type,
                'enrollment' AS payment_source,
                u.full_name AS student_name,
                c.course_name,
                b.batch_name,
                b.modality,
                b.course_id, -- Used for filtering
                b.instructor_id -- Used for filtering
            FROM payments p
            JOIN course_enrollments ce ON p.enrollment_id = ce.id
            JOIN users u ON ce.student_id = u.id
            JOIN batches b ON ce.batch_id = b.id
            JOIN courses c ON b.course_id = c.id
            WHERE p.payment_date BETWEEN ? AND ?
        ";

        // Initialize parameters with the date range for both queries
        $params = [$start_date, $end_date, $start_date, $end_date];

        // Apply Payment Source Filter to the UNION structure
        if ($filter_payment_source === 'enrollment') {
            $sql_combined = "($sql_enrollment_payments)";
            $params = [$start_date, $end_date]; // Reset params for single query
        } elseif ($filter_payment_source === 'monthly') {
            $sql_combined = "($sql_monthly_payments)";
            $params = [$start_date, $end_date]; // Reset params for single query
        } else {
            // Default: UNION ALL
            $sql_combined = "
                ($sql_monthly_payments)
                UNION ALL
                ($sql_enrollment_payments)
            ";
            // params remain [$start_date, $end_date, $start_date, $end_date]
        }
        
        // Wrap the UNION/single query in a subquery to apply common filters
        $sql_final = "SELECT * FROM ($sql_combined) AS combined_payments";

        // --- ADD CONDITIONAL FILTERS ---
        $where_clauses = []; 

        if ($filter_course_id) {
            $where_clauses[] = "course_id = ?";
            $params[] = $filter_course_id;
        }

        if ($filter_modality) {
            $where_clauses[] = "modality = ?";
            $params[] = $filter_modality;
        }

        if ($filter_bank) {
            $where_clauses[] = "bank_name = ?";
            $params[] = $filter_bank;
        }
        
        // Add instructor filtering if not an admin
        if ($current_user_role === 'instructor') {
            $where_clauses[] = "instructor_id = ?";
            $params[] = $current_user_id;
        }
        
        if (!empty($where_clauses)) {
            $sql_final .= " WHERE " . implode(" AND ", $where_clauses);
        }

        $sql_final .= " ORDER BY payment_date DESC";

        $stmt_payments = $pdo->prepare($sql_final);
        $stmt_payments->execute($params);
        $all_payments = $stmt_payments->fetchAll(PDO::FETCH_ASSOC);

        if (empty($all_payments)) {
            $message = "No payments found for the selected filters.";
        } else {
            // Process payments for summaries
            foreach ($all_payments as $payment) {
                // Overall Summary
                if ($payment['status'] === 'verified') {
                    $overall_summary['total_verified_amount'] += $payment['amount'];
                    
                    // NEW: Separate Verified Summaries
                    if ($payment['payment_source'] === 'enrollment') {
                        $enrollment_summary['total_verified'] += $payment['amount'];
                    } elseif ($payment['payment_source'] === 'monthly') {
                        $monthly_installment_summary['total_verified'] += $payment['amount'];
                    }
                } elseif ($payment['status'] === 'uploaded') {
                    $overall_summary['total_uploaded_amount'] += $payment['amount'];
                    $overall_summary['total_pending_count']++;
                } elseif ($payment['status'] === 'rejected') {
                    $overall_summary['total_rejected_amount'] += $payment['amount'];
                }

                // Monthly Summary (only for verified payments)
                if ($payment['status'] === 'verified') {
                    $month_key = date('Y-m', strtotime($payment['payment_date']));
                    if (!isset($monthly_summary[$month_key])) {
                        $monthly_summary[$month_key] = 0;
                    }
                    $monthly_summary[$month_key] += $payment['amount'];
                }

                // Bank Summary (only for verified payments)
                if ($payment['status'] === 'verified' && !empty($payment['bank_name'])) {
                    $bank_name_key = htmlspecialchars($payment['bank_name']);
                    if (!isset($bank_summary[$bank_name_key])) {
                        $bank_summary[$bank_name_key] = 0;
                    }
                    $bank_summary[$bank_name_key] += $payment['amount'];
                }
            }
            // Sort monthly summary by month
            krsort($monthly_summary);
        }
    }

} catch (PDOException $e) {
    $message = "Database error: " . $e->getMessage();
    $is_error = true;
    error_log("Admin Financial Dashboard Fetch Error: " . $e->getMessage());
}

?>

<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h2 class="text-3xl font-bold mb-6 text-center text-gray-800">Financial Overview & Reports</h2>

    <div id="financialPageMessage" class="mb-4 mt-2 text-center text-sm font-semibold"></div>

    <?php if (!empty($message) && !$is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-blue-50 text-blue-700 border border-blue-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if ($is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <div class="mb-8 p-4 bg-gray-50 rounded-lg shadow-sm border border-gray-200">
        <h3 class="text-xl font-semibold mb-4 text-gray-800">Generate Report</h3>
        <form action="index.php" method="GET" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-6 gap-4 items-end">
            <input type="hidden" name="page" value="admin_financial_dashboard">
            
            <div>
                <label for="start_date" class="block text-gray-700 text-sm font-semibold mb-2">Start Date:</label>
                <input type="date" id="start_date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label for="end_date" class="block text-gray-700 text-sm font-semibold mb-2">End Date:</label>
                <input type="date" id="end_date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label for="course_id" class="block text-gray-700 text-sm font-semibold mb-2">Course:</label>
                <select id="course_id" name="course_id" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">All Courses</option>
                    <?php foreach ($all_courses as $course): ?>
                        <option value="<?php echo htmlspecialchars($course['id']); ?>"
                                <?php echo ($filter_course_id == $course['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($course['course_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label for="modality" class="block text-gray-700 text-sm font-semibold mb-2">Modality:</label>
                <select id="modality" name="modality" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">All Modalities</option>
                    <?php foreach ($all_modalities as $modality): ?>
                        <option value="<?php echo htmlspecialchars($modality); ?>" <?php echo ($filter_modality === $modality) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars(ucfirst($modality)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label for="bank_name" class="block text-gray-700 text-sm font-semibold mb-2">Bank:</label>
                <select id="bank_name" name="bank_name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">All Banks</option>
                    <?php foreach ($all_banks as $bank): ?>
                        <option value="<?php echo htmlspecialchars($bank); ?>"
                                <?php echo ($filter_bank === $bank) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($bank); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div>
                <label for="payment_source" class="block text-gray-700 text-sm font-semibold mb-2">Payment Type:</label>
                <select id="payment_source" name="payment_source" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">All Payments</option>
                    <option value="enrollment" <?php echo ($filter_payment_source === 'enrollment') ? 'selected' : ''; ?>>Enrollment Fees</option>
                    <option value="monthly" <?php echo ($filter_payment_source === 'monthly') ? 'selected' : ''; ?>>Monthly Installments</option>
                </select>
            </div>

            <div class="sm:col-span-2 md:col-span-6 flex justify-end items-center space-x-2">
                <button type="submit" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-md hover:bg-blue-700 transition duration-300">
                    Generate Report
                </button>
            </div>
        </form>
    </div>

    <?php if (!$is_error && !empty($all_payments)): ?>
        <div class="mb-8">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-semibold text-gray-800">Overall Summary</h2>
                <button type="button" class="print-section-btn px-4 py-2 bg-gray-600 text-white font-semibold rounded-md hover:bg-gray-700 transition duration-300" data-section="overall-summary">
                    Print Section
                </button>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <div class="bg-gradient-to-br from-green-500 to-green-700 text-white p-6 rounded-lg shadow-lg">
                    <p class="text-sm font-light">Total Verified Revenue</p>
                    <p class="text-3xl font-bold mt-2">$<?php echo number_format($overall_summary['total_verified_amount'], 2); ?></p>
                </div>
                <div class="bg-gradient-to-br from-blue-500 to-blue-700 text-white p-6 rounded-lg shadow-lg">
                    <p class="text-sm font-light">Verified Enrollment Fees</p>
                    <p class="text-3xl font-bold mt-2">$<?php echo number_format($enrollment_summary['total_verified'], 2); ?></p>
                </div>
                <div class="bg-gradient-to-br from-indigo-500 to-indigo-700 text-white p-6 rounded-lg shadow-lg">
                    <p class="text-sm font-light">Verified Monthly Inst.</p>
                    <p class="text-3xl font-bold mt-2">$<?php echo number_format($monthly_installment_summary['total_verified'], 2); ?></p>
                </div>
                <div class="bg-gradient-to-br from-orange-400 to-orange-600 text-white p-6 rounded-lg shadow-lg">
                    <p class="text-sm font-light">Total Pending/Rejected</p>
                    <p class="text-3xl font-bold mt-2">$<?php echo number_format($overall_summary['total_uploaded_amount'] + $overall_summary['total_rejected_amount'], 2); ?></p>
                </div>
            </div>
        </div>

        <div class="mb-8">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-semibold text-gray-800">Monthly Verified Payments (<?php echo date('M Y', strtotime($start_date)); ?> to <?php echo date('M Y', strtotime($end_date)); ?>)</h2>
                <button type="button" class="print-section-btn px-4 py-2 bg-gray-600 text-white font-semibold rounded-md hover:bg-gray-700 transition duration-300" data-section="monthly-summary">
                    Print Section
                </button>
            </div>
            <div class="p-6 bg-gray-50 rounded-lg shadow-sm border border-gray-200">
                <?php if (!empty($monthly_summary)): ?>
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white border border-gray-200 rounded-lg">
                            <thead class="bg-gray-100">
                                <tr>
                                    <th class="py-2 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Month</th>
                                    <th class="py-2 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Total Verified Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($monthly_summary as $month => $amount): ?>
                                    <tr class="hover:bg-gray-50 border-b border-gray-200 last:border-b-0">
                                        <td class="py-2 px-4 text-sm text-gray-800"><?php echo date('F Y', strtotime($month . '-01')); ?></td>
                                        <td class="py-2 px-4 text-sm text-green-700 font-semibold">$<?php echo number_format($amount, 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="text-gray-600 italic">No verified payments for this date range.</p>
                <?php endif; ?>
            </div>
        </div>

        <div class="mb-8">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-semibold text-gray-800">Bank-wise Verified Payments (<?php echo date('M d, Y', strtotime($start_date)); ?> to <?php echo date('M d, Y', strtotime($end_date)); ?>)</h2>
                <button type="button" class="print-section-btn px-4 py-2 bg-gray-600 text-white font-semibold rounded-md hover:bg-gray-700 transition duration-300" data-section="bank-summary">
                    Print Section
                </button>
            </div>
            <div class="p-6 bg-gray-50 rounded-lg shadow-sm border border-gray-200">
                <?php if (!empty($bank_summary)): ?>
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white border border-gray-200 rounded-lg">
                            <thead class="bg-gray-100">
                                <tr>
                                    <th class="py-2 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Bank Name</th>
                                    <th class="py-2 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Total Verified Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php arsort($bank_summary); // Sort by amount, descending ?>
                                <?php foreach ($bank_summary as $bank => $amount): ?>
                                    <tr class="hover:bg-gray-50 border-b border-gray-200 last:border-b-0">
                                        <td class="py-2 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($bank); ?></td>
                                        <td class="py-2 px-4 text-sm text-green-700 font-semibold">$<?php echo number_format($amount, 2); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="text-gray-600 italic">No verified payments by bank for this date range.</p>
                <?php endif; ?>
            </div>
        </div>

        <div class="mb-8">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-semibold text-gray-800">Detailed Payment List (<?php echo date('M d, Y', strtotime($start_date)); ?> to <?php echo date('M d, Y', strtotime($end_date)); ?>)</h2>
                <button type="button" class="print-section-btn px-4 py-2 bg-gray-600 text-white font-semibold rounded-md hover:bg-gray-700 transition duration-300" data-section="detailed-list">
                    Print Section
                </button>
            </div>
            <div class="p-6 bg-gray-50 rounded-lg shadow-sm border border-gray-200">
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white border-collapse border border-gray-200 rounded-lg overflow-hidden">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Student</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Course</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Batch</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Modality</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Type</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Amount</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Date Paid</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Bank</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Slip No.</th>
                                <th class="py-3 px-4 text-left text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Status</th>
                                <th class="py-3 px-4 text-center text-xs font-medium text-gray-600 uppercase tracking-wider border-b border-gray-200">Slip</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($all_payments as $payment): ?>
                                <tr class="hover:bg-gray-50 border-b border-gray-200 last:border-b-0">
                                    <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['student_name']); ?></td>
                                    <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['course_name']); ?></td>
                                    <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['batch_name']); ?></td>
                                    <td class="py-3 px-4 text-sm text-gray-800 capitalize"><?php echo htmlspecialchars($payment['modality']); ?></td>
                                    <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['payment_type']); ?></td>
                                    <td class="py-3 px-4 text-sm font-semibold">$<?php echo number_format($payment['amount'], 2); ?></td>
                                    <td class="py-3 px-4 text-sm text-gray-800"><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                    <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['bank_name'] ?: 'N/A'); ?></td>
                                    <td class="py-3 px-4 text-sm text-gray-800"><?php echo htmlspecialchars($payment['slip_number'] ?: 'N/A'); ?></td>
                                    <td class="py-3 px-4 text-sm font-medium capitalize
                                        <?php
                                        if ($payment['status'] === 'verified') echo 'text-green-700';
                                        elseif ($payment['status'] === 'uploaded') echo 'text-orange-600';
                                        elseif ($payment['status'] === 'rejected') echo 'text-red-700';
                                        ?>">
                                        <?php echo htmlspecialchars($payment['status']); ?>
                                    </td>
                                    <td class="py-3 px-4 text-center">
                                        <?php if (!empty($payment['slip_path'])): ?>
                                            <button type="button" class="view-slip-btn bg-blue-500 text-white px-3 py-1 rounded-md text-xs hover:bg-blue-600 transition duration-300"
                                                    data-slip-path="<?php echo htmlspecialchars($payment['slip_path']); ?>">
                                                View
                                            </button>
                                        <?php else: ?>
                                            <span class="text-gray-500 text-xs italic">N/A</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php elseif (!$is_error): ?>
        <p class="text-center text-gray-600 text-lg mt-8">Please select a date range and click "Generate Report" to view financial data.</p>
    <?php endif; ?>

    <div class="mt-8 text-center">
        <a href="index.php?page=admin_dashboard" class="px-6 py-3 bg-gray-200 text-gray-700 font-semibold rounded-md hover:bg-gray-300 transition duration-300">
            Back to Admin Dashboard
        </a>
    </div>
</div>

<div id="viewSlipModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center hidden">
    <div class="bg-white p-6 rounded-lg shadow-xl w-full max-w-md">
        <h3 class="text-xl font-bold mb-4 text-center">Payment Slip</h3>
        <div class="text-center mb-4">
            <img id="slipImageView" src="" alt="Payment Slip" class="max-w-full h-auto rounded-md shadow-md mx-auto" onerror="this.onerror=null;this.src='https://placehold.co/300x200/cccccc/333333?text=Image+Not+Found';" />
        </div>
        <div class="flex justify-center">
            <button type="button" id="closeViewSlipModal" class="px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400">Close</button>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const viewSlipModal = document.getElementById('viewSlipModal');
        const slipImageView = document.getElementById('slipImageView');
        const closeViewSlipModalButton = document.getElementById('closeViewSlipModal');

        // Event listeners for section print buttons
        document.querySelectorAll('.print-section-btn').forEach(button => {
            button.addEventListener('click', function() {
                const targetSection = this.dataset.section;
                const startDate = document.getElementById('start_date').value;
                const endDate = document.getElementById('end_date').value;
                const courseId = document.getElementById('course_id').value;
                const modality = document.getElementById('modality').value;
                const bankName = document.getElementById('bank_name').value;
                // NEW: Get payment source filter
                const paymentSource = document.getElementById('payment_source').value;

                // Construct the URL with all relevant filters
                let printUrl = `index.php?page=admin_financial_report_print&start_date=${startDate}&end_date=${endDate}&section=${targetSection}`;
                if (courseId) printUrl += `&course_id=${courseId}`;
                if (modality) printUrl += `&modality=${modality}`;
                if (bankName) printUrl += `&bank_name=${encodeURIComponent(bankName)}`;
                // NEW: Add payment source filter
                if (paymentSource) printUrl += `&payment_source=${paymentSource}`;

                window.open(printUrl, '_blank');
            });
        });

        // Show View Slip Modal (for existing payments, reused logic)
        document.querySelectorAll('.view-slip-btn').forEach(button => {
            button.addEventListener('click', function() {
                const slipPath = this.dataset.slipPath;
                if (slipPath) {
                    slipImageView.src = slipPath;
                    viewSlipModal.classList.remove('hidden');
                } else {
                    alert("No slip image available.");
                }
            });
        });

        // Close View Slip Modal
        if (closeViewSlipModalButton) {
            closeViewSlipModalButton.addEventListener('click', function() {
                viewSlipModal.classList.add('hidden');
                slipImageView.src = '';
            });
        }
    });
</script>