<?php

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

class List2Play_Servers_API {
    
    private $base_url;
    private $token;
    private $cache_duration;
    
    public function __construct() {
        $this->base_url = get_option('list2play_api_base_url', 'https://list2play.net/api');
        if (empty($this->base_url)) {
            $this->base_url = 'https://list2play.net/api';
            update_option('list2play_api_base_url', $this->base_url);
        }
        $this->token = get_option('list2play_api_token', '');
        $this->cache_duration = (int) get_option('list2play_cache_duration', 300); // 5 minutes default
    }
    
    /**
     * Make API request
     */
    private function request($endpoint, $args = []) {
        $url = rtrim($this->base_url, '/') . '/' . ltrim($endpoint, '/');
        
        if (!empty($args)) {
            $url .= '?' . http_build_query($args);
        }
        
        $cache_key = 'list2play_' . md5($url);
        $cached = get_transient($cache_key);
        
        if (false !== $cached) {
            return $cached;
        }
        
        $response = wp_remote_get($url, [
            'headers' => [
                'Authorization' => $this->token,
                'Accept' => 'application/json',
            ],
            'timeout' => 15,
        ]);
        
        if (is_wp_error($response)) {
            return [
                'error' => true,
                'message' => $response->get_error_message(),
            ];
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($status_code !== 200) {
            return [
                'error' => true,
                'message' => $data['message'] ?? 'API request failed',
                'status_code' => $status_code,
            ];
        }
        
        // Cache successful response
        set_transient($cache_key, $data, $this->cache_duration);
        
        return $data;
    }
    
    /**
     * Get servers list
     */
    public function get_servers($args = []) {
        // Default: user servers only
        if (!isset($args['user_servers_only'])) {
            $args['user_servers_only'] = true;
        }
        
        // Check for selected server IDs from admin settings
        // Only use selected_ids if server_ids is not explicitly provided
        if (!isset($args['server_ids'])) {
            $selected_ids = get_option('list2play_selected_server_ids', []);
            if (!empty($selected_ids) && is_array($selected_ids)) {
                $args['server_ids'] = $selected_ids;
                // Override user_servers_only when specific IDs are selected
                unset($args['user_servers_only']);
            }
        } else {
            // If server_ids is explicitly provided, use it and override user_servers_only
            unset($args['user_servers_only']);
        }
        
        return $this->request('v1/servers', $args);
    }
    
    /**
     * Get user's servers only
     */
    public function get_user_servers($args = []) {
        $args['user_servers_only'] = true;
        return $this->get_servers($args);
    }
    
    /**
     * Get all servers (with optional filters)
     */
    public function get_all_servers($filters = []) {
        $filters['user_servers_only'] = false;
        return $this->get_servers($filters);
    }
    
    /**
     * Get server details
     * This can get any server by ID, not just user's servers
     */
    public function get_server($server_id) {
        // Use v1 API endpoint to get server by ID
        $url = rtrim($this->base_url, '/') . '/v1/servers/' . intval($server_id);
        
        $cache_key = 'list2play_server_' . $server_id;
        $cached = get_transient($cache_key);
        
        if (false !== $cached) {
            return $cached;
        }
        
        // Try with auth first (for user's servers)
        $response = wp_remote_get($url, [
            'headers' => [
                'Authorization' => $this->token,
                'Accept' => 'application/json',
            ],
            'timeout' => 15,
        ]);
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        // If 403 or 404 with auth, try without auth (public endpoint)
        if ($status_code === 403 || $status_code === 404) {
            $response = wp_remote_get($url, [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'timeout' => 15,
            ]);
            $status_code = wp_remote_retrieve_response_code($response);
        }
        
        if (is_wp_error($response)) {
            return [
                'error' => true,
                'message' => $response->get_error_message(),
            ];
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($status_code !== 200) {
            return [
                'error' => true,
                'message' => $data['message'] ?? 'API request failed',
                'status_code' => $status_code,
            ];
        }
        
        // Cache successful response
        set_transient($cache_key, $data, $this->cache_duration);
        
        return $data;
    }
    
    /**
     * Get game types
     */
    public function get_game_types() {
        return $this->request('v1/meta/game-types');
    }
    
    /**
     * Get categories
     */
    public function get_categories() {
        return $this->request('v1/meta/categories');
    }
    
    /**
     * Get countries
     */
    public function get_countries() {
        return $this->request('v1/meta/countries');
    }
    
    /**
     * Get server players history (24 hours, public endpoint)
     */
    public function get_server_players_history($server_id, $days = 1, $granularity = 'hour') {
        // This is a public endpoint, no authentication needed
        $url = rtrim($this->base_url, '/') . '/servers/' . intval($server_id) . '/stats/players';
        $url .= '?days=' . intval($days) . '&granularity=' . urlencode($granularity);
        
        $cache_key = 'list2play_history_' . md5($url);
        $cached = get_transient($cache_key);
        
        if (false !== $cached) {
            return $cached;
        }
        
        // Public endpoint - no auth token needed
        $response = wp_remote_get($url, [
            'headers' => [
                'Accept' => 'application/json',
            ],
            'timeout' => 15,
        ]);
        
        if (is_wp_error($response)) {
            return [
                'error' => true,
                'message' => $response->get_error_message(),
            ];
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($status_code !== 200) {
            return [
                'error' => true,
                'message' => $data['message'] ?? 'API request failed',
                'status_code' => $status_code,
            ];
        }
        
        // Cache for longer duration (10 minutes for stats to reduce API requests)
        set_transient($cache_key, $data, 600);
        
        return $data;
    }
    
    /**
     * Send client metadata to API for detailed statistics
     * This is optional - basic statistics work without this
     * Respects user's privacy setting
     */
    public function send_client_metadata() {
        if (empty($this->token)) {
            return; // Can't send metadata without token
        }
        
        // Check if user has disabled metadata sending
        if (get_option('list2play_send_metadata', '1') !== '1') {
            return; // User has disabled metadata sending
        }
        
        $url = rtrim($this->base_url, '/') . '/v1/client-metadata';
        
        // Get WordPress and PHP version
        global $wp_version;
        $php_version = PHP_VERSION;
        
        // Get site URL (domain)
        $site_url = home_url();
        $url_parts = wp_parse_url($site_url);
        $domain = isset($url_parts['host']) ? $url_parts['host'] : '';
        
        // Prepare metadata
        $plugin_version = defined('LIST2PLAY_SERVERS_VERSION') ? LIST2PLAY_SERVERS_VERSION : '1.2.0';
        
        $metadata = [
            'client_name' => 'WordPress Plugin',
            'client_version' => $plugin_version,
            'platform_name' => 'WordPress',
            'platform_version' => $wp_version,
            'domain' => $domain,
            'metadata' => [
                'php_version' => $php_version,
                'site_url' => $site_url,
            ],
        ];
        
        // Send POST request (non-blocking, don't wait for response)
        wp_remote_post($url, [
            'headers' => [
                'Authorization' => $this->token,
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($metadata),
            'timeout' => 5, // Short timeout, don't block
            'blocking' => false, // Non-blocking request
        ]);
    }
    
    /**
     * Clear cache
     * Direct DB query is acceptable for admin cache clearing functionality
     */
    public function clear_cache() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
                $wpdb->esc_like('_transient_list2play_') . '%'
            )
        );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
                $wpdb->esc_like('_transient_timeout_list2play_') . '%'
            )
        );
    }
}

