<?php
namespace EveAI\Chat;

class Admin implements Loadable {
    public function init() {
        add_action('admin_menu', [$this, 'add_plugin_page']);
        add_action('admin_init', [$this, 'register_settings']);
    }

    public function add_plugin_page() {
        add_options_page(
            __('EveAI Chat Settings', 'eveai-chat'),
            __('EveAI Chat', 'eveai-chat'),
            'manage_options',
            'eveai-chat-settings',
            [$this, 'render_settings_page']
        );
    }

    public function register_settings() {
        register_setting(
            'eveai_chat_settings',
            'eveai_chat_settings',
            [$this, 'sanitize_settings']
        );

        add_settings_section(
            'eveai_chat_general',
            __('General Settings', 'eveai-chat'),
            [$this, 'render_section_info'],
            'eveai-chat-settings'
        );

        // Add settings fields
        $this->add_settings_fields();
    }

    private function add_settings_fields() {
        $fields = [
            'tenant_id' => [
                'label' => __('Tenant ID', 'eveai-chat'),
                'type' => 'number'
            ],
            'api_key' => [
                'label' => __('API Key', 'eveai-chat'),
                'type' => 'password'
            ],
            'socket_url' => [
                'label' => __('Socket URL', 'eveai-chat'),
                'type' => 'url'
            ],
            'auth_url' => [
                'label' => __('Auth URL', 'eveai-chat'),
                'type' => 'url'
            ]
        ];

        foreach ($fields as $key => $field) {
            add_settings_field(
                "eveai_chat_{$key}",
                $field['label'],
                [$this, 'render_field'],
                'eveai-chat-settings',
                'eveai_chat_general',
                [
                    'key' => $key,
                    'type' => $field['type'],
                    'label_for' => "eveai_chat_{$key}"
                ]
            );
        }
    }

    public function render_section_info() {
        echo '<p>' . esc_html__('Configure your EveAI Chat settings below.', 'eveai-chat') . '</p>';
    }

    public function render_field($args) {
        $options = get_option('eveai_chat_settings');
        $key = $args['key'];
        $type = $args['type'];
        $value = isset($options[$key]) ? $options[$key] : '';

        // If it's an API key and not empty, show placeholder
        if ($key === 'api_key' && !empty($value)) {
            $value = str_repeat('•', 20);
        }

        printf(
            '<input type="%s" id="eveai_chat_%s" name="eveai_chat_settings[%s]" value="%s" class="regular-text" />',
            esc_attr($type),
            esc_attr($key),
            esc_attr($key),
            esc_attr($value)
        );
    }

    public function sanitize_settings($input) {
        $sanitized = [];

        // Sanitize tenant_id
        $sanitized['tenant_id'] = isset($input['tenant_id']) ?
            absint($input['tenant_id']) : '';

        // Handle API key (only update if changed)
        $old_settings = get_option('eveai_chat_settings');
        if (isset($input['api_key']) && !empty($input['api_key']) &&
            $input['api_key'] !== str_repeat('•', 20)) {
            $sanitized['api_key'] = Security::encrypt_api_key($input['api_key']);
        } else {
            $sanitized['api_key'] = $old_settings['api_key'] ?? '';
        }

        // Sanitize URLs
        $sanitized['socket_url'] = isset($input['socket_url']) ?
            esc_url_raw($input['socket_url']) : 'https://chat.askeveai.com';
        $sanitized['auth_url'] = isset($input['auth_url']) ?
            esc_url_raw($input['auth_url']) : 'https://api.askeveai.com';

        return $sanitized;
    }

    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        require_once EVEAI_CHAT_PLUGIN_DIR . 'admin/views/settings-page.php';
    }
}