<?php
// pages/components/newsletter_item_favorite_toggle.php
// Toggle NewsletterItem favorite flag via HTMX. Returns an OOB fragment updating the star control.

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

if (!Htmx::isPost()) {
    http_response_code(405);
    echo 'Method Not Allowed';
    return;
}

$id = (int) (mh_get('id', 0, 'int'));

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);
    }

    $new = !$it->isFavorite();
    $it->setFavorite($new); // persist section when possible; in dev this is a no-op

    // Trigger collections list refresh so smart counts (e.g. Favorite) update
    // Use a dedicated event so the collection list only refreshes once (avoids double-refresh)
    Htmx::trigger($pageConfig->getEventName('newsletter_item:collections:refresh'), ['id' => (string)$id]);
    Htmx::flushTriggers();

    // Return the star HTML directly; the button uses hx-swap="outerHTML" on the wrapper span
    // The UI already updated optimistically, so we don't need to animate again on mount.
    echo NewsletterItem::renderFavoriteStarHtml($it, false);
} catch (\Throwable $e) {
    // No content on error; UI remains unchanged
    Htmx::noContent();
}
