<?php
/**
 * TalkGenAI API Class
 * Handles communication with the TalkGenAI server
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit('Direct access not allowed.');
}

class TalkGenAI_API {
    
    /**
     * Plugin settings
     */
    private $settings;
    
    /**
     * Server configurations
     */
    private $server_configs;
    
    /**
     * Default settings
     */
    private $default_settings = array(
        'server_mode' => 'remote',  // Default to remote for production users
        'local_server_url' => 'http://localhost:8000',
        'remote_server_url' => 'https://app.talkgen.ai',  // Production server URL
        'remote_api_key' => '',  // User must provide their own API key
        'max_requests_per_hour' => 100,  // Default rate limit
        'enable_debug_logging' => false
    );
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->load_settings();
        $this->init_server_configs();
        $this->init_caching();
    }
    
    /**
     * Initialize caching for API responses
     */
    private function init_caching() {
        // Schedule cleanup of expired server health checks
        if (!wp_next_scheduled('talkgenai_api_cache_cleanup')) {
            wp_schedule_event(time(), 'hourly', 'talkgenai_api_cache_cleanup');
        }
        
        add_action('talkgenai_api_cache_cleanup', [$this, 'cleanup_api_cache']);
    }
    
    /**
     * Clean up API cache
     */
    public function cleanup_api_cache() {
        // Clean up old server health transients
        delete_transient('talkgenai_server_health');
        delete_transient('talkgenai_server_stats');
        
        // Debug logging removed for WordPress.org submission
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log('TalkGenAI: API cache cleanup completed');
        // }
    }
    
    /**
     * Load settings with defaults
     */
    private function load_settings() {
        $saved_settings = get_option('talkgenai_settings', array());
        
        // Merge with defaults to ensure all keys exist
        $this->settings = array_merge($this->default_settings, $saved_settings);
        
        // If no settings exist in database, save defaults
        if (empty($saved_settings)) {
            update_option('talkgenai_settings', $this->settings);
        }
    }
    
    /**
     * Initialize server configurations
     */
    private function init_server_configs() {
        $this->server_configs = array(
            'local' => array(
                'url' => $this->settings['local_server_url'],
                'timeout' => 120,
                'verify_ssl' => false,
                'api_key' => $this->settings['remote_api_key']
            ),
            'remote' => array(
                'url' => $this->settings['remote_server_url'],
                'timeout' => 120,
                'verify_ssl' => true,
                'api_key' => $this->settings['remote_api_key']
            )
        );
    }
    
    /**
     * Get current server configuration
     */
    private function get_server_config() {
        $mode = $this->settings['server_mode'];
        
        if (!isset($this->server_configs[$mode])) {
            $mode = 'local'; // Fallback to local
        }
        
        $config = $this->server_configs[$mode];
        
        // Validate configuration
        if (empty($config['url'])) {
            return new WP_Error('no_server_url', 'Server URL not configured');
        }
        
        return $config;
    }
    
    /**
     * Generate new app via server API
     */
    public function generate_app($description, $current_spec = null) {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }
        
        $endpoint = '/api/generate-app';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        // Prepare request data
        $request_data = array(
            'description' => sanitize_textarea_field($description),
            'ai_provider' => 'anthropic'  // Default AI provider for generation
        );
        
        if ($current_spec) {
            $request_data['current_spec'] = $current_spec;
        }
        
        // Make API request
        $start_time = microtime(true);
        $response = $this->make_request('POST', $url, $request_data, $config);
        $response_time = microtime(true) - $start_time;
        
        if (is_wp_error($response)) {
            $this->log_api_call($endpoint, $response_time, false, $response->get_error_message());
            return $response;
        }
        
        // Validate and parse response
        $data = $this->parse_response($response);
        if (is_wp_error($data)) {
            $this->log_api_call($endpoint, $response_time, false, $data->get_error_message());
            return $data;
        }
        
        // Add response time to data
        $data['server_response_time'] = $response_time;
        
        // Debug logging removed for WordPress.org submission
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log('TalkGenAI API Response keys: ' . print_r(array_keys($data), true));
        //     error_log('TalkGenAI API Response json_spec exists: ' . (isset($data['json_spec']) ? 'YES' : 'NO'));
        //     if (isset($data['json_spec'])) {
        //         error_log('TalkGenAI API Response json_spec type: ' . gettype($data['json_spec']));
        //         error_log('TalkGenAI API Response json_spec preview: ' . substr(print_r($data['json_spec'], true), 0, 200));
        //     }
        //     error_log("TalkGenAI: App generated successfully in {$response_time}s");
        // }
        
        $this->log_api_call($endpoint, $response_time, true);
        
        return $data;
    }
    
    /**
     * Modify existing app via server API
     */
    public function modify_app($description, $current_spec) {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }
        
        $endpoint = '/api/generate-app';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        // Prepare request data for modification
        $request_data = array(
            'description' => sanitize_textarea_field($description),
            'current_spec' => $current_spec,
            'ai_provider' => 'anthropic'  // Default AI provider for modification
        );
        
        // Backend requires appClass and appType as top-level parameters for modifications
        // Extract from current_spec if available
        if (is_array($current_spec)) {
            if (isset($current_spec['appClass'])) {
                $request_data['appClass'] = sanitize_text_field($current_spec['appClass']);
            }
            if (isset($current_spec['appType'])) {
                $request_data['appType'] = sanitize_text_field($current_spec['appType']);
            }
        }
        
        // Make API request
        $start_time = microtime(true);
        $response = $this->make_request('POST', $url, $request_data, $config);
        $response_time = microtime(true) - $start_time;
        
        if (is_wp_error($response)) {
            $this->log_api_call($endpoint, $response_time, false, $response->get_error_message());
            return $response;
        }
        
        // Validate and parse response
        $data = $this->parse_response($response);
        if (is_wp_error($data)) {
            $this->log_api_call($endpoint, $response_time, false, $data->get_error_message());
            return $data;
        }
        
        // Add response time to data
        $data['server_response_time'] = $response_time;
        
        $this->log_api_call($endpoint, $response_time, true);
        
        // Debug logging removed for WordPress.org submission
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log("TalkGenAI: App modified successfully in {$response_time}s");
        // }
        
        return $data;
    }
    
    /**
     * Generate article for an app via server API
     */
    public function generate_article($app_id, $app_title, $app_description, $app_spec = null, $article_length = 'medium', $additional_instructions = '', $app_url = '', $internal_link_candidates = array()) {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }
        
        $endpoint = '/api/generate-article';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        // Prepare request data
        $request_data = array(
            'app_id' => intval($app_id),
            'app_title' => sanitize_text_field($app_title),
            'app_description' => sanitize_textarea_field($app_description),
            'article_length' => sanitize_text_field($article_length),
            'additional_instructions' => sanitize_textarea_field($additional_instructions),
            'user_id' => get_current_user_id(),
            'ai_provider' => 'anthropic'  // Default AI provider for article generation
        );

        // Optional: app URL (used for schema generation / internal links context)
        if (!empty($app_url)) {
            $request_data['app_url'] = esc_url_raw($app_url);
        }

        // Optional: internal link candidates (WordPress posts/pages)
        if (is_array($internal_link_candidates) && !empty($internal_link_candidates)) {
            // Best-effort sanitize
            $sanitized_candidates = array();
            foreach ($internal_link_candidates as $c) {
                if (!is_array($c)) { continue; }
                $u = isset($c['url']) ? esc_url_raw($c['url']) : '';
                if (empty($u)) { continue; }
                $sanitized_candidates[] = array(
                    'title' => isset($c['title']) ? sanitize_text_field($c['title']) : '',
                    'url' => $u,
                    'type' => isset($c['type']) ? sanitize_text_field($c['type']) : '',
                    'excerpt' => isset($c['excerpt']) ? sanitize_textarea_field($c['excerpt']) : ''
                );
            }
            if (!empty($sanitized_candidates)) {
                $request_data['internal_link_candidates'] = $sanitized_candidates;
            }
        }
        
        if ($app_spec) {
            $request_data['app_spec'] = $app_spec;
        }
        
        // Make API request
        $start_time = microtime(true);
        $response = $this->make_request('POST', $url, $request_data, $config);
        $response_time = microtime(true) - $start_time;
        
        if (is_wp_error($response)) {
            $this->log_api_call($endpoint, $response_time, false, $response->get_error_message());
            return $response;
        }
        
        // Validate and parse response
        $data = $this->parse_response($response);
        if (is_wp_error($data)) {
            $this->log_api_call($endpoint, $response_time, false, $data->get_error_message());
            return $data;
        }
        
        // Add response time to data
        $data['server_response_time'] = $response_time;
        
        // Debug logging removed for WordPress.org submission
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log('TalkGenAI Article API Response keys: ' . print_r(array_keys($data), true));
        //     error_log('TalkGenAI Article API Response success: ' . (isset($data['success']) ? ($data['success'] ? 'YES' : 'NO') : 'NOT SET'));
        //     if (isset($data['article'])) {
        //         error_log('TalkGenAI Article API Response article keys: ' . print_r(array_keys($data['article']), true));
        //         error_log('TalkGenAI Article API Response word count: ' . (isset($data['article']['word_count']) ? $data['article']['word_count'] : 'NOT SET'));
        //     }
        //     error_log("TalkGenAI: Article generated successfully in {$response_time}s");
        // }
        
        $this->log_api_call($endpoint, $response_time, true);
        
        return $data;
    }
    
    /**
     * Get writing styles (brand voices) for the current API key, filtered by site domain.
     *
     * @param string $domain Site domain to filter by (e.g. "example.com"). Voices with no domain are always included.
     * @return array|WP_Error Parsed API response or WP_Error on failure.
     */
    public function get_writing_styles($domain = '') {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }

        $endpoint = '/api/plugin/styles';
        $url = rtrim($config['url'], '/') . $endpoint;
        if (!empty($domain)) {
            $url .= '?' . http_build_query(array('domain' => $domain));
        }

        $start_time = microtime(true);
        $response = $this->make_request('GET', $url, null, $config);
        $response_time = microtime(true) - $start_time;

        if (is_wp_error($response)) {
            $this->log_api_call($endpoint, $response_time, false, $response->get_error_message());
            return $response;
        }

        $data = $this->parse_response($response);
        if (is_wp_error($data)) {
            $this->log_api_call($endpoint, $response_time, false, $data->get_error_message());
            return $data;
        }

        $this->log_api_call($endpoint, $response_time, true);
        return $data;
    }

    /**
     * Analyze website and get app ideas via server API
     */
    public function analyze_website($website_url, $description) {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }
        
        $endpoint = '/api/analyze-website';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        // Prepare request data
        $request_data = array(
            'user_id' => get_current_user_id()
        );
        
        // Only include non-empty values
        if (!empty($website_url)) {
            $request_data['website_url'] = esc_url_raw($website_url);
        }
        
        if (!empty($description)) {
            $request_data['description'] = sanitize_textarea_field($description);
        }
        
        // Make API request
        $start_time = microtime(true);
        $response = $this->make_request('POST', $url, $request_data, $config);
        $response_time = microtime(true) - $start_time;
        
        if (is_wp_error($response)) {
            $this->log_api_call($endpoint, $response_time, false, $response->get_error_message());
            return $response;
        }
        
        // Validate and parse response
        $data = $this->parse_response($response);
        if (is_wp_error($data)) {
            $this->log_api_call($endpoint, $response_time, false, $data->get_error_message());
            return $data;
        }
        
        // Add response time to data
        $data['server_response_time'] = $response_time;
        
        $this->log_api_call($endpoint, $response_time, true);
        
        // Debug logging removed for WordPress.org submission
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log("TalkGenAI: Website analyzed successfully in {$response_time}s");
        // }
        
        return $data;
    }
    
    /**
     * Test server connection (with caching for production)
     */
    public function test_connection($force_check = false) {
        // Check cache first (unless forced)
        if (!$force_check) {
            $cached_result = get_transient('talkgenai_server_health');
            if ($cached_result !== false) {
                return $cached_result;
            }
        }
        
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }
        
        $endpoint = '/health';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        $start_time = microtime(true);
        $response = $this->make_request('GET', $url, null, $config);
        $response_time = microtime(true) - $start_time;
        
        if (is_wp_error($response)) {
            $this->log_api_call($endpoint, $response_time, false, $response->get_error_message());
            $result = array(
                'success' => false,
                'message' => $response->get_error_message(),
                'response_time' => $response_time,
                'timestamp' => time()
            );
            
            // Cache failed results for shorter duration
            set_transient('talkgenai_server_health', $result, 2 * MINUTE_IN_SECONDS);
            return $result;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        
        if ($response_code === 200) {
            // Some environments return JSON as an escaped string; parse defensively
            $data = json_decode($body, true);
            if (json_last_error() !== JSON_ERROR_NONE && is_string($body)) {
                $txt = trim($body);
                if ((substr($txt,0,1)==='"' && substr($txt,-1)==='"') || (substr($txt,0,1)==="'" && substr($txt,-1)==="'")) {
                    $txt = substr($txt,1,-1);
                }
                $txt = str_replace('\\"','"', str_replace('\\\\','\\', $txt));
                $data = json_decode($txt, true);
            }
            $this->log_api_call($endpoint, $response_time, true);
            
            $result = array(
                'success' => true,
                'message' => 'Connection successful',
                'response_time' => $response_time,
                'server_info' => $data,
                'timestamp' => time()
            );
            
            // Cache successful results for longer duration
            set_transient('talkgenai_server_health', $result, 5 * MINUTE_IN_SECONDS);
            return $result;
        } else {
            $this->log_api_call($endpoint, $response_time, false, "HTTP {$response_code}");
            $result = array(
                'success' => false,
                'message' => "Server returned HTTP {$response_code}",
                'response_time' => $response_time,
                'timestamp' => time()
            );
            
            // Cache failed results for shorter duration
            set_transient('talkgenai_server_health', $result, 2 * MINUTE_IN_SECONDS);
            return $result;
        }
    }
    
    /**
     * Get server statistics
     */
    public function get_server_stats() {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }
        
        $endpoint = '/api/stats';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        $response = $this->make_request('GET', $url, null, $config);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        return $this->parse_response($response);
    }
    
    /**
     * Get server cost statistics (admin only)
     */
    public function get_cost_stats() {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return $config;
        }
        
        $endpoint = '/api/cost-stats';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        $response = $this->make_request('GET', $url, null, $config);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        return $this->parse_response($response);
    }
    
    /**
     * Make HTTP request to server
     */
    private function make_request($method, $url, $data = null, $config = null) {
        if (!$config) {
            $config = $this->get_server_config();
            if (is_wp_error($config)) {
                return $config;
            }
        }
        
        // Prepare request arguments
        $args = array(
            'method' => $method,
            'timeout' => $config['timeout'],
            'sslverify' => $config['verify_ssl'],
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'TalkGenAI-WordPress-Plugin/' . TALKGENAI_VERSION
            )
        );
        
        // Add API key if configured
        if (!empty($config['api_key'])) {
            $args['headers']['Authorization'] = 'Bearer ' . $config['api_key'];
        }
        
        // Add request body for POST requests
        if ($method === 'POST' && $data) {
            $args['body'] = wp_json_encode($data);
        }
        
        // Make request
        $response = wp_remote_request($url, $args);
        
        // Check for WordPress HTTP errors
        if (is_wp_error($response)) {
            // Debug logging removed for WordPress.org submission
            // if (defined('WP_DEBUG') && WP_DEBUG) {
            //     error_log("TalkGenAI API Error: " . $response->get_error_message());
            // }
            return $response;
        }
        
        return $response;
    }
    
    /**
     * Parse and validate API response
     */
    private function parse_response($response) {
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        
        // Check response code
        if ($response_code !== 200) {
            // Special handling for 400 errors with structured responses (e.g., unsupported app types)
            if ($response_code === 400 && !empty($body)) {
                $error_data = json_decode($body, true);
                // If it's a structured error with ai_message, return the data instead of WP_Error
                if (isset($error_data['error']) && isset($error_data['ai_message'])) {
                    // Return the full error data so it can be used in the UI
                    return $error_data;
                }
            }
            
            // Special handling for 402/403 errors (payment/credits required or premium features)
            if (($response_code === 402 || $response_code === 403) && !empty($body)) {
                $error_data = json_decode($body, true);
                // Check if this is an insufficient credits error OR premium feature error
                if (isset($error_data['detail']) && is_array($error_data['detail'])) {
                    $error_code = $error_data['detail']['code'] ?? '';
                    
                    if ($error_code === 'insufficient_credits') {
                        // Return user-friendly error message
                        $user_message = isset($error_data['detail']['message']) 
                            ? $error_data['detail']['message'] 
                            : 'You don\'t have enough credits to generate content. Please upgrade your plan.';
                        return new WP_Error('insufficient_credits', $user_message);
                    } elseif ($error_code === 'premium_feature') {
                        // Return structured error data for premium feature (handled in frontend)
                        // Don't convert to WP_Error - let it pass through so JS can handle it
                        return new WP_Error('premium_feature', '', $error_data['detail']);
                    }
                }
            }
            
            $error_message = "Server returned HTTP {$response_code}";
            $error_code_str = 'api_error';
            
            // Try to get error details from response body
            if (!empty($body)) {
                $error_data = json_decode($body, true);
                
                // FastAPI wraps errors in a 'detail' field
                if (isset($error_data['detail'])) {
                    if (is_string($error_data['detail'])) {
                        // Simple string error
                        $error_message = $error_data['detail'];
                        
                        // Check if this is an authorization error (401)
                        if ($response_code === 401 || strpos($error_message, 'Authorization') !== false) {
                            $error_code_str = 'unauthorized';
                        }
                    } elseif (is_array($error_data['detail']) && isset($error_data['detail']['message'])) {
                        // Structured error with message field
                        $error_message = $error_data['detail']['message'];
                        
                        // Get error code if available
                        if (isset($error_data['detail']['code'])) {
                            $error_code_str = $error_data['detail']['code'];
                        }
                    }
                } elseif (isset($error_data['message'])) {
                    // Direct message field (older format)
                    $error_message = $error_data['message'];
                }
            }
            
            return new WP_Error($error_code_str, $error_message);
        }
        
        // Check if response is empty
        if (empty($body)) {
            return new WP_Error('empty_response', 'Empty response from server');
        }
        
        // Parse JSON
        $data = json_decode($body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new WP_Error('invalid_json', 'Invalid JSON response from server');
        }
        
        // Check for API errors in response
        // But allow structured errors with ai_message (like unsupported app types)
        if (isset($data['error']) && !isset($data['ai_message'])) {
            return new WP_Error('api_error', $data['error']);
        }
        
        return $data;
    }
    
    /**
     * Log API calls for monitoring
     */
    private function log_api_call($endpoint, $response_time, $success, $error_message = null) {
        // Usage logging disabled: usage table removed. No-op to avoid DB references.
        return;
    }
    
    /**
     * Update server settings
     */
    public function update_settings($new_settings) {
        $current_settings = get_option('talkgenai_settings', array());
        
        // Validate and sanitize settings
        $validated_settings = $this->validate_settings($new_settings);
        if (is_wp_error($validated_settings)) {
            return $validated_settings;
        }
        
        // Merge with current settings
        $updated_settings = array_merge($current_settings, $validated_settings);
        
        // Update option
        $result = update_option('talkgenai_settings', $updated_settings);
        
        if ($result) {
            // Refresh internal settings
            $this->load_settings();
            $this->init_server_configs();
            
            // Debug logging removed for WordPress.org submission
            // if (defined('WP_DEBUG') && WP_DEBUG) {
            //     error_log('TalkGenAI: Settings updated successfully');
            // }
            
            return true;
        } else {
            return new WP_Error('update_failed', 'Failed to update settings');
        }
    }
    
    /**
     * Validate settings data
     */
    public function validate_settings($settings) {
        $validated = array();
        
        // Server mode
        if (isset($settings['server_mode'])) {
            $mode = sanitize_text_field($settings['server_mode']);
            if (in_array($mode, array('local', 'remote'))) {
                $validated['server_mode'] = $mode;
            }
        }
        
        // Local server URL
        if (isset($settings['local_server_url'])) {
            $url = esc_url_raw($settings['local_server_url']);
            if (!empty($url)) {
                $validated['local_server_url'] = $url;
            }
        }
        
        // Remote server URL
        if (isset($settings['remote_server_url'])) {
            $url = esc_url_raw($settings['remote_server_url']);
            $validated['remote_server_url'] = $url; // Can be empty
        }
        
        // Remote API key
        if (isset($settings['remote_api_key'])) {
            $api_key = sanitize_text_field($settings['remote_api_key']);
            $validated['remote_api_key'] = $api_key; // Can be empty
        }
        
        // Max requests per hour
        if (isset($settings['max_requests_per_hour'])) {
            $max_requests = intval($settings['max_requests_per_hour']);
            if ($max_requests > 0 && $max_requests <= 1000) {
                $validated['max_requests_per_hour'] = $max_requests;
            }
        }
        
        // Debug logging
        if (isset($settings['enable_debug_logging'])) {
            $validated['enable_debug_logging'] = (bool) $settings['enable_debug_logging'];
        }
        
        return $validated;
    }
    
    /**
     * Get current settings
     */
    public function get_settings() {
        return $this->settings;
    }
    
    /**
     * Get default settings
     */
    public function get_default_settings() {
        return $this->default_settings;
    }
    
    /**
     * Check if server is configured
     */
    public function is_server_configured() {
        $config = $this->get_server_config();
        
        if (is_wp_error($config)) {
            return false;
        }
        
        // For remote server, also check if API key is set
        if ($this->settings['server_mode'] === 'remote') {
            return !empty($config['api_key']);
        }
        
        return true;
    }
    
    /**
     * Get server status with caching
     */
    public function get_server_status($force_check = false) {
        $cache_key = 'talkgenai_server_status';
        
        if (!$force_check) {
            $cached_status = get_transient($cache_key);
            if ($cached_status !== false) {
                return $cached_status;
            }
        }
        
        $status = $this->test_connection();
        
        // Cache for 5 minutes
        set_transient($cache_key, $status, 5 * MINUTE_IN_SECONDS);
        
        return $status;
    }
    
    /**
     * Auto-detect local server
     */
    public function auto_detect_local_server() {
        $possible_urls = array(
            'http://localhost:8000',
            'http://127.0.0.1:8000',
            'http://localhost:8080',
            'http://127.0.0.1:8080'
        );
        
        foreach ($possible_urls as $url) {
            $config = array(
                'url' => $url,
                'timeout' => 5,
                'verify_ssl' => false,
                'api_key' => null
            );
            
            $test_url = rtrim($url, '/') . '/health';
            $response = $this->make_request('GET', $test_url, null, $config);
            
            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                return $url;
            }
        }
        
        return false;
    }
    
    /**
     * Delete app and notify service to decrement counter
     * 
     * @param int $app_id App ID from WordPress database
     * @return array Response from service
     */
    public function delete_app($app_id) {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return array('success' => false, 'error' => 'Server not configured');
        }
        
        $endpoint = '/api/apps/' . intval($app_id);
        $url = rtrim($config['url'], '/') . $endpoint;
        
        // Make DELETE request to service
        $response = $this->make_request('DELETE', $url, null, $config);
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'error' => $response->get_error_message()
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return array(
                'success' => false,
                'error' => 'Invalid JSON response from server'
            );
        }
        
        return $data;
    }
    
    /**
     * Notify backend that an app was saved
     * This increments the active_apps counter for new apps
     * 
     * @param string $app_id App identifier
     * @param bool $is_modification Whether this is modifying an existing app
     * @return array Response with updated user stats
     */
    public function notify_app_saved($app_id, $is_modification = false) {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            // Debug logging removed for WordPress.org submission
            // error_log('TalkGenAI: Cannot notify backend - server not configured');
            return array('success' => false, 'error' => 'Server not configured');
        }
        
        $endpoint = '/api/apps/save';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        $body = array(
            'app_id' => (string)$app_id,
            'is_modification' => (bool)$is_modification
        );
        
        // Make POST request
        $response = $this->make_request('POST', $url, $body, $config);
        
        if (is_wp_error($response)) {
            // Debug logging removed for WordPress.org submission
            // error_log('TalkGenAI: Failed to notify backend of save: ' . $response->get_error_message());
            return array(
                'success' => false,
                'error' => $response->get_error_message()
            );
        }
        
        $response_body = wp_remote_retrieve_body($response);
        $data = json_decode($response_body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            // Debug logging removed for WordPress.org submission
            // error_log('TalkGenAI: Invalid JSON response from save notification');
            return array(
                'success' => false,
                'error' => 'Invalid JSON response from server'
            );
        }
        
        // Debug logging removed for WordPress.org submission
        // if (!empty($data['success']) && !empty($data['stats'])) {
        //     $stats = $data['stats'];
        //     error_log(sprintf(
        //         'TalkGenAI: App saved notification successful - Active apps: %d/%d, Can create new: %s',
        //         $stats['active_apps'] ?? 0,
        //         $stats['app_limit'] ?? 5,
        //         ($stats['can_create_new'] ?? false) ? 'yes' : 'no'
        //     ));
        // }
        
        return $data;
    }
    
    /**
     * Get user stats including app counts and limits
     * 
     * @return array User stats with app limits
     */
    public function get_user_stats() {
        $config = $this->get_server_config();
        if (is_wp_error($config)) {
            return array('success' => false, 'error' => 'Server not configured');
        }
        
        // Check cache first (5 minute cache)
        $cache_key = 'talkgenai_user_stats_' . md5($config['api_key']);
        $cached = get_transient($cache_key);
        
        if ($cached !== false) {
            return $cached;
        }
        
        $endpoint = '/api/user/stats';
        $url = rtrim($config['url'], '/') . $endpoint;
        
        // Make GET request
        $response = $this->make_request('GET', $url, null, $config);
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'error' => $response->get_error_message()
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return array(
                'success' => false,
                'error' => 'Invalid JSON response from server'
            );
        }
        
        // Cache for 5 minutes
        if (isset($data['success']) && $data['success']) {
            set_transient($cache_key, $data, 5 * MINUTE_IN_SECONDS);
        }
        
        return $data;
    }
    
    /**
     * Clear user stats cache (call after create/delete operations)
     */
    public function clear_stats_cache() {
        $config = $this->get_server_config();
        if (!is_wp_error($config) && !empty($config['api_key'])) {
            $cache_key = 'talkgenai_user_stats_' . md5($config['api_key']);
            delete_transient($cache_key);
        }
    }
}
