<?php
// pages/components/audience_export.php
ob_start();
use Components\Models\Audience;

$listId = (int)mh_get('id', 0, 'int');
if ($listId <= 0) {
    die("Invalid List ID");
}
$list = Audience::find($listId);
if (!$list) {
    die("Audience list not found");
}

$format = (string)mh_post('format', mh_get('format', 'csv'));
$safeName = preg_replace('/[^a-zA-Z0-9_-]+/', '_', trim($list->newsletter_list_name));
$defaultFilename = $safeName . '_' . date('Y-m-d');
$filename = (string)mh_post('filename', mh_get('filename', $defaultFilename));
if (empty($filename)) {
    $filename = $defaultFilename;
}

// Prepare export token for cookie
$exportToken = trim((string)mh_post('export_token', '', 'string'));
if ($exportToken !== '') {
    setcookie('audience_export_ready_' . $exportToken, '1', 0, '/');
}

// Logic from legacy list_segmentation_export.php
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/mb_newsletter.php');
$newsletter_obj = \Components\Models\NewsletterItem::mbNewsletter();

$newsletter_list_id = $listId;
$newsletter_list_source = sourcebeez::get_list_source($newsletter_list_id);
$newsletter_list_raw_sql = $newsletter_obj->get_list_query_sql($newsletter_list_id, $newsletter_list_source);

$sourcebeez_module_name = $newsletter_obj->get_sourcebeez_info($newsletter_list_source);
$newsletter_obj->set_subscription_check($GLOBALS[$sourcebeez_module_name]->subscription_check);

$newsletter_list_query = mh_db_query($newsletter_list_raw_sql);

$mb_chk = new mailbeez_mailer($newsletter_obj);

$addon_export_array = array();
if (function_exists('mh_nl_export_addon_fields')) {
    $addon_export_array = mh_nl_export_addon_fields();
}

$header = array_merge(array('id', 'email','firstname', 'lastname', 'blocked', 'bounced'), $addon_export_array);

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

while (($list_item = mh_db_fetch_array($newsletter_list_query))) {
    list($check_result, $date_sent, $iteration_result, $date_block, $filter_block, $valid_block, $filter_result, $bounce_block, $check_subscr) = $mb_chk->check($newsletter_obj->get_module_id(), '', $list_item['recipient_id']);

    // Original implementation had this commented out:
    // if ($check_result) { $exclude_row++; // continue; }
    // We follow the legacy behavior which includes them but shows blocked status.

    $addon_content = array();
    if (function_exists('mh_nl_export_addon_content')) {
        $addon_content = mh_nl_export_addon_content($list_item['recipient_id']);
    }

    $row = array_merge(array(
        $list_item['recipient_id'],
        $list_item['recipient_email_address'],
        $list_item['recipient_firstname'],
        $list_item['recipient_lastname'],
        $date_block,
        $bounce_block
    ), $addon_content);

    fputcsv($fp, $row, ';');
}

// Clear any output buffers that might have captured legacy echoes (e.g. SQL queries in HTML comments)
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($newsletter_list_query);
exit;
