<?php
// pages/components/save_ui_list_per_page.php
// Persist per-user list per_page selection. Expects POST: list_id, per_page

use Components\Base;
use Components\ConfigStore;

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$listId = preg_replace('/[^a-z0-9_-]/i', '', (string)mh_post('list_id', ''));
$perPage = (int)mh_post('per_page', 0);
$redirectUrl = (string)mh_post('redirect_url', '');
$redirectTarget = (string)mh_post('redirect_target', '');

if ($listId !== '' && $perPage > 0) {
    try {
        ConfigStore::setListPerPage($listId, $perPage);
        $triggerEvent = 'list-per-page-updated';
        if ($listId !== '') {
            $triggerEvent .= ':' . $listId;
        }

//        if ($redirectUrl !== '') {
//            if ($redirectTarget !== '') {
//                header('HX-Location: ' . json_encode(['path' => $redirectUrl, 'target' => $redirectTarget, 'swap' => 'outerHTML', 'push' => false]));
//            } else {
//                header('HX-Location: ' . json_encode(['path' => $redirectUrl, 'push' => false]));
//            }
//        } else {
            header('HX-Trigger: ' . $triggerEvent);
//        }
        http_response_code(204); // No Content
        exit;
    } catch (\Throwable $e) {
        http_response_code(200);
        echo Base::h(json_encode(['ok' => false]), false);
        exit;
    }
}

http_response_code(400);
echo Base::h(json_encode(['ok' => false, 'reason' => 'bad_request']), false);
