<?php
// pages/components/newsletter_ui_state_save.php
// Async endpoint to persist newsletter page UI state per user.
// Accepts POST: state_patch => JSON string of field => value pairs.
// Allowed fields: sidebar_width, sidebar_collapsed, selected_slug,
//                 smart_layout, smart_hidden, sections_open.
use Components\ConfigStore;
use Components\Newsletter\PageConfig;

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

$pageConfig = PageConfig::fromRequest();
$raw = (string) mh_post('state_patch', '', 'string');
if ($raw === '') {
    http_response_code(400);
    return;
}

$patch = json_decode($raw, true);
if (!is_array($patch)) {
    http_response_code(400);
    return;
}

// Whitelist and sanitize allowed fields
$allowed = [
    'sidebar_width'    => 'int',
    'sidebar_collapsed' => 'bool',
    'selected_slug'    => 'string',
    'selected_slug_newsletter' => 'string',
    'selected_slug_automation' => 'string',
    'smart_layout'     => 'string',
    'smart_hidden'     => 'array',
    'sections_open'    => 'object',
];

$clean = [];
foreach ($allowed as $field => $type) {
    if (!array_key_exists($field, $patch)) {
        continue;
    }
    $val = $patch[$field];
    switch ($type) {
        case 'int':
            $clean[$field] = (int) $val;
            break;
        case 'bool':
            $clean[$field] = (bool) $val;
            break;
        case 'string':
            $clean[$field] = (string) $val;
            break;
        case 'array':
            $clean[$field] = is_array($val) ? array_values(array_map('strval', $val)) : [];
            break;
        case 'object':
            $clean[$field] = is_array($val) ? $val : [];
            break;
    }
}

if (!empty($clean)) {
    // For sections_open: merge sub-keys into the existing stored map to avoid wiping other sections
    if (isset($clean['sections_open']) && is_array($clean['sections_open'])) {
        $existing = ConfigStore::getNewsletterUiState($pageConfig->mode);
        $existingSections = isset($existing['sections_open']) && is_array($existing['sections_open'])
            ? $existing['sections_open']
            : [];
        $clean['sections_open'] = array_merge($existingSections, $clean['sections_open']);
    }
    ConfigStore::setNewsletterUiState($clean, $pageConfig->mode);
}
// Return 204 No Content for HTMX (no swap needed)
http_response_code(204);
