<?php
// pages/components/newsletter_smart_config_toggle.php
// Toggles Smart section config (layout or individual list visibility) in the per-user
// newsletter UI state and re-renders the collections list (outerHTML swap).
use Components\ConfigStore;
use Components\Newsletter\PageConfig;

$method = (string) \mh_server('REQUEST_METHOD', 'GET');
if ($method !== 'POST') {
    return;
}

$pageConfig = PageConfig::fromRequest();
$action = (string) mh_get('toggle', '', 'string');

if ($action === 'toggle_layout') {
    $nlUiState   = ConfigStore::getNewsletterUiState($pageConfig->mode);
    $current     = isset($nlUiState['smart_layout']) ? (string)$nlUiState['smart_layout'] : 'cards';
    $next        = ($current === 'cards') ? 'list' : 'cards';
    ConfigStore::setNewsletterUiState(['smart_layout' => $next], $pageConfig->mode);
} elseif ($action === 'toggle_visibility') {
    $slug = (string) mh_get('slug', '', 'string');
    if ($slug === '') { return; }

    $nlUiState = ConfigStore::getNewsletterUiState($pageConfig->mode);
    $hidden    = isset($nlUiState['smart_hidden']) && is_array($nlUiState['smart_hidden'])
        ? array_values(array_map('strval', $nlUiState['smart_hidden']))
        : [];

    if (in_array($slug, $hidden, true)) {
        $hidden = array_values(array_diff($hidden, [$slug]));
    } else {
        $hidden[] = $slug;
    }
    ConfigStore::setNewsletterUiState(['smart_hidden' => $hidden], $pageConfig->mode);
} elseif ($action === 'set_timeframe') {
    $timeframe = (int) mh_get('timeframe', 0, 'int');
    ConfigStore::setNewsletterUiState(['smart_timeframe' => $timeframe], $pageConfig->mode);
    header('HX-Trigger: ' . $pageConfig->getEventName('timeframe:updated'));
}

// Re-render the collections list so the caller can swap it in (outerHTML)
$selectedGroup = mh_get('group', '', 'string');
require __DIR__ . '/newsletter_collection_list.php';
