<?php

namespace GriffinForms\Admin\Ajax;

use GriffinForms\Admin\Html\Pages\Lists\ColumnPreferences;

class ListPrefs extends \GriffinForms\Admin\Ajax\Format
{
    public function __construct()
    {
        add_action('wp_ajax_gf_save_list_prefs',  [$this, 'savePrefs']);
        add_action('wp_ajax_gf_reset_list_prefs', [$this, 'resetPrefs']);
    }

    public function savePrefs(): void
    {
        check_ajax_referer('gf_list_prefs', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'griffinforms-form-builder')]);
        }

        $list_type = sanitize_key(wp_unslash($_POST['list_type'] ?? ''));
        if ($list_type === '') {
            wp_send_json_error(['message' => __('Invalid list type.', 'griffinforms-form-builder')]);
        }

        // ColumnRegistry is empty in AJAX context (registerColumns() never runs here).
        // Column keys come from our own JS data and are already sanitize_key'd — that's sufficient.
        $posted_columns = isset($_POST['columns']) && is_array($_POST['columns'])
            ? array_values(array_filter(array_map('sanitize_key', wp_unslash($_POST['columns']))))
            : [];

        $prefs = ['columns' => $posted_columns];

        if (!empty($_POST['variants']) && is_array($_POST['variants'])) {
            $prefs['variants'] = array_map('sanitize_key', wp_unslash($_POST['variants']));
        }

        if (!empty($_POST['widths']) && is_array($_POST['widths'])) {
            $prefs['widths'] = [];
            foreach (wp_unslash($_POST['widths']) as $col => $width) {
                $col   = sanitize_key($col);
                $width = preg_replace('/[^0-9a-z.%]/', '', strtolower((string) $width));
                if ($col !== '' && $width !== '') {
                    $prefs['widths'][$col] = $width;
                }
            }
        }

        if (isset($_POST['list_size'])) {
            $allowed = [10, 25, 50, 100];
            $size    = absint(wp_unslash($_POST['list_size']));
            $prefs['list_size'] = in_array($size, $allowed, true) ? $size : 10;
        }

        ColumnPreferences::getInstance()->save($list_type, $prefs);
        wp_send_json_success();
    }

    public function resetPrefs(): void
    {
        check_ajax_referer('gf_list_prefs', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'griffinforms-form-builder')]);
        }

        $list_type = sanitize_key(wp_unslash($_POST['list_type'] ?? ''));
        if ($list_type === '') {
            wp_send_json_error(['message' => __('Invalid list type.', 'griffinforms-form-builder')]);
        }

        ColumnPreferences::getInstance()->reset($list_type);
        wp_send_json_success();
    }
}
