<?php
// pages/components/newsletter_collection_delete.php
// Confirmation + deletion of an empty NewsletterCampaign collection

use Components\Router;
use Components\Support\Htmx;
use Components\Models\NewsletterCampaign;
use Components\Models\NewsletterItem;
use Components\Button;

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

$deleted = false;
$error = '';
$campaignName = '';
$itemCount = 0;

$campaign = null;
if ($id > 0) {
    try {
        $campaign = NewsletterCampaign::find($id);
        if ($campaign) {
            $arr = $campaign->toArray();
            $campaignName = (string)($arr['newsletter_campaign_name'] ?? ('#' . $id));
        }
    } catch (\Throwable $e) { /* ignore */ }

    // Always compute item count server-side for safety.
    try {
        $q = \mh_db_query(
            "SELECT COUNT(*) AS cnt FROM " . NewsletterItem::table() .
            " WHERE newsletter_campaign_id = " . (int)$id .
            " AND COALESCE(newsletter_followup_id, 0) = 0"
        );
        $row = \mh_db_fetch_array($q);
        $itemCount = (int)($row['cnt'] ?? 0);
        \mh_db_free_result($q);
    } catch (\Throwable $e) {
        $itemCount = 0;
    }
}

if ($method === 'POST' && $id > 0) {
    if (!$campaign) {
        $error = \mh_lng('UI_NO_RESULTS', 'Collection not found.');
    } elseif ($itemCount !== 0) {
        $error = \mh_lng('UI_ERROR_COLLECTION_NOT_EMPTY', 'This collection is not empty and cannot be deleted.');
    } else {
        try {
            $campaign->delete();
            $deleted = true;
            try {
                $pageConfig = \Components\Newsletter\PageConfig::fromRequest();
                Htmx::trigger($pageConfig->getEventName('campaigns:refresh'));
                Htmx::flushTriggers();
            } catch (\Throwable $e) { /* ignore */ }
        } catch (\Throwable $e) {
            $error = 'Failed to delete collection.';
        }
    }
}

$canDelete = ($campaign !== null && $itemCount === 0);

ob_start();
if ($deleted && $error === '') {
    Htmx::parentClose('confirm-modal');
} else { ?>
    <div class="space-y-4">
        <div class="text-sm text-gray-800"><?= \mh_lng('UI_CONFIRM_DELETE_COLLECTION', 'Are you sure you want to delete this collection?') ?></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_COLLECTION', 'Collection') ?>: <?php echo \Components\Base::h($campaignName); ?> (ID #<?php echo (int)$id; ?>)</div>
            <div class="text-sm mt-1"><?= \mh_lng('UI_TEXT_ITEMS_IN_COLLECTION', 'Items in collection') ?>: <span class="font-semibold"><?php echo (int)$itemCount; ?></span></div>
            <?php if (!$canDelete && $campaign): ?>
                <div class="text-sm mt-2 font-semibold"><?= \mh_lng('UI_ERROR_COLLECTION_NOT_EMPTY', 'This collection is not empty and cannot be deleted.') ?></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,
                        'icon' => \Components\Base::SVG_TRASH,
                        'iconPosition' => 'front',
                        'attrs' => array_merge([
                                'hx-post' => Router::url('newsletter_collection_delete', ['partial' => 1, 'id' => $id, 'page_mode' => $pageMode]),
                                'hx-target' => '#confirm-modal-body',
                                'hx-swap' => 'innerHTML',
                        ], $canDelete ? [] : ['disabled' => true, 'aria-disabled' => 'true']),
                ]) ?>
            </div>
        </template>
    </div>
<?php } ?>
<?php

$__html = ob_get_clean();
echo $__html;
