<?php

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

class List2Play_Servers_Admin {
    
    private $api;
    
    public function __construct($api) {
        $this->api = $api;
        
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('wp_ajax_list2play_get_user_servers', [$this, 'ajax_get_user_servers']);
        add_action('wp_ajax_list2play_save_selected_servers', [$this, 'ajax_save_selected_servers']);
        add_action('wp_ajax_list2play_get_server_by_id', [$this, 'ajax_get_server_by_id']);
        add_action('wp_ajax_list2play_save_server_order', [$this, 'ajax_save_server_order']);
        
        // Add Settings link to plugin list
        add_filter('plugin_action_links_' . LIST2PLAY_SERVERS_PLUGIN_BASENAME, [$this, 'add_plugin_action_links']);
    }
    
    public function add_admin_menu() {
        add_options_page(
            __('List2Play Servers Settings', 'list2play-servers'),
            __('List2Play Servers', 'list2play-servers'),
            'manage_options',
            'list2play-servers',
            [$this, 'render_settings_page']
        );
    }
    
    public function register_settings() {
        register_setting('list2play_servers_settings', 'list2play_api_base_url', [
            'sanitize_callback' => 'esc_url_raw',
        ]);
        register_setting('list2play_servers_settings', 'list2play_api_token', [
            'sanitize_callback' => [$this, 'sanitize_api_token'],
        ]);
        register_setting('list2play_servers_settings', 'list2play_cache_duration', [
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_default_per_page', [
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_default_style_preset', [
            'default' => 'default',
            'sanitize_callback' => [$this, 'sanitize_style_preset'],
        ]);
        register_setting('list2play_servers_settings', 'list2play_selected_server_ids', [
            'type' => 'array',
            'sanitize_callback' => [$this, 'sanitize_server_ids'],
        ]);
        
        // Display options - what to show in frontend
        register_setting('list2play_servers_settings', 'list2play_show_hostname', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_status', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_address', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_game', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_region', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_players', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_map', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_votes', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_chart', [
            'default' => '0',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_stats', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        register_setting('list2play_servers_settings', 'list2play_show_vote_button', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        
        // Privacy/Statistics settings
        register_setting('list2play_servers_settings', 'list2play_send_metadata', [
            'default' => '1',
            'sanitize_callback' => 'absint',
        ]);
        
        // Initialize default API Base URL if not set
        if (get_option('list2play_api_base_url') === false) {
            add_option('list2play_api_base_url', 'https://list2play.net/api');
        }
    }
    
    public function sanitize_server_ids($value) {
        if (!is_array($value)) {
            return [];
        }
        return array_map('absint', $value);
    }

    public function sanitize_style_preset($value) {
        $allowed = ['default', 'neon-cyan', 'neon-purple', 'neon-red', 'neon-toxic'];
        $preset = sanitize_key((string) $value);
        return in_array($preset, $allowed, true) ? $preset : 'default';
    }
    
    public function enqueue_admin_assets($hook) {
        if ($hook !== 'settings_page_list2play-servers') {
            return;
        }
        
        wp_enqueue_style(
            'list2play-admin',
            LIST2PLAY_SERVERS_PLUGIN_URL . 'admin/assets/admin.css',
            [],
            LIST2PLAY_SERVERS_VERSION
        );
        
        wp_enqueue_script('jquery-ui-sortable');
        
        wp_enqueue_script(
            'list2play-admin',
            LIST2PLAY_SERVERS_PLUGIN_URL . 'admin/assets/admin.js',
            ['jquery', 'jquery-ui-sortable'],
            LIST2PLAY_SERVERS_VERSION,
            true
        );
        
        $selected_server_ids = get_option('list2play_selected_server_ids', []);
        if (!is_array($selected_server_ids)) {
            $selected_server_ids = [];
        }
        
        $server_order = get_option('list2play_server_order', []);
        if (!is_array($server_order)) {
            $server_order = [];
        }
        
        wp_localize_script('list2play-admin', 'list2playAdmin', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('list2play_admin_nonce'),
            'selectedServerIds' => array_map('absint', $selected_server_ids),
            'serverOrder' => array_map('absint', $server_order),
            'autoLoad' => true, // Auto-load servers on page load
        ]);
    }
    
    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Handle cache clear
        if (isset($_POST['clear_cache']) && check_admin_referer('list2play_clear_cache')) {
            $this->api->clear_cache();
            echo '<div class="notice notice-success"><p>' . esc_html__('Cache cleared successfully.', 'list2play-servers') . '</p></div>';
        }
        
        include LIST2PLAY_SERVERS_PLUGIN_DIR . 'admin/views/settings.php';
    }
    
    public function ajax_get_user_servers() {
        check_ajax_referer('list2play_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        // Get selected server IDs (includes manually added servers)
        $selected_ids = get_option('list2play_selected_server_ids', []);
        
        // If we have selected IDs, get those specific servers (includes manually added ones)
        if (!empty($selected_ids) && is_array($selected_ids)) {
            // First, try to get all servers via get_servers with server_ids
            $response = $this->api->get_servers([
                'server_ids' => $selected_ids,
                'per_page' => 1000, // Get all selected servers
            ]);
            
            $servers = [];
            if (!isset($response['error']) && isset($response['data']) && is_array($response['data'])) {
                $servers = $response['data'];
            }
            
            // Get server IDs that were returned
            $returned_ids = array_map(function($server) {
                return $server['id'] ?? 0;
            }, $servers);
            
            // For any missing server IDs, fetch them individually (for manually added servers)
            $missing_ids = array_diff($selected_ids, $returned_ids);
            
            foreach ($missing_ids as $server_id) {
                $server_response = $this->api->get_server($server_id);
                if (!isset($server_response['error']) && isset($server_response['id'])) {
                    $servers[] = $server_response;
                }
            }
            
            wp_send_json_success([
                'servers' => $servers,
            ]);
        } else {
            // Otherwise, get all user servers
            $response = $this->api->get_user_servers(['per_page' => 100]);
            
            if (isset($response['error'])) {
                wp_send_json_error(['message' => $response['message'] ?? 'Failed to fetch servers']);
            }
            
            wp_send_json_success([
                'servers' => $response['data'] ?? [],
            ]);
        }
    }
    
    public function ajax_save_selected_servers() {
        check_ajax_referer('list2play_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verified in AJAX handler, sanitized below with array_map('absint')
        $server_ids = isset($_POST['server_ids']) ? wp_unslash($_POST['server_ids']) : [];
        
        // Ensure it's an array and sanitize
        if (!is_array($server_ids)) {
            $server_ids = [];
        }
        $server_ids = array_map('absint', $server_ids);
        
        $server_ids = array_map('absint', $server_ids);
        $server_ids = array_filter($server_ids); // Remove empty values
        $server_ids = array_values($server_ids); // Re-index array
        
        $saved = update_option('list2play_selected_server_ids', $server_ids);
        
        wp_send_json_success([
            'message' => 'Selected servers saved successfully.',
            'saved_ids' => $server_ids,
            'saved' => $saved,
        ]);
    }
    
    public function ajax_get_server_by_id() {
        check_ajax_referer('list2play_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $server_id = isset($_POST['server_id']) ? absint($_POST['server_id']) : 0;
        
        if (!$server_id) {
            wp_send_json_error(['message' => 'Invalid server ID']);
        }
        
        $response = $this->api->get_server($server_id);
        
        if (isset($response['error'])) {
            wp_send_json_error(['message' => $response['message'] ?? 'Failed to fetch server']);
        }
        
        wp_send_json_success([
            'server' => $response,
        ]);
    }
    
    public function ajax_save_server_order() {
        check_ajax_referer('list2play_admin_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce verified in AJAX handler, sanitized below with array_map('absint')
        $server_order = isset($_POST['server_order']) ? wp_unslash($_POST['server_order']) : [];
        $server_order = array_map('absint', $server_order);
        
        update_option('list2play_server_order', $server_order);
        
        wp_send_json_success([
            'message' => 'Server order saved successfully.',
        ]);
    }
    
    /**
     * Sanitize API token and send metadata when token is saved
     */
    public function sanitize_api_token($value) {
        $old_value = get_option('list2play_api_token', '');
        $sanitized = sanitize_text_field($value);
        
        // If token changed or is new, send metadata
        if ($sanitized !== $old_value && !empty($sanitized)) {
            // Schedule metadata send (non-blocking)
            add_action('shutdown', function() use ($sanitized) {
                $api = new List2Play_Servers_API();
                $api->send_client_metadata();
            }, 20);
        }
        
        return $sanitized;
    }
    
    /**
     * Add Settings link to plugin action links
     */
    public function add_plugin_action_links($links) {
        $settings_link = '<a href="' . esc_url(admin_url('options-general.php?page=list2play-servers')) . '">' . esc_html__('Settings', 'list2play-servers') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }
}

