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

use Components\Support\Htmx;
use Components\Models\Audience;

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

$id = (int) (mh_get('id', 0, 'int'));
$idSuffix = (string) mh_get('id_suffix', '', 'string');

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

    $new = !$it->isFavorite();
    $it->setFavorite($new);

    // Trigger collections list refresh if applicable, or just refresh counts/list if needed.
    // For audiences, we might not have a dedicated collections list yet, but we can emit a general event.
    Htmx::trigger('audience_lists:favorites: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 Audience::renderFavoriteStarHtml($it, false, $idSuffix);
} catch (\Throwable $e) {
    Htmx::noContent();
}
