<?php
// pages/components/newsletter_item_toggle.php
// Toggle NewsletterItem.flow_status via HTMX. Emits HX-Trigger events so rows refresh (Pattern A).

use Components\Support\Htmx;
use Components\Models\NewsletterItem;
use Components\Newsletter\PageConfig;

// Only handle POST (hx-trigger="change" on checkbox)
if (!Htmx::isPost()) {
    http_response_code(405);
    echo 'Method Not Allowed';
    return;
}

$id = (int) (mh_get('id', 0, 'int'));
// When posted from a checkbox, presence of the field typically means "on"
// Accept common truthy values; otherwise treat as off
$raw = (string) (mh_post('flow_status', '', 'string'));
$truthy = in_array(strtolower(trim($raw)), ['on', '1', 'true', 'yes', 'y', 't', 'enabled', 'active', 'checked'], true);

try {
    $it = $id > 0 ? NewsletterItem::find($id) : null;
    if (!$it instanceof NewsletterItem) {
        http_response_code(404);
        echo 'Not found';
        return;
    }

    // Refine PageConfig from model for robust event prefixing
    $pageConfig = PageConfig::fromRequest();
    $type = $it->scheduleTypeCode();
    if ($type === 'automation') {
        $pageConfig = new PageConfig(PageConfig::MODE_AUTOMATION);
    } elseif ($type === 'bulk_mail' || $type === 'scheduled_window') {
        $pageConfig = new PageConfig( PageConfig::MODE_NEWSLETTER);
    }

    // Backend safety: disallow changing when in forbidden states
    if (!$it->canToggleFlowStatus()) {
        // Force a row refresh to re-sync UI with persisted state
        Htmx::trigger($pageConfig->getEventName('newsletter_item:updated'), ['id' => (string)$id]);
        Htmx::trigger($pageConfig->getEventName('newsletter_item:expandable:refresh'), ['id' => (string)$id]);
        Htmx::trigger($pageConfig->getEventName('newsletter_item:collections:refresh'), ['id' => (string)$id]);
        Htmx::flushTriggers();
        Htmx::noContent();
        return;
    }

    $ok = $it->setFlowStatusForFlow($truthy);
    // Emit refresh events regardless of success to keep UI consistent
    Htmx::trigger($pageConfig->getEventName('newsletter_item:updated'), ['id' => (string)$id]);
    Htmx::trigger($pageConfig->getEventName('newsletter_item:expandable:refresh'), ['id' => (string)$id]);
    // Dedicated event for the collections sidebar (avoids double-refresh when row also reacts to :updated)
    Htmx::trigger($pageConfig->getEventName('newsletter_item:collections:refresh'), ['id' => (string)$id]);
    Htmx::flushTriggers();
    Htmx::noContent();
    return;
} catch (\Throwable $e) {
    // Ensure client-side does not attempt a swap; still try to refresh the row
    if ($id > 0) {
        $pageConfig = \Components\Newsletter\PageConfig::fromRequest();
        Htmx::trigger($pageConfig->getEventName('newsletter_item:updated'), ['id' => (string)$id]);
        Htmx::trigger($pageConfig->getEventName('newsletter_item:expandable:refresh'), ['id' => (string)$id]);
        Htmx::trigger($pageConfig->getEventName('newsletter_item:collections:refresh'), ['id' => (string)$id]);
        Htmx::flushTriggers();
    }
    Htmx::noContent();
}
