<?php
// pages/components/coupon_export.php
ob_start();
use Components\Models\CouponBatch;
use Components\Models\Coupon;
use Components\Support\Htmx;

$batchId = (int)mh_get('batch_id', 0, 'int');
if ($batchId <= 0) {
    die("Invalid Batch ID");
}
$batch = CouponBatch::find($batchId);
if (!$batch) {
    die("Batch not found");
}
$format = (string)mh_post('format', mh_get('format', 'csv'));
$filename = (string)mh_post('filename', mh_get('filename', 'coupons_batch_' . $batchId . '_' . date('Y-m-d')));
if (empty($filename)) {
    $filename = 'coupons_batch_' . $batchId . '_' . date('Y-m-d');
}
$include = (string)mh_post('include', mh_get('include', 'all'));
$selectedColumns = (array)mh_post('columns', mh_request('columns', []));

$allColumns = [
    'coupon_id' => 'Coupon ID',
    'coupon_code' => 'Code',
    'coupon_amount' => 'Amount',
    'coupon_type' => 'Type',
    'coupon_start_date' => 'Start Date',
    'coupon_expire_date' => 'Expire Date',
    'redeemed' => 'Redeemed',
];

// If no columns selected (e.g. initial direct link), use defaults
if (empty($selectedColumns)) {
    $selectedColumns = [
        'coupon_id' => 'on',
        'coupon_code' => 'on',
        'coupon_amount' => 'on',
        'coupon_type' => 'on',
        'coupon_start_date' => 'on',
        'coupon_expire_date' => 'on',
    ];
}

$header = [];
$activeColumns = [];
foreach ($allColumns as $key => $label) {
    if (isset($selectedColumns[$key]) && $selectedColumns[$key] === 'on') {
        $header[] = $label;
        $activeColumns[] = $key;
    }
}

// Fetch coupons with tracking info
$couponTable = Coupon::table();
$trackingTable = (string)\mh_cfg('TABLE_MAILBEEZ_TRACKING_COUPONS', 'mailbeez_tracking_coupons');

$sql = "SELECT c.*, t.redeemed FROM {$couponTable} c 
        JOIN {$trackingTable} t ON c.coupon_id = t.coupon_id 
        WHERE t.batch_id = {$batchId} ";

if ($include === 'unused') {
    $sql .= " AND t.redeemed = 0 ";
} elseif ($include === 'redeemed') {
    $sql .= " AND t.redeemed > 0 ";
}

$sql .= " ORDER BY c.coupon_id DESC";

$q = \mh_db_query($sql);

$exportToken = trim((string)mh_post('export_token', '', 'string'));
if ($exportToken !== '') {
    setcookie('coupon_export_ready_' . $exportToken, '1', 0, '/');
}

// Use a temporary stream to capture only CSV output, avoiding legacy echoes
$fp = fopen('php://temp', 'r+');
fputcsv($fp, $header, ';');

while ($row = \mh_db_fetch_array($q)) {
    $data = [];
    foreach ($activeColumns as $col) {
        $data[] = $row[$col] ?? '';
    }
    fputcsv($fp, $data, ';');
}

// Clear any output buffers that might have captured legacy echoes
while (ob_get_level() > 0) {
    ob_end_clean();
}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

rewind($fp);
fpassthru($fp);
fclose($fp);

\mh_db_free_result($q);
exit;
