<?php
// pages/components/coupon_generate_modal.php
use Components\Router;
use Components\Form\Input;
use Components\Button;
use Components\Base;
use Components\Support\Htmx;
use Components\Form\Select;
use Components\Form\RichSelect;
use Components\Ui\CollectionIdentity;
use Components\Ui\TabsGroup;
use Components\Ui\VoucherMockup;
use Components\Models\Coupon;
use Components\Models\CouponBatch;

$panelId = Htmx::resolvePanelId();
$panelTarget = '#' . $panelId . '-body';
$panelFooter = '#' . $panelId . '-footer';

$id = (int) mh_post('id', (int) mh_get('id', 0, 'int'));
$selectable_coupon = (bool) mh_post('selectable_coupon', (bool) mh_get('selectable_coupon', false));

// When no template coupon id is provided, render a lightweight selector first
if ($id <= 0) {
    $title = mh_lng('TEXT_SELECT_TEMPLATE_COUPON', 'Select template coupon');
    $formId = 'coupon-select-form-' . uniqid();

    // Build options from Coupon::listOptions
    $rawOptions = Coupon::listOptions(false);
    $options = [
        0 => [
            'label' => (string)mh_lng('TEXT_SELECT_A_COUPON', 'select a coupon'),
            'disabled' => true
        ]
    ];
    foreach ($rawOptions as $key => $opt) {
        $rawLabel = is_array($opt) ? ($opt['label'] ?? (string)$key) : (string)$opt;
        $identity = is_array($opt) ? ($opt['identity'] ?? null) : null;
        if ($identity) {
            $options[$key] = [
                'label' => $rawLabel,
                'label_html' => CollectionIdentity::render(Base::h($rawLabel), $identity)
            ];
        } else {
            $options[$key] = $rawLabel;
        }
    }

    ob_start();
    ?>
    <form x-data="{ selectedId: 0 }" id="<?= $formId ?>" hx-post="<?= Router::url('coupon_generate_modal', ['partial' => 1]) ?>" hx-target="#config-modal-body" data-no-global-loader="1" data-no-local-loader="1">
        <input type="hidden" name="selectable_coupon" value="<?= $selectable_coupon ? '1' : '0' ?>">
        <div class="space-y-4">
            <?= RichSelect::render('id', (string)mh_lng('TEXT_TEMPLATE_COUPON', 'Template coupon'), $options, 0, [
                'input_attrs' => 'x-model="selectedId"'
            ]) ?>
        </div>

        <template x-teleport="<?= $panelFooter ?>">
            <div class="flex items-center justify-end gap-3 w-full">
                <?= Button::render(mh_lng('MH_BUTTON_CANCEL'), [
                    'variant' => 'ghost',
                    'size' => 'md',
                    'attrs' => ['command' => 'close', 'commandfor' =>  $panelId]
                ]) ?>
                <?= Button::render(mh_lng('MH_BUTTON_PROCEED', 'Proceed'), [
                    'variant' => 'primary',
                    'size' => 'md',
                    'type' => 'submit',
                    'attrs' => [
                        'form' => $formId,
                        ':disabled' => 'selectedId == 0'
                    ]
                ]) ?>
            </div>
        </template>
    </form>
    <?php

    $content = ob_get_clean();
    ?>
    <div class="space-y-3 py-4">
        <span hx-swap-oob="innerHTML:#<?= $panelId ?>-title"><?= Base::h($title) ?></span>
        <?= $content ?>
    </div>
    <?php
    return;
}

// Instantiate engine
if (!class_exists('couponbeez')) {
    $configDir = function_exists('mh_cfg') ? mh_cfg('MH_DIR_CONFIG') : null;
    if ($configDir && file_exists($configDir . 'config_coupon_engine/classes/couponbeez.php')) {
        require_once($configDir . 'config_coupon_engine/classes/couponbeez.php');
    }
}
$cbEngine = class_exists('couponbeez') ? new \couponbeez() : null;

mh_load_modules_language_files(mh_cfg('MH_DIR_CONFIG'), 'config_coupon_engine');

if (!$cbEngine) {
    echo Base::h(mh_lng('TEXT_COUPON_ENGINE_NOT_AVAILABLE'));
    return;
}

$templateData = $cbEngine->read_coupon($id);
if (!$templateData) {
    echo Base::h(mh_lng('TEXT_TEMPLATE_NOT_FOUND'));
    return;
}

$typeLabel = $cbEngine->get_coupon_type_label($id);
$code = $templateData['coupon']['coupon_code'];
$codeMain = str_replace('template_', '', (string)$code);
$couponType = $templateData['coupon']['coupon_type'] ?? '';

$numTotal = (int)mh_post('num_coupons', (int)mh_get('num_coupons', 1));
$generatedSoFar = (int)mh_post('generated', 0);
$validityType = (string)mh_post('validity_type', (string)mh_get('validity_type', 'days'));
$validityDays = (int)mh_post('validity_days', (int)mh_get('validity_days', 30));
$endDate = (string)mh_post('end_date', (string)mh_get('end_date', ''));

$prefix = (string)mh_post('prefix', (string)mh_get('prefix', mh_cfg('MAILBEEZ_CONFIG_COUPON_ENGINE_DEFAULT_PREFIX', '')));
$batchType = (string)mh_post('batch_type', (string)mh_get('batch_type', ''));
$batchName = (string)mh_post('batch_name', (string)mh_get('batch_name', ''));
if (empty($batchName)) {
    $batchName = $typeLabel . ' - ' . date('M Y');
}
$batchId = (int)mh_post('batch_id', 0);

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $generatedSoFar == 0) {
    if (empty($batchType)) {
        $errors['batch_type'][] = (string)mh_lng('TEXT_ERROR_BATCH_TYPE_REQUIRED');
    }

    if (strlen($batchName) < 5) {
        $errors['batch_name'][] = (string)mh_lng('TEXT_ERROR_BATCH_NAME_TOO_SHORT');
    } else {
        $batchTable = \Components\Models\CouponBatch::table();
        $checkSql = "SELECT COUNT(*) as total FROM {$batchTable} WHERE batch_name = '" . mh_db_input($batchName) . "'";
        $checkQuery = mh_db_query($checkSql);
        $checkResult = mh_db_fetch_array($checkQuery);
        if ($checkResult['total'] > 0) {
            $errors['batch_name'][] = (string)mh_lng('TEXT_ERROR_BATCH_NAME_NOT_UNIQUE');
        }
    }

    if ($numTotal < 1 || $numTotal > 100000) {
        $errors['num_coupons'][] = (string)mh_lng('TEXT_ERROR_NUM_COUPONS_RANGE');
    }

    if (!empty($prefix)) {
        if (strlen($prefix) > 8) {
            $errors['prefix'][] = (string)mh_lng('TEXT_ERROR_PREFIX_TOO_LONG');
        }
        if (!preg_match('/^[a-zA-Z0-9-]*$/', $prefix)) {
            $errors['prefix'][] = (string)mh_lng('TEXT_ERROR_PREFIX_INVALID_CHARS');
        }
    }

    if ($validityType === 'days') {
        if ($validityDays < 7 || $validityDays > 1000) {
            $errors['validity_days'][] = (string)mh_lng('TEXT_ERROR_VALIDITY_DAYS_RANGE');
        }
    } else if ($validityType === 'date') {
        $days = (strtotime($endDate) - strtotime(date('Y-m-d'))) / 86400;
        if ($days < 7 || $days > 1000) {
            $errors['end_date'][] = (string)mh_lng('TEXT_ERROR_END_DATE_RANGE');
        }
    }
}

$title = mh_lng('UI_BUTTON_GENERATE_COUPON_SERIES');
$formId = 'coupon-generate-form-' . uniqid();

ob_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($errors)) {
    if ($generatedSoFar == 0 && !empty($batchName)) {
        // Create batch on first run
        $batch = new \Components\Models\CouponBatch([
            'batch_name' => $batchName,
            'template_coupon_id' => $id,
            'date_created' => date('Y-m-d H:i:s'),
            'batch_type' => $batchType,
            'prefix' => $prefix
        ]);
        if ($batch->save()) {
            $batchId = (int)$batch->batch_id;
        }
    }

    $expireDate = null;
    if ($validityType === 'days') {
        $expireDate = $cbEngine->generate_coupon_date($validityDays);
    } else if ($validityType === 'date' && !empty($endDate)) {
        if (strlen($endDate) == 10) {
            $expireDate = $endDate . " 23:59:59";
        } else {
            $expireDate = $endDate;
        }
    }

    $batchSize = 10;
    $remaining = $numTotal - $generatedSoFar;
    $toGenerate = min($batchSize, $remaining);

    $generatedInThisBatch = 0;
    for ($i = 0; $i < $toGenerate; $i++) {
        $newCode = $cbEngine->generate_coupon_code(6, 42, $prefix);
        $newData = $templateData;
        unset($newData['coupon']['coupon_id']);
        $newData['coupon']['coupon_code'] = $newCode;
        if ($expireDate) {
            $newData['coupon']['coupon_expire_date'] = $expireDate;
        }
        $newData['coupon']['coupon_active'] = 'Y';
        $newData['coupon']['coupon_start_date'] = date("Y-m-d H:i:s", strtotime('-1 day'));
        $newData['coupon']['date_created'] = date('Y-m-d H:i:s');
        $newData['coupon']['date_modified'] = date('Y-m-d H:i:s');
        
        $insert_id = $cbEngine->write_coupon($newData);
        if ($insert_id) {
            $generatedInThisBatch++;

            $cbEngine->track_coupon([
                'coupon_id' => $insert_id,
                'template_coupon_id' => $id,
                'batch_id' => $batchId,
                'customer_id_sent' => 0,
                'emailed_to' => '',
                'message_id' => 0,
                'module' => 'coupon_generate_modal'
            ]);
        }
    }

    $totalGenerated = $generatedSoFar + $generatedInThisBatch;

    if ($totalGenerated < $numTotal) {
        // Progress State
        $title = mh_lng('TEXT_GENERATING_COUPONS');
        $percent = round(($totalGenerated / $numTotal) * 100);
        ?>
        <div class="flex gap-8 items-stretch"
             hx-post="<?= Router::url('coupon_generate_modal', ['partial' => 1, 'id' => $id]) ?>"
             hx-trigger="load delay:50ms"
             hx-target="<?= $panelTarget ?>"
             hx-include="this"
             data-no-global-loader="1"
             data-no-local-loader="1">

            <div class="w-1/3 min-w-[300px] bg-muted rounded-2xl p-6 flex flex-col justify-center">
                <div class="aspect-[316/190]">
                    <?= VoucherMockup::render($typeLabel, $codeMain, $code, (string)\mh_lng('UI_TEXT_COUPON_NO_RESTRICTIONS', 'no restrictions'), $couponType) ?>
                </div>
            </div>

            <div class="flex-1 flex flex-col justify-center space-y-4">
                <input type="hidden" name="selectable_coupon" value="<?= $selectable_coupon ? '1' : '0' ?>">
                <input type="hidden" name="num_coupons" value="<?= $numTotal ?>">
                <input type="hidden" name="generated" value="<?= $totalGenerated ?>">
                <input type="hidden" name="validity_type" value="<?= Base::h($validityType) ?>">
                <input type="hidden" name="validity_days" value="<?= $validityDays ?>">
                <input type="hidden" name="end_date" value="<?= Base::h($endDate) ?>">
                <input type="hidden" name="prefix" value="<?= Base::h($prefix) ?>">
                <input type="hidden" name="batch_type" value="<?= Base::h($batchType) ?>">
                <input type="hidden" name="batch_name" value="<?= Base::h($batchName) ?>">
                <input type="hidden" name="batch_id" value="<?= $batchId ?>">

                <div class="flex items-center justify-between mb-1">
                    <span class="text-sm font-medium text-brand-700 dark:text-brand-300"><?= Base::h(sprintf(mh_lng('TEXT_GENERATED_X_OF_Y_COUPONS'), $totalGenerated, $numTotal)) ?></span>
                    <span class="text-sm font-medium text-brand-700 dark:text-brand-300"><?= $percent ?>%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700">
                    <div class="bg-brand-600 h-2.5 rounded-full transition-all duration-300" style="width: <?= $percent ?>%"></div>
                </div>
            </div>

            <template x-teleport="#config-modal-footer">
                <div class="flex justify-end w-full">
                    <?= Button::render(mh_lng('MH_BUTTON_STOP'), [
                        'variant' => 'danger',
                        'size' => 'md',
                        'attrs' => ['command' => 'close', 'commandfor' => 'config-modal']
                    ]) ?>
                </div>
            </template>
        </div>
        <?php
    } else {
        // Success State
        $title = mh_lng('TEXT_SUCCESS');
        Htmx::trigger('coupon:created');
        Htmx::trigger('coupons:refresh');
        Htmx::trigger('notification', ['level' => 'success', 'message' => Base::h(sprintf(mh_lng('TEXT_X_COUPONS_GENERATED'), $totalGenerated))]);
        Htmx::flushTriggers();
        ?>
        <div class="flex gap-8 items-stretch">
            <div class="w-1/3 min-w-[300px] bg-muted rounded-2xl p-6 flex flex-col justify-center">
                <div class="aspect-[316/190]">
                    <?= VoucherMockup::render($typeLabel, $codeMain, $code, (string)\mh_lng('UI_TEXT_COUPON_NO_RESTRICTIONS', 'no restrictions'), $couponType) ?>
                </div>
            </div>

            <div class="flex-1 flex flex-col justify-center text-center gap-4">
                <?= \Components\Modal::getIconForType('info') ?>
                <h1 class="text-xl font-semibold text-gray-900 dark:text-white text-center mt-1"><?= Base::h(mh_lng('TEXT_GENERATION_COMPLETE')) ?></h1>
                <p class="text-sm text-gray-500">
                    <?= Base::h(sprintf(mh_lng('TEXT_GENERATION_SUCCESS_MSG'), $totalGenerated, Base::h($templateData['coupon']['coupon_code']))) ?>
                </p>
            </div>

            <template x-teleport="#config-modal-footer">
                <div class="flex justify-end w-full">
                    <?= Button::render(mh_lng('MH_BUTTON_CLOSE'), [
                        'variant' => 'primary',
                        'attrs' => ['command' => 'close', 'commandfor' => 'config-modal']
                    ]) ?>
                </div>
            </template>
        </div>
        <?php
    }
} else {
    // Initial Form State
    ?>
    <form id="<?= $formId ?>" hx-post="<?= Router::url('coupon_generate_modal', ['partial' => 1, 'id' => $id]) ?>" hx-target="#config-modal-body" data-no-global-loader="1" data-no-local-loader="1">
        <input type="hidden" name="selectable_coupon" value="<?= $selectable_coupon ? '1' : '0' ?>">
        <div class="flex gap-8 items-stretch">
            <div class="w-1/3 min-w-[300px] bg-muted rounded-2xl p-6 flex flex-col justify-center">
                <?php if ($selectable_coupon): ?>
                <div class="mb-2">
                    <?= Button::render(mh_lng('TEXT_SELECT_DIFFERENT_TEMPLATE', 'Select different template'), [
                        'variant' => 'ghost',
                        'size' => 'sm',
                        'attrs' => [
                            'hx-get' => Router::url('coupon_generate_modal', ['partial' => 1, 'selectable_coupon' => 1]),
                            'hx-target' => '#config-modal-body',
                            'hx-swap' => 'innerHTML'
                        ]
                    ]) ?>
                </div>
                <?php endif; ?>
                <div class="aspect-[316/190]">
                    <?= VoucherMockup::render($typeLabel, $codeMain, $code, (string)\mh_lng('UI_TEXT_COUPON_NO_RESTRICTIONS', 'no restrictions'), $couponType) ?>
                </div>
            </div>

            <div class="flex-1 space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <?= Input::render('batch_name', (string)mh_lng('TEXT_BATCH_NAME', 'batch name'), $batchName, [
                        'placeholder' => 'e.g. Spring Event 2026',
                        'validate' => [
                            'required' => true
                        ],
                        'input_attrs' => 'minlength="5"',
                        'errors' => $errors['batch_name'] ?? []
                    ]) ?>
                    <?= Input::render('num_coupons', (string)mh_lng('TEXT_NUM_COUPONS_TO_GENERATE', 'Number of coupons' ), $numTotal, [
                        'validate' => [
                            'type' => 'integer',
                            'min' => 1,
                            'max' => 100000,
                            'required' => true
                        ],
                        'errors' => $errors['num_coupons'] ?? []
                    ]) ?>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <?= Input::render('prefix', (string)mh_lng('TEXT_COUPON_PREFIX', 'prefix'), $prefix, [
                        'placeholder' => 'e.g. OFF-',
                        'validate' => [
                            'max' => 8
                        ],
                        'input_attrs' => 'maxlength="8" pattern="[a-zA-Z0-9-]*"',
                        'errors' => $errors['prefix'] ?? []
                    ]) ?>
                    <?= RichSelect::render('batch_type', (string)mh_lng('UI_TEXT_BATCH_TYPE', 'Type'), CouponBatch::getTypeOptions(false, (string)mh_lng('UI_TEXT_SELECT_TYPE', 'select type')), $batchType, [
                        'validate' => [
                            'required' => true
                        ],
                        'errors' => $errors['batch_type'] ?? []
                    ]) ?>
                </div>

                <div x-data="{ validity_type: '<?= Base::h($validityType) ?>' }" class="space-y-4">
                    <input type="hidden" name="validity_type" x-model="validity_type">

                    <div class="rounded-lg border border-gray-200 dark:border-white/10 dark:bg-gray-800/40 overflow-hidden">
                        <div class="flex flex-wrap items-center gap-2 px-3 py-2">
                            <span class="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider"><?= Base::h((string)mh_lng('TEXT_VALIDITY', 'Validity')) ?></span>
                            <?= TabsGroup::render([
                                [
                                    'label' => (string)mh_lng('TEXT_DAYS_FROM_NOW', 'Days from now'),
                                    'value' => 'days',
                                ],
                                [
                                    'label' => (string)mh_lng('TEXT_FIXED_DATE', 'Fixed date'),
                                    'value' => 'date',
                                ]
                            ], [
                                'class' => 'ml-auto',
                                'model' => 'validity_type'
                            ]) ?>
                        </div>

                        <div class="px-3 py-2.5 min-h-[44px]">
                            <template x-if="validity_type === 'days'">
                                <div>
                                    <?= Input::render('validity_days', (string)mh_lng('TEXT_VALIDITY_IN_DAYS', 'Validity in days'), $validityDays, [
                                        'validate' => [
                                            'type' => 'integer',
                                            'min' => 7,
                                            'max' => 1000,
                                            'required' => true
                                        ],
                                        'no_label' => true,
                                        'placeholder' => (string)mh_lng('TEXT_VALIDITY_IN_DAYS', 'Validity in days'),
                                        'errors' => $errors['validity_days'] ?? []
                                    ]) ?>
                                </div>
                            </template>
                            <template x-if="validity_type === 'date'">
                                <div>
                                    <?= Input::render('end_date', (string)mh_lng('TEXT_END_DATE', 'End date'), $endDate ?: date('Y-m-d', strtotime('+30 days')), [
                                        'input_type' => 'date',
                                        'validate' => [
                                            'min' => date('Y-m-d', strtotime('+7 days')),
                                            'max' => date('Y-m-d', strtotime('+1000 days')),
                                            'required' => true
                                        ],
                                        'no_label' => true,
                                        'errors' => $errors['end_date'] ?? []
                                    ]) ?>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <template x-teleport="<?= $panelFooter ?>">
            <div class="flex items-center justify-end gap-3 w-full">
                <?= Button::render(mh_lng('MH_BUTTON_CANCEL'), [
                    'variant' => 'ghost',
                    'size' => 'md',
                    'attrs' => ['command' => 'close', 'commandfor' =>  $panelId]
                ]) ?>
                <?= Button::render(mh_lng('TEXT_GENERATE_COUPONS'), [
                    'variant' => 'primary',
                    'size' => 'md',
                    'type' => 'submit',
                    'attrs' => [
                        'form' => $formId
                    ]
                ]) ?>
            </div>
        </template>
    </form>
    <?php
}

$content = ob_get_clean();
?>
<div class="space-y-3 py-4">
    <span hx-swap-oob="innerHTML:#<?= $panelId ?>-title"><?= Base::h($title) ?></span>
    <?= $content ?>
</div>
