<?php
// pages/components/newsletter_item_delete.php
// Confirmation + deletion of a Newsletter Item entry
use Components\Router;
use Components\Support\Htmx;
use Components\Models\NewsletterItem;
use Components\Button;
use Components\Newsletter\PageConfig;

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

$deleted = false;
$error = '';
$itemName = '';
$childrenCount = 0;
$isInitial = false;

// Initialize PageConfig from request (GET or POST)
$pageConfig = PageConfig::fromRequest();
$group = (string)mh_get('group', '', 'string');
$listId = (int)mh_get('list_id', 0, 'int');
$scheduleType = (string)mh_get('schedule_type', '', 'string');

$filterParams = [];
if ($group !== '') $filterParams['group'] = $group;
if ($listId > 0) $filterParams['list_id'] = $listId;
if ($scheduleType !== '') $filterParams['schedule_type'] = $scheduleType;

if ($id > 0) {
    if (class_exists(NewsletterItem::class)) {
        try {
            $model = NewsletterItem::find($id);
            if ($model) {
                $arr = $model->toArray();
                $itemName = (string)($arr['newsletter_item_name'] ?? ('#' . $id));
                $isInitial = (int)($arr['newsletter_followup_id'] ?? 0) === 0;

                // Refine page_mode based on item's schedule type if available
                $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);
                }
            }
        } catch (\Throwable $e) { /* ignore */
        }
    }

    if (class_exists('mb_newsletter_items')) {
        $childrenCount = \mb_newsletter_items::recursiveCountChildren($id);
    }
}

if ($method === 'POST' && $id > 0) {
    try {
        if (class_exists('mb_newsletter_items')) {
            \mb_newsletter_items::deepDelete($id);
            $deleted = true;
            // Emit resource-specific delete trigger for Pattern A listeners
            try {
                Htmx::trigger($pageConfig->getEventName('newsletter_item:deleted'), ['id' => (string)$id]);
            } catch (\Throwable $e) { /* ignore */
            }
            try {
                Htmx::flushTriggers();
            } catch (\Throwable $e) { /* ignore */
            }
        } else {
            $error = 'mb_newsletter_items class not found.';
        }
    } catch (\Throwable $e) {
        $error = 'Failed to delete item: ' . $e->getMessage();
    }
}

ob_start();
if ($deleted && $error === '') {
    // On successful delete: refresh list via OOB and close modal
    try {
        $_GET = array_merge($_GET, ['oob' => 1]);
        $path = Router::path('newsletter_items_list');
        if (is_string($path) && $path !== '') {
            include BEEZUI_ROOT . '/' . ltrim($path, '/');
        }
    } catch (\Throwable $e) { /* ignore */
    }

    // Trigger HTMX refresh for the list
    Htmx::trigger($pageConfig->getEventName('newsletter_item:deleted'));
    Htmx::flushTriggers();
    Htmx::parentClose('confirm-modal');
} else { ?>
    <div class="space-y-4">
        <div class="text-sm text-gray-800"><?= \mh_lng('UI_CONFIRM_DELETE_ITEM', 'Are you sure you want to delete this item?') ?></div>
        <div class="rounded border border-danger bg-danger p-3 text-sm text-danger">
            <div class="font-medium"><?= \mh_lng('UI_TEXT_ACTION_CANNOT_BE_UNDONE', 'This action cannot be undone.') ?></div>
            <div class="text-sm mt-1"><?= \mh_lng('UI_TEXT_ITEM', 'Item') ?>: <?php echo \Components\Base::h($itemName); ?> (ID #<?php echo (int)$id; ?>
                )
            </div>
            <?php if ($childrenCount > 0): ?>
                <div class="text-sm mt-2 font-semibold">
                    <?php if ($isInitial): ?>
                        <?= sprintf(\mh_lng('UI_NEWSLETTER_ITEM_DELETE_PARENT_WARNING', 'This is the parent item. The complete flow with %d children will be deleted.'), $childrenCount) ?>
                    <?php else: ?>
                        <?= sprintf(\mh_lng('UI_NEWSLETTER_ITEM_DELETE_CHILDREN_WARNING', '%d children will also be deleted.'), $childrenCount) ?>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </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('UI_BUTTON_CANCEL', 'Cancel'), [
                        'variant' => 'outline',
                        'fullWidth' => true,
                        'attrs' => [
                                'command' => 'close',
                                'commandfor' => 'confirm-modal',
                        ],
                ]) ?>

                <?= Button::render(\mh_lng('UI_BUTTON_DELETE', 'Delete'), [
                        'variant' => 'danger',
                        'fullWidth' => true,
                        'attrs' => [
                                'hx-post' => Router::url('newsletter_item_delete', array_merge(['partial' => 1, 'id' => $id, 'page_mode' => $pageConfig->mode], $filterParams)),
                                'hx-target' => '#confirm-modal-body',
                                'hx-swap' => 'innerHTML',
                        ],
                ]) ?>
            </div>
        </template>
    </div>
<?php } ?>
<?php

$__html = ob_get_clean();
echo $__html;
