<?php
// pages/components/audience_refresh_counts.php
// Invalidates cached result_count for all Audience lists and triggers a UI-wide refresh event

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

// Always buffer inline HTML per rendering conventions
ob_start();

    try {
        $lists = Audience::all();
        foreach ($lists as $model) {
            try { $model->invalidateResultCountCache(true); } catch (\Throwable $e) { /* ignore per-item */ }
        }
    } catch (\Throwable $e) { /* ignore */ }

    // Emit a global event so visible count widgets re-fetch themselves
    Htmx::trigger('audience_lists:counts:refresh', ['ts' => (string) time()]);
    Htmx::flushTriggers();

    // Do not swap any DOM by default; keep it tiny and invisible.
//    echo '<span class="hidden" aria-hidden="true"></span>';

echo ob_get_clean();
