button link <a href="?export=csv">Download CSV</a>

// CSV export if (isset($_GET['export']) && $_GET['export'] === 'csv') {
// Clean output buffer to avoid any other output
if (ob_get_length()) {
ob_end_clean();
}

global $wpdb;
$sql = "
SELECT
cfa.ID,
cfa.form_id,
cfa.sum_total_amount,
pd.*,
total_donated_data.actual_payment_amount
FROM
wp_ntt_processed_donations pd
JOIN
wp_ntt_contact_form_addon cfa
ON pd.entry_id = cfa.ID
JOIN
(
SELECT
entry_id,
ROUND(
SUM(sub_total_for_student) +
MAX(transaction_fees) +
MAX(CASE
WHEN enable_school_optional_donation = 'yes'
THEN school_optional_donation_amount
ELSE 0
END), 2
) AS actual_payment_amount
FROM
wp_ntt_processed_donations
WHERE
donation_type = 'online'
AND payment_status = 'success'
GROUP BY
entry_id
) AS total_donated_data
ON pd.entry_id = total_donated_data.entry_id
WHERE
cfa.transaction_status = 1
AND total_donated_data.actual_payment_amount != cfa.sum_total_amount
";
$results = $wpdb->get_results($sql, ARRAY_A);


// Check if there is data to export
if (empty($results)) {
echo 'No data found!';
exit();
}

// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=payment_reconciliation_report.csv');

// Open output stream to write CSV
$output = fopen('php://output', 'w');

// Output column headers
fputcsv($output, array(
'ID', 'Form ID', 'Form Title', 'School ID', 'Donor Email',
'Student First Name', 'Student Last Name', 'Date Stamp',
'Subtotal for Student', 'Optional Donation', 'Transaction Fees',
'Sum Total Amount', 'Actual Payment Amount'
));

// Output data rows
foreach ($results as $row) {
fputcsv($output, array(
$row['ID'], $row['form_id'], $row['form_title'], $row['school_id'],
$row['donor_email_address'], $row['student_first_name'], $row['student_last_name'],
$row['datestamp'], $row['sub_total_for_student'], $row['school_optional_donation_amount'],
$row['transaction_fees'], $row['sum_total_amount'], $row['actual_payment_amount']
));
}

fclose($output);
exit();
}