<?php
// pages/components/save_column_state_bulk.php
// Bulk endpoint to persist column visibility state in a single request
// Expects POST: column_map => JSON string of { key: true|false }

use Components\Base;
use Components\ConfigStore;

// Parse incoming JSON map
$raw = \mh_post('column_map', '', 'string');
if ($raw === '') {
    http_response_code(400);
    echo '<div class="text-sm text-red-600">Missing payload</div>';
    return;
}
$map = json_decode($raw, true);
if (!is_array($map)) {
    http_response_code(400);
    echo '<div class="text-sm text-red-600">Invalid payload</div>';
    return;
}

$updated = 0;
foreach ($map as $key => $state) {
    if (!is_string($key) || $key === '') {
        continue;
    }
    // Key validation: namespaced key containing ':' (e.g. "resource-list:table:column")
    if (strpos($key, ':') === false || preg_match('/^[A-Za-z0-9:_-]+$/', $key) !== 1) {
        continue;
    }

    // Normalize truthy/falsey to boolean
    $visible = ($state === 'on' || $state === '1' || $state === 1 || $state === true || $state === 'true');
    ConfigStore::setColumnState($key, $visible);
    $updated++;
}

// Nothing to update is still a success (no-op)
if (\Components\Support\Htmx::isRequest()) {
    // For HTMX, we can return 204 to avoid any swap
    if ($updated >= 0) {
        http_response_code(204);
        return;
    }
}

// Non-HTMX fallback: simple confirmation message
$label = $updated === 1 ? 'column' : 'columns';
echo '<div class="text-sm text-green-600">Updated ' . Base::h((string)$updated) . ' ' . $label . '.</div>';
