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

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

    $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('newsletter_item:collections:refresh', ['id' => (string)$id]);
    Htmx::flushTriggers();

    // Return the star HTML directly; the button uses hx-swap="outerHTML" on the wrapper span
    // Animate only when the item has just been marked as favorite.
    echo NewsletterItem::renderFavoriteStarHtml($it, $new);
} catch (\Throwable $e) {
    // No content on error; UI remains unchanged
    Htmx::noContent();
}
