<?php
// pages/components/coupon_export_modal.php
use Components\Models\CouponBatch;
use Components\Router;
use Components\Base;
use Components\Button;
use Components\Form\Input;
use Components\Form\Select;
use Components\Form\Toggle;
use Components\Form\RadioList;

$batchId = (int)mh_get('batch_id', 0, 'int');
if ($batchId <= 0) {
    echo Base::h(mh_lng('TEXT_INVALID_ID', 'Invalid ID'));
    return;
}
$batch = CouponBatch::find($batchId);
if (!$batch) {
    echo Base::h(mh_lng('TEXT_BATCH_NOT_FOUND', 'Batch not found'));
    return;
}

$title = mh_lng('UI_TEXT_EXPORT_COUPON_BATCH', 'Export coupon batch');
$filename = 'coupons_batch_' . $batchId . '_' . date('Y-m-d');

$columns = [
    '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',
];

$includeOptions = [
    'all' => mh_lng('UI_TEXT_INCLUDE_ALL', 'all'),
    'unused' => mh_lng('UI_TEXT_INCLUDE_UNUSED', 'unused'),
    'redeemed' => mh_lng('UI_TEXT_INCLUDE_REDEEMED', 'redeemed'),
];

$exportUrl = Router::url('coupon_export', ['batch_id' => $batchId, '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 'coupon_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="coupon-export-download-frame"
            class="hidden"
            tabindex="-1"
            aria-hidden="true"
            @load="handleFrameLoad()"></iframe>

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

<!--
            <div>
                <h3 class="text-base font-semibold text-gray-900 dark:text-white"><?= Base::h($title) ?></h3>
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400"><?= Base::h($batch->batch_name) ?></p>
            </div>
-->

            <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 class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                    <?= RadioList::render('include', mh_lng('UI_TEXT_INCLUDE', 'Include'), $includeOptions, 'all') ?>
                </div>

                <fieldset class="form-field">
                    <legend class="mb-1 block text-sm font-medium text-primary"><?= mh_lng('UI_COLUMNS', 'Columns') ?></legend>
                    <div class="mt-2 grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <?php foreach ($columns as $key => $label): ?>
                            <?= Toggle::render("columns[{$key}]", $label, in_array($key, ['coupon_id', 'coupon_code', 'coupon_amount']) ? 'on' : 'off') ?>
                        <?php endforeach; ?>
                    </div>
                </fieldset>
            </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' => 'coupon-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();
