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

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

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

    // Optional flag to suppress emitting the global refresh event. Default: true
    $emit = mh_get('emit', '1', 'raw');
    $shouldEmit = !in_array(strtolower((string)$emit), ['0', 'false', 'no', 'off'], true);

    try {
        $lists = Audience::all();
        foreach ($lists as $model) {
            try {
                $model->invalidateResultCountCache(false);
                if (method_exists($model, 'invalidateFlowCache')) {
                    $model->invalidateFlowCache(false);
                }
                $model->save();
            } catch (\Throwable $e) { /* ignore per-item */ }
        }
    } catch (\Throwable $e) { /* ignore */ }

    if ($shouldEmit) {
        // 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();
