<?php
// pages/components/audience_list_count.php
// Returns the computed result count for a newsletter list (Audience) and updates cache in newsletter_list_meta

use Components\Models\Audience;
use Components\Support\Format;

// Always buffer inline HTML per guideline
ob_start();

try {
    $id = (int) mh_get('id', 0, 'int');
    $refresh = (string) mh_get('refresh', '', 'raw');
    $force = ($refresh === '1' || strtolower($refresh) === 'true' || strtolower($refresh) === 'yes');

    if ($id <= 0) {
        // Return standardized anchor via model helper
        echo Audience::countAnchorHtml($id, [
            'label' => '0',
        ]);
        echo ob_get_clean();
        return;
    }

    $model = Audience::find($id);
    if (!$model) {
        echo Audience::countAnchorHtml($id, [
            'label' => '0',
        ]);
        echo ob_get_clean();
        return;
    }

    // Compute or return cached count; update cache when computed
    // Some legacy layers may emit HTML comments during computation; suppress any incidental output
    $count = 0;
    $__lvl = ob_get_level();
    try {
        ob_start();
        $count = (int) $model->getResultCount($force, 900);
    } catch (\Throwable $e) {
        $count = 0;
    } finally {
        if (ob_get_level() > $__lvl) { ob_end_clean(); }
    }

    // Return an <a> element wired with htmx so that after it swaps in once, it will still
    // listen to future global refresh events and re-fetch itself. This fixes the bug where
    // the first refresh worked but subsequent ones did not due to missing hx-* attributes
    // in the swapped HTML.
    $label = '';
    try {
        $label = Format::humanNumber($count, [
            'decimals' => 1,
            'trim_zeros' => true,
        ]);
    } catch (\Throwable $e) {
        $label = (string)(int)$count;
    }
    echo Audience::countAnchorHtml($id, [
        'label' => \Components\Base::h($label, false),
    ]);
} catch (\Throwable $e) {
    // Even on error, return a wired anchor so the UI can recover on the next refresh
    echo Audience::countAnchorHtml((int)($id ?? 0), [
        'label' => '0',
    ]);
}

echo ob_get_clean();
