<?php
// pages/components/newsletter_item_reactivate.php
// Re-activate a completed Newsletter Item (clears completed_at)
use Components\Router;
use Components\Newsletter\PageConfig;
use Components\Support\Htmx;
use Components\Models\NewsletterItem;
use Components\Button;

$id = (int)mh_get('id', 0, 'int');
$method = (string)\mh_server('REQUEST_METHOD', 'GET');

$reactivated = false;
$error = '';
$itemName = '';

if ($id > 0 && class_exists(NewsletterItem::class)) {
    try {
        $model = NewsletterItem::find($id);
        if ($model) {
            $arr = $model->toArray();
            $itemName = (string)($arr['newsletter_item_name'] ?? ('#' . $id));
        }
    } catch (\Throwable $e) { /* ignore */ }
}

if ($method === 'POST' && $id > 0) {
    try {
        $model = NewsletterItem::find($id);
        if ($model) {
            $result = $model->reactivate();
            if ($result) {
                // Refine PageConfig from model for robust event prefixing
                $pageConfig = PageConfig::fromRequest();
                $type = $model->scheduleTypeCode();
                if ($type === 'automation') {
                    $pageConfig = new PageConfig(PageConfig::MODE_AUTOMATION);
                } elseif ($type === 'bulk_mail' || $type === 'scheduled_window') {
                    $pageConfig = new PageConfig(PageConfig::MODE_NEWSLETTER);
                }

                $reactivated = true;
                try { Htmx::trigger($pageConfig->getEventName('newsletter_item:updated'), ['id' => (string)$id]); } catch (\Throwable $e) { /* ignore */ }
                try { Htmx::flushTriggers(); } catch (\Throwable $e) { /* ignore */ }
            } else {
                $error = 'Failed to re-activate item.';
            }
        } else {
            $error = 'Item not found.';
        }
    } catch (\Throwable $e) {
        $error = 'Failed to re-activate item: ' . $e->getMessage();
    }
}

ob_start();
if ($reactivated && $error === '') {
    // Refine PageConfig from model (refetch or re-use if possible, but $model is available)
    $pageConfig = PageConfig::fromRequest();
    if (isset($model)) {
        $type = $model->scheduleTypeCode();
        if ($type === 'automation') {
            $pageConfig = new PageConfig(PageConfig::MODE_AUTOMATION);
        } elseif ($type === 'bulk_mail' || $type === 'scheduled_window') {
            $pageConfig = new PageConfig(PageConfig::MODE_NEWSLETTER);
        }
    }

    // Trigger row refresh and close confirmation modal
    Htmx::trigger($pageConfig->getEventName('newsletter_item:updated'), ['id' => (string)$id]);
    try { Htmx::trigger($pageConfig->getEventName('newsletter_item:expandable:refresh'), ['id' => (string)$id]); } catch (\Throwable $e) {}
    Htmx::flushTriggers();
    Htmx::parentClose('confirm-modal');
} else { ?>
    <div class="space-y-4">
        <div class="text-sm text-gray-800">
            Re-activate this completed newsletter item? It will become eligible for sending again when its schedule allows.
        </div>
        <div class="rounded border border-brand bg-brand/5 p-3 text-sm">
            <div class="font-medium">Item: <?php echo \Components\Base::h($itemName); ?> (ID #<?php echo (int)$id; ?>)</div>
        </div>
        <?php if ($error !== ''): ?>
            <div class="text-sm text-red-700 bg-red-50 rounded p-2"><?php echo \Components\Base::h($error); ?></div>
        <?php endif; ?>

        <template x-teleport="#confirm-modal-footer">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full">
                <?= Button::render(\mh_lng('MH_BUTTON_CANCEL', 'Cancel'), [
                        'variant' => 'outline',
                        'fullWidth' => true,
                        'attrs' => [
                                'command' => 'close',
                                'commandfor' => 'confirm-modal',
                        ],
                ]) ?>

                <?= Button::render(\mh_lng('MAILBEEZ_NEWSLETTER_REACTIVATE', 'Re-activate'), [
                        'variant' => 'primary',
                        'fullWidth' => true,
                        'attrs' => [
                                'hx-post' => Router::url('newsletter_item_reactivate', ['partial' => 1, 'id' => $id]),
                                'hx-target' => '#confirm-modal-body',
                                'hx-swap' => 'innerHTML',
                        ],
                ]) ?>
            </div>
        </template>
    </div>
<?php } ?>
<?php

$__html = ob_get_clean();
echo $__html;
