<?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;

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

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

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;
            }
        } 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('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('newsletter_item:deleted');
    Htmx::flushTriggers();
    Htmx::parentClose('confirm-modal');
} else { ?>
    <div class="space-y-4">
        <div class="text-sm text-gray-800">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">This action cannot be undone.</div>
            <div class="text-sm mt-1">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): ?>
                        This is the parent item. The complete flow with <?php echo $childrenCount; ?> children will be deleted.
                    <?php else: ?>
                        <?php echo $childrenCount; ?> children will also be deleted.
                    <?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('MH_BUTTON_CANCEL', 'Cancel'), [
                        'variant' => 'outline',
                        'fullWidth' => true,
                        'attrs' => [
                                'command' => 'close',
                                'commandfor' => 'confirm-modal',
                        ],
                ]) ?>

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

$__html = ob_get_clean();
echo $__html;
