<?php

if (!defined('ABSPATH')) {
    exit;
}

class IrepGeneralController
{

    public function __construct()
    {
        $this->init_ajax_hooks();
    }

    private function init_ajax_hooks()
    {
        add_action('wp_ajax_irep_add_table_fields',               [$this, 'add_table_fields']);
        add_action('wp_ajax_irep_get_table_fields',               [$this, 'get_table_fields']);

        add_action('wp_ajax_irep_add_table_contact_url',          [$this, 'add_table_contact_url']);
        add_action('wp_ajax_irep_get_table_contact_url',          [$this, 'get_table_contact_url']);

        add_action('wp_ajax_irep_change_table_one_column',        [$this, 'change_table_one_column']);
        add_action('wp_ajax_irep_get_table_one_column',           [$this, 'get_table_one_column']);

        add_action('wp_ajax_irep_change_table_whole_row_clickable', [$this, 'change_table_whole_row_clickable']);
        add_action('wp_ajax_irep_get_table_whole_row_clickable',    [$this, 'get_table_whole_row_clickable']);

        add_action('wp_ajax_irep_save_table_action_svgs',         [$this, 'save_table_action_svgs']);
        add_action('wp_ajax_irep_get_table_action_svgs',          [$this, 'get_table_action_svgs']);

        add_action('wp_ajax_irep_get_all_table_settings',         [$this, 'get_all_table_settings']);
        add_action('wp_ajax_irep_save_all_table_settings',        [$this, 'save_all_table_settings']);
    }

    private function canUserChangeFlatStatus()
    {
        $check = ire_fs()->is_plan_or_trial('gold', true);
        if (!$check) {
            irep_upgrade_plan();
        }
    }

    // -------------------------------------------------------------------------
    // Consolidated storage helpers
    // -------------------------------------------------------------------------

    private function get_table_settings_data(): array
    {
        $global = get_option('irep_global_settings', []);

        if (!empty($global['table'])) {
            return $global['table'];
        }

        // Migration fallback: read from legacy individual keys
        $fields = irep_handle_json_data(get_option('irep_table_fields', ''));
        if (empty($fields)) {
            $fields = [];
        }

        $actionSvgs = get_option('irep_table_action_svgs', []);
        if (!is_array($actionSvgs)) {
            $actionSvgs = [];
        }
        $svgDefaults = ['contactSvg' => '', 'downloadSvg' => '', 'magnifySvg' => ''];
        $actionSvgs  = array_merge($svgDefaults, array_intersect_key($actionSvgs, $svgDefaults));

        return [
            'fields'                  => $fields,
            'contactUrl'              => get_option('irep_table_contact_url', ''),
            'flatFieldQueryParameter' => get_option('flatFieldQueryParameter', 'id'),
            'oneColumnOnResponsive'   => (bool) get_option('irep_table_one_column', false),
            'wholeRowClickable'       => (bool) get_option('irep_table_whole_row_clickable', false),
            'actionSvgs'              => $actionSvgs,
        ];
    }

    private function save_table_settings_data(array $table): void
    {
        $global          = get_option('irep_global_settings', []);
        $global['table'] = $table;
        update_option('irep_global_settings', $global);
    }

    // -------------------------------------------------------------------------
    // New consolidated AJAX actions
    // -------------------------------------------------------------------------

    public function get_all_table_settings($data = null)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');

        $s = $this->get_table_settings_data();

        $s['fields'] = array_map(function ($item) {
            if (isset($item['sortable'])) {
                $item['sortable'] = filter_var($item['sortable'], FILTER_VALIDATE_BOOLEAN);
            }
            return $item;
        }, $s['fields']);

        $svgDefaults = ['contactSvg' => '', 'downloadSvg' => '', 'magnifySvg' => ''];
        $svgs        = array_merge($svgDefaults, array_intersect_key($s['actionSvgs'], $svgDefaults));
        foreach ($svgDefaults as $key => $_) {
            $svgs[$key] = irep_sanitize_svg((string) ($svgs[$key] ?? ''));
        }
        $s['actionSvgs'] = $svgs;

        irep_send_json_response(true, $s);
    }

    public function save_all_table_settings($data = null)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');
        $this->canUserChangeFlatStatus();

        $rawFields = $data['fields'] ?? [];
        if (is_string($rawFields)) {
            $fields = json_decode($rawFields, true) ?? [];
        } else {
            $fields = is_array($rawFields) ? $rawFields : [];
        }
        $fields = array_map(function ($item) {
            if (isset($item['sortable'])) {
                $item['sortable'] = filter_var($item['sortable'], FILTER_VALIDATE_BOOLEAN);
            }
            return $item;
        }, $fields);

        $svgKeys   = ['contactSvg', 'downloadSvg', 'magnifySvg'];
        $actionSvgs = [];
        foreach ($svgKeys as $key) {
            $raw              = isset($data[$key]) ? (string) wp_unslash($data[$key]) : '';
            $actionSvgs[$key] = irep_sanitize_svg($raw);
        }

        $table = [
            'fields'                  => $fields,
            'contactUrl'              => isset($data['contactUrl']) ? sanitize_text_field($data['contactUrl']) : '',
            'flatFieldQueryParameter' => isset($data['flatFieldQueryParameter']) ? sanitize_text_field($data['flatFieldQueryParameter']) : 'id',
            'oneColumnOnResponsive'   => isset($data['oneColumnOnResponsive']) ? rest_sanitize_boolean($data['oneColumnOnResponsive']) : false,
            'wholeRowClickable'       => isset($data['wholeRowClickable']) ? rest_sanitize_boolean($data['wholeRowClickable']) : false,
            'actionSvgs'              => $actionSvgs,
        ];

        $this->save_table_settings_data($table);

        irep_send_json_response(true, 'Settings saved successfully');
    }

    // -------------------------------------------------------------------------
    // Legacy individual setters (kept for backward compat)
    // -------------------------------------------------------------------------

    public function add_table_fields($data)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');
        $this->canUserChangeFlatStatus();

        $rawFields = $data['fields'] ?? [];
        $fields = is_string($rawFields) ? (json_decode($rawFields, true) ?? []) : (is_array($rawFields) ? $rawFields : []);

        $s           = $this->get_table_settings_data();
        $s['fields'] = $fields;
        $this->save_table_settings_data($s);

        irep_send_json_response(true, 'Fields saved successfully');
    }

    public function add_table_contact_url($data)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');
        $this->canUserChangeFlatStatus();

        $s['contactUrl']             = isset($data['contactUrl']) ? sanitize_text_field($data['contactUrl']) : '';
        $s['flatFieldQueryParameter'] = isset($data['flatFieldQueryParameter']) ? sanitize_text_field($data['flatFieldQueryParameter']) : 'id';

        $existing                              = $this->get_table_settings_data();
        $existing['contactUrl']                = $s['contactUrl'];
        $existing['flatFieldQueryParameter']   = $s['flatFieldQueryParameter'];
        $this->save_table_settings_data($existing);

        irep_send_json_response(true, 'Url saved successfully');
    }

    public function change_table_one_column($data)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');
        $this->canUserChangeFlatStatus();

        $existing                         = $this->get_table_settings_data();
        $existing['oneColumnOnResponsive'] = isset($data['oneColumnOnResponsive']) ? rest_sanitize_boolean($data['oneColumnOnResponsive']) : false;
        $this->save_table_settings_data($existing);

        irep_send_json_response(true, 'Config saved successfully');
    }

    public function change_table_whole_row_clickable($data)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');
        $this->canUserChangeFlatStatus();

        $existing                    = $this->get_table_settings_data();
        $existing['wholeRowClickable'] = isset($data['wholeRowClickable']) ? rest_sanitize_boolean($data['wholeRowClickable']) : false;
        $this->save_table_settings_data($existing);

        irep_send_json_response(true, 'Config saved successfully');
    }

    public function save_table_action_svgs($data)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');
        $this->canUserChangeFlatStatus();

        $keys       = ['contactSvg', 'downloadSvg', 'magnifySvg'];
        $actionSvgs = [];
        foreach ($keys as $key) {
            $raw              = isset($data[$key]) ? (string) wp_unslash($data[$key]) : '';
            $actionSvgs[$key] = irep_sanitize_svg($raw);
        }

        $existing               = $this->get_table_settings_data();
        $existing['actionSvgs'] = $actionSvgs;
        $this->save_table_settings_data($existing);

        irep_send_json_response(true, 'SVGs saved successfully');
    }

    // -------------------------------------------------------------------------
    // Legacy individual getters — read from consolidated storage
    // -------------------------------------------------------------------------

    public function get_table_fields($data, $returnArray = false)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');

        $fields = $this->get_table_settings_data()['fields'] ?? [];
        if (empty($fields)) {
            $fields = [];
        }

        $fields = array_map(function ($item) {
            if (isset($item['sortable'])) {
                $item['sortable'] = filter_var($item['sortable'], FILTER_VALIDATE_BOOLEAN);
            }
            return $item;
        }, $fields);

        if ($returnArray) {
            return $fields;
        }
        irep_send_json_response(true, $fields);
    }

    public function get_table_contact_url($data, $returnArray = false)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');

        $s      = $this->get_table_settings_data();
        $result = [
            'contactUrl'              => $s['contactUrl'] ?? '',
            'flatFieldQueryParameter' => $s['flatFieldQueryParameter'] ?? 'id',
        ];

        if ($returnArray) {
            return $result;
        }
        irep_send_json_response(true, $result);
    }

    public function get_table_one_column($data, $returnArray = false)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');

        $config = (bool) ($this->get_table_settings_data()['oneColumnOnResponsive'] ?? false);

        if ($returnArray) {
            return $config;
        }
        irep_send_json_response(true, $config);
    }

    public function get_table_whole_row_clickable($data, $returnArray = false)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');

        $config = (bool) ($this->get_table_settings_data()['wholeRowClickable'] ?? false);

        if ($returnArray) {
            return $config;
        }
        irep_send_json_response(true, $config);
    }

    public function get_table_action_svgs($data, $returnArray = false)
    {
        if (!is_array($data)) {
            $data = $_POST;
        }
        irep_check_nonce($data['nonce'], 'irep_nonce');

        $defaults = ['contactSvg' => '', 'downloadSvg' => '', 'magnifySvg' => ''];
        $stored   = $this->get_table_settings_data()['actionSvgs'] ?? $defaults;

        if (!is_array($stored)) {
            $stored = $defaults;
        }

        $result = array_merge($defaults, array_intersect_key($stored, $defaults));
        foreach ($defaults as $key => $_) {
            $result[$key] = irep_sanitize_svg((string) ($result[$key] ?? ''));
        }

        if ($returnArray) {
            return $result;
        }
        irep_send_json_response(true, $result);
    }

}

if (is_admin() || wp_doing_ajax()) {
    new IrepGeneralController();
}
