<?php
// pages/components/newsletter_collection_archive.php
// Sets the archive flag on a NewsletterCampaign and fires the campaigns:refresh event.
use Components\Models\NewsletterCampaign;
use Components\Support\Htmx;

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

if ($method === 'POST' && $id > 0) {
    try {
        $model = NewsletterCampaign::find($id);
        if ($model) {
            $arr    = $model->toArray();
            $isArch = !empty($arr['newsletter_campaign_archived'])
                      && $arr['newsletter_campaign_archived'] !== 'False'
                      && $arr['newsletter_campaign_archived'] !== '0';
            // Toggle: if already archived, unarchive; otherwise archive
            $model->newsletter_campaign_archived = $isArch ? '0' : '1';
            $model->save();
            $done = true;
            try {
                Htmx::trigger('newsletter:campaigns:refresh');
                Htmx::flushTriggers();
            } catch (\Throwable $e) { /* ignore */ }
        } else {
            $error = 'Campaign not found.';
        }
    } catch (\Throwable $e) {
        $error = 'Error: ' . $e->getMessage();
    }
}

if ($done) {
    // Response body is empty; the HX-Trigger header drives the sidebar refresh
    return;
}
if ($error !== '') {
    echo '<div class="text-sm text-red-600">' . \Components\Base::h($error, false) . '</div>';
}
