<?php

namespace TableBuilderPro\Routes;

defined('ABSPATH') || exit;

class SettingsList {
    public function __construct() {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes() {
        $routes = [
            '/lists' => ['GET' => 'get_settings_list', 'POST' => 'update_settings_list'],
            '/edit' => ['POST' => 'edit_table_builder_setting'],
            '/delete/list' => ['POST' => 'delete_table_builder_settings'],
        ];

        foreach ($routes as $route => $methods) {
            foreach ($methods as $method => $callback) {
                register_rest_route('table-builder/v1', $route, [
                    'methods' => $method,
                    'callback' => [$this, $callback],
                    'permission_callback' => [$this, 'check_permissions'],
                ]);
            }
        }
    }

    public function check_permissions() {
        return current_user_can('manage_options');
    }

    public function get_settings_list() {
        return rest_ensure_response([
            'status' => 'success',
            'message' => 'Settings list fetched successfully',
            'data' => get_option('table-builder_settings_list', []),
        ]);
    }

    public function update_settings_list($request) {
        $data = $request->get_json_params();
        $actual_data = get_option('table-builder_settings_list', []);

        if (empty($data['accounts'][0]) || !$this->validate_api_key($data['accounts'][0], $data['slug'])) {
            return new \WP_Error('invalid_data', __('Invalid input data.', 'table-builder-block'), ['status' => 400]);
        }

        $slug = $data['slug'];

        if (!isset($actual_data[$slug])) {
            $actual_data[$slug] = ['slug' => $slug, 'accounts' => []];
        }

        $accounts = &$actual_data[$slug]['accounts'];

        $empty_index = array_search(true, array_map('empty', $accounts), true);
        if ($empty_index !== false) {
            $accounts[$empty_index] = $data['accounts'][0];
        } else {
            $accounts[] = $data['accounts'][0];
        }

        update_option('table-builder_settings_list', $actual_data);

        return rest_ensure_response([
            'status' => 'success',
            'message' => __('Settings list updated successfully.', 'table-builder-block'),
            'data' => $actual_data[$slug],
        ]);
    }

    public function edit_table_builder_setting($request) {
        $data = $request->get_json_params();
        $actual_data = get_option('table-builder_settings_list', []);

        if (!$this->validate_api_key($data, $data['slug']) || !isset($actual_data[$data['slug']]['accounts'][$data['index']])) {
            return new \WP_Error('invalid_data', __('Invalid API key or index.', 'table-builder-block'), ['status' => 400]);
        }

        foreach ($data as $key => $value) {
            if ($key !== 'slug' && $key !== 'index') {
                $actual_data[$data['slug']]['accounts'][$data['index']][$key] = $value;
            }
        }

        update_option('table-builder_settings_list', $actual_data);

        return rest_ensure_response([
            'success' => true,
            'message' => __('Settings updated successfully.', 'table-builder-block'),
            'updated_data' => $actual_data[$data['slug']],
        ]);
    }

    public function delete_table_builder_settings($request) {
        $data = $request->get_json_params();
        $actual_data = get_option('table-builder_settings_list', []);

        if (empty($data['slug']) || !isset($actual_data[$data['slug']]['accounts'][$data['index']])) {
            return new \WP_Error('invalid_data', __('Invalid slug or index.', 'table-builder-block'), ['status' => 400]);
        }

        unset($actual_data[$data['slug']]['accounts'][$data['index']]);
        $actual_data[$data['slug']]['accounts'] = array_values($actual_data[$data['slug']]['accounts']);

        update_option('table-builder_settings_list', $actual_data);

        return rest_ensure_response([
            'success' => true,
            'message' => __('Account deleted successfully.', 'table-builder-block'),
            'updated_data' => $actual_data[$data['slug']],
        ]);
    }

    private function validate_api_key($data, $slug) {
        // Add your validation logic here
        return true;
    }
}
