<?php
// pages/components/audience_export_modal.php
use Components\Models\Audience;
use Components\Router;
use Components\Base;
use Components\Button;
use Components\Form\Input;
use Components\Form\Select;

$listId = (int)mh_get('id', 0, 'int');
if ($listId <= 0) {
    echo Base::h(mh_lng('TEXT_INVALID_ID', 'Invalid ID'));
    return;
}
$list = Audience::find($listId);
if (!$list) {
    echo Base::h(mh_lng('MAILBEEZ_AUDIENCE_NOT_FOUND', 'Audience list not found'));
    return;
}

$title = mh_lng('UI_TEXT_EXPORT_AUDIENCE', 'Export Audience');
$safeName = preg_replace('/[^a-zA-Z0-9_-]+/', '_', trim($list->newsletter_list_name));
$filename = $safeName . '_' . date('Y-m-d');

$exportUrl = Router::url('audience_export', ['id' => $listId, 'partial' => 1]);

ob_start();
?>
    <div class=""
     x-data="{
        exporting: false,
        finished: false,
        failed: false,
        timeoutSec: <?= (int) ini_get('max_execution_time') ?: 30 ?>,
        pollMs: 400,
        timer: null,
        pollTimer: null,
        exportToken: '',

        startExport() {
            this.exporting = true;
            this.finished = false;
            this.failed = false;
            this.cleanup();

            this.exportToken = 'exp_' + Date.now() + '_' + Math.random().toString(36).slice(2, 10);
            this.$refs.exportToken.value = this.exportToken;

            this.clearReadyCookie();

            this.timer = setTimeout(() => {
                if (this.exporting) {
                    this.failExport();
                }
            }, this.timeoutSec * 1000);

            this.pollTimer = setInterval(() => {
                if (this.hasReadyCookie()) {
                    this.completeExport();
                }
            }, this.pollMs);
        },

        completeExport() {
            this.exporting = false;
            this.finished = true;
            this.failed = false;
            this.clearReadyCookie();
            this.cleanup();
        },

        failExport() {
            this.exporting = false;
            this.finished = false;
            this.failed = true;
            this.clearReadyCookie();
            this.cleanup();
        },

        cleanup() {
            if (this.timer) {
                clearTimeout(this.timer);
                this.timer = null;
            }

            if (this.pollTimer) {
                clearInterval(this.pollTimer);
                this.pollTimer = null;
            }
        },

        handleFrameLoad() {
            if (!this.exporting) {
                return;
            }
        },

        readyCookieName() {
            return 'audience_export_ready_' + this.exportToken;
        },

        hasReadyCookie() {
            if (!this.exportToken) {
                return false;
            }

            return document.cookie.split('; ').some(cookie => cookie.indexOf(this.readyCookieName() + '=1') === 0);
        },

        clearReadyCookie() {
            if (!this.exportToken) {
                return;
            }

            document.cookie = this.readyCookieName() + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
        }
     }"
>
    <iframe name="audience-export-download-frame"
            class="hidden"
            tabindex="-1"
            aria-hidden="true"
            @load="handleFrameLoad()"></iframe>

    <form id="audience-export-form"
          method="post"
          action="<?= Base::h($exportUrl) ?>"
          target="audience-export-download-frame"
          @submit="startExport()"
    >
        <input type="hidden" name="export_token" value="" x-ref="exportToken">
        <div class="space-y-6">

            <div x-show="!exporting && !finished && !failed" class="space-y-6">
                <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                    <?= Select::render('format', mh_lng('UI_TEXT_FORMAT', 'Format'), ['csv' => 'CSV'], 'csv', ['include_empty' => false]) ?>
                    <?= Input::render('filename', mh_lng('UI_TEXT_FILENAME', 'Filename'), $filename, ['addon_suffix' => '.csv']) ?>
                </div>
            </div>

            <!-- Live status messages -->
            <div x-show="exporting && !finished && !failed" class="text-sm text-gray-600 dark:text-gray-300">
                <?= Base::h(mh_lng('UI_TEXT_EXPORT_PREPARING', 'Compiling CSV… waiting for the download to start.')) ?>
            </div>
            <div x-show="finished" class="text-sm text-green-600 dark:text-green-400">
                <?= Base::h(mh_lng('UI_TEXT_EXPORT_FINISHED', 'Download started. If nothing appeared, please check your browser download settings.')) ?>
            </div>
            <div x-show="failed" class="text-sm text-red-600 dark:text-red-400">
                <?= Base::h(mh_lng('UI_TEXT_EXPORT_FAILED', 'The export did not confirm the download start in time. Please try again. If the problem persists, contact support.')) ?>
            </div>
        </div>

        <template x-teleport="#config-modal-footer">
            <div class="flex items-center justify-end gap-3 w-full">
                <span x-show="!exporting && !finished && !failed">
                    <?= Button::render(mh_lng('UI_CANCEL', 'Cancel'), [
                        'variant' => 'ghost',
                        'size' => 'md',
                        'attrs' => ['command' => 'close', 'commandfor' =>  'config-modal']
                    ]) ?>
                </span>

                <!-- Export button (hidden once exporting starts) -->
                <span x-show="!exporting && !finished && !failed">
                <?= Button::render(mh_lng('UI_TEXT_EXPORT_DOWNLOAD', 'Export & Download'), [
                        'variant' => 'primary',
                        'size' => 'md',
                        'type' => 'submit',
                        'attrs' => [
                            'form' => 'audience-export-form'
                        ]
                ]) ?>
                </span>

                <!-- Disabled indicator while exporting -->
                <span x-show="exporting && !finished && !failed" class="inline-flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
                    <svg class="h-4 w-4 animate-spin text-gray-400" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path></svg>
                    <span><?= Base::h(mh_lng('UI_TEXT_EXPORT_PREPARING_SHORT', 'Waiting for download…')) ?></span>
                </span>

                <!-- Close button after finished or failed -->
                <span x-show="finished || failed">
                <?= Button::render(mh_lng('UI_CLOSE', 'Close'), [
                        'variant' => 'primary',
                        'size' => 'md',
                        'attrs' => ['command' => 'close', 'commandfor' =>  'config-modal']
                ]) ?>
                </span>
            </div>
        </template>
    </form>
</div>
<?php
echo ob_get_clean();
