<?php
// pages/components/invalidate_flow_cache.php
// Invalidates the flow cache for a specific resource and triggers a refresh event.

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

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

$id = (int)($_REQUEST['id'] ?? 0);
$type = (string)($_REQUEST['type'] ?? 'newsletter_item');
$eventPrefix = (string)($_REQUEST['event_prefix'] ?? $type);

try {
    if ($type === 'newsletter_item' && $id > 0) {
        NewsletterItem::invalidateFlowCacheById($id);
        Htmx::trigger($eventPrefix . ':expandable:refresh', ['id' => (string)$id]);
    } elseif ($type === 'audience' && $id > 0) {
        $model = Audience::find($id);
        if ($model) {
            // Also invalidate the cached result_count so list counters refresh correctly
            // Keep this non-persistent to avoid unnecessary writes; flow cache persists below
            try { $model->invalidateResultCountCache(true); } catch (\Throwable $e) { /* ignore */ }
            // Audience model's invalidateFlowCache takes a $persist bool
            $model->invalidateFlowCache(true);
        }
        // Trigger refresh of the expandable flow AND all count anchors that listen for
        // "<prefix>:counts:refresh" events via Audience::countAnchorHtml()
        Htmx::trigger($eventPrefix . ':expandable:refresh', ['id' => (string)$id]);
        Htmx::trigger($eventPrefix . ':counts:refresh', ['id' => (string)$id, 'ts' => (string) time()]);
    } elseif ($id >= 0 && $type !== '' && $type !== 'newsletter_item' && $type !== 'audience') {
        // Support for generic beez modules (trigger flows)
        $moduleKey = $type;
        \mailbeez_pro::invalidateFlowCacheStatic($moduleKey);
        // For trigger modules, the ID might be 0, but the event prefix is often the module key
        Htmx::trigger($eventPrefix . ':expandable:refresh', ['id' => (string)$id]);
    }
} catch (\Throwable $e) {
    // ignore
}

// Ensure triggers are sent in headers
try { Htmx::flushTriggers(); } catch (\Throwable $e) { /* ignore */ }

echo ob_get_clean();
