<?php
if (!defined('ABSPATH')) exit;

// Load the routes configuration
require_once __DIR__ . '/Routes.php';

/**
 * API Client for handling HTTP requests to Blogibot API endpoints
 */
class Blog82AI_API_Client
{
    /**
     * Default request timeout in seconds
     */
    const DEFAULT_TIMEOUT = 120; // Increased from 30 to 120 seconds for blog generation
    
    /**
     * Default user agent
     */
    const USER_AGENT = 'Blogibot-WordPress-Plugin/1.0';
    
    /**
     * Determine if SSL verification should be enabled
     * Disabled for local development to avoid self-signed certificate issues
     */
    private static function should_verify_ssl()
    {
        // Get environment info
        $env_info = Blog82AI_API_Routes::get_environment_info();
        
        // Disable SSL verification for local/development environments
        if ($env_info['is_local']) {
            return false;
        }
        
        // Enable SSL verification for production
        return true;
    }
    
    /**
     * Make an API request
     */
    public static function request($endpoint_key, $payload = [], $options = [])
    {
        try {
            // Get endpoint configuration
            $config = Blog82AI_API_Routes::get_endpoint_config($endpoint_key);
            $url = Blog82AI_API_Routes::get_endpoint_url($endpoint_key);
            
            // Validate payload
            $validation = Blog82AI_API_Routes::validate_payload($endpoint_key, $payload);
            if (!$validation['valid']) {
                return [
                    'success' => false,
                    'error' => 'Invalid payload: ' . implode(', ', $validation['errors'])
                ];
            }
            
            // Prepare request arguments
            $args = wp_parse_args($options, [
                'method' => $config['method'],
                'timeout' => self::DEFAULT_TIMEOUT,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'User-Agent' => self::USER_AGENT,
                    'Accept' => 'application/json'
                ],
                'body' => $config['method'] === 'POST' ? json_encode($payload) : null,
                // Disable SSL verification for local development
                'sslverify' => self::should_verify_ssl()
            ]);
            
            // For GET requests, add payload as query parameters
            if ($config['method'] === 'GET' && !empty($payload)) {
                $url = add_query_arg($payload, $url);
            }
            
            // Log the request (only in debug mode)
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("Blogibot API Request: {$config['method']} {$url}");
                error_log("Blogibot SSL Verify: " . (self::should_verify_ssl() ? 'enabled' : 'disabled'));
                if ($config['method'] === 'POST') {
                    error_log("Blogibot API Payload: " . json_encode($payload, JSON_PRETTY_PRINT));
                }
                error_log("Blogibot Request Headers: " . json_encode($args['headers'], JSON_PRETTY_PRINT));
            }
            
            // Make the request
            $response = wp_remote_request($url, $args);
            
            // Handle request errors
            if (is_wp_error($response)) {
                $error_message = $response->get_error_message();
                $error_code = $response->get_error_code();
                error_log("Blogibot API WP Error [{$error_code}]: {$error_message}");
                
                // Special handling for SSL certificate errors
                if (strpos($error_message, 'SSL certificate') !== false || strpos($error_message, 'cURL error 60') !== false) {
                    error_log("Blogibot: SSL certificate error detected, SSL verification is " . (self::should_verify_ssl() ? 'enabled' : 'disabled'));
                    
                    if (self::should_verify_ssl()) {
                        error_log("Blogibot: Consider disabling SSL verification for local development");
                    }
                }
                
                // If this is a 404 or endpoint not found, throw exception for fallback handling
                if (strpos($error_message, '404') !== false || strpos($error_message, 'not found') !== false) {
                    throw new Exception("API endpoint not found: {$error_message}");
                }
                
                return [
                    'success' => false,
                    'error' => 'Request failed: ' . $error_message,
                    'error_code' => $error_code
                ];
            }
            
            // Get response data
            $status_code = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);
            
            // Log the response (only in debug mode)
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("Blogibot API Response Code: {$status_code}");
                error_log("Blogibot API Response Body: " . $body);
            }
            
            // Parse JSON response
            $data = json_decode($body, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return [
                    'success' => false,
                    'error' => 'Invalid JSON response: ' . json_last_error_msg()
                ];
            }
            
            // Check HTTP status code
            if ($status_code < 200 || $status_code >= 300) {
                return [
                    'success' => false,
                    'error' => 'HTTP ' . $status_code . ': ' . ($data['message'] ?? 'Unknown error'),
                    'status_code' => $status_code,
                    'data' => $data
                ];
            }
            
            // Return successful response
            return [
                'success' => true,
                'data' => $data,
                'status_code' => $status_code
            ];
            
        } catch (Exception $e) {
            error_log("Blogibot API Exception: " . $e->getMessage());
            return [
                'success' => false,
                'error' => 'Exception: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Register a license
     */
    public static function register_license($license_key, $domain)
    {
        try {
            $result = self::request('license_register', [
                'license_key' => $license_key,
                'domain' => $domain
            ]);
            
            return $result;
        } catch (Exception $e) {
            // If endpoint doesn't exist yet, log and return mock success for development
            error_log('Blogibot: Register endpoint not available, using mock response');
            return [
                'success' => true,
                'message' => 'License registered successfully (mock response - API endpoint not yet implemented)',
                'mock' => true,
                'data' => [
                    'license_key' => $license_key,
                    'domain' => $domain,
                    'status' => 'active'
                ]
            ];
        }
    }
    
    /**
     * Deregister a license
     */
    public static function deregister_license($license_key, $domain)
    {
        return self::request('license_deregister', [
            'license_key' => $license_key,
            'domain' => $domain
        ]);
    }
    
    /**
     * Remove license registration from domain
     */
    public static function remove_license_registration($license_key, $domain)
    {
        // For development/testing, if the endpoint doesn't exist, return a mock success
        try {
            $result = self::request('license_remove_registration', [
                'license_key' => $license_key,
                'domain' => $domain
            ]);
            
            return $result;
        } catch (Exception $e) {
            // If endpoint doesn't exist yet, log and return mock success for development
            error_log('Blogibot: Remove registration endpoint not available, using mock response');
            return [
                'success' => true,
                'message' => 'License removed successfully (mock response - API endpoint not yet implemented)',
                'mock' => true
            ];
        }
    }
    
    /**
     * Validate a license
     */
    public static function validate_license($license_key, $domain)
    {
        return self::request('license_validate', [
            'license_key' => $license_key,
            'domain' => $domain
        ]);
    }
    
    /**
     * Generate simple blog post (for scheduled posts and fetch now)
     */
    public static function generate_blog($payload)
    {
        error_log('Blogibot: Attempting to call simple blog generation API');
        error_log('Blogibot: Payload: ' . json_encode($payload));
        
        try {
            $result = self::request('blog_generate', $payload);
            error_log('Blogibot: Simple blog API call successful, result: ' . json_encode($result));
            
            // Handle Laravel API response structure
            if (isset($result['data']) && isset($result['data']['status']) && $result['data']['status'] === 'success') {
                error_log('Blogibot: Detected Laravel API response structure');
                // Laravel returns the blog data directly in the data field
                return $result;
            } else {
                error_log('Blogibot: Standard API response structure');
                return $result;
            }
            
        } catch (Exception $e) {
            error_log('Blogibot: Simple blog API call failed with error: ' . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * Generate advanced blog post
     */
    public static function generate_blog_advanced($payload)
    {
        error_log('Blogibot: Attempting to call real API for blog generation');
        error_log('Blogibot: Payload: ' . json_encode($payload));
        
        try {
            $result = self::request('blog_generate_advanced', $payload);
            error_log('Blogibot: API call successful, result: ' . json_encode($result));
            return $result;
        } catch (Exception $e) {
            error_log('Blogibot: API call failed with error: ' . $e->getMessage());
            error_log('Blogibot: Error trace: ' . $e->getTraceAsString());
            
            // Instead of automatically falling back to mock, throw the error
            throw $e;
            
            // Only use mock response if explicitly requested
            /*
            error_log('Blogibot: Generate blog advanced endpoint not available, using mock response');
            
            // Calculate estimated values
            $word_count = self::estimate_word_count($payload['blog82ai_length'] ?? 'Medium (500-800 words)');
            $reading_time = ceil($word_count / 200) . ' min read';
            
            return [
                'success' => true,
                'message' => 'Blog generated successfully (mock response)',
                'data' => [
                    'title' => $payload['blog82ai_title'] ?? 'AI Generated Blog Post',
                    'content' => self::generate_mock_content($payload),
                    'meta_title' => $payload['blog82ai_meta_title'] ?? ($payload['blog82ai_title'] ?? 'AI Generated Blog Post'),
                    'meta_description' => $payload['blog82ai_meta_description'] ?? 'This is a mock blog post generated for development testing.',
                    'keyphrase' => $payload['blog82ai_keyphrase'] ?? 'blog post',
                    'category_id' => $payload['blog82ai_category'],
                    'language' => $payload['blog82ai_language'],
                    'style' => $payload['blog82ai_style'],
                    'featured_image' => $payload['blog82ai_images'] ? 'https://via.placeholder.com/800x400/0073aa/ffffff?text=Featured+Image' : null,
                    'images' => $payload['blog82ai_images'] ? [
                        'https://via.placeholder.com/600x300/0073aa/ffffff?text=Content+Image+1',
                        'https://via.placeholder.com/600x300/28a745/ffffff?text=Content+Image+2'
                    ] : []
                ],
                'word_count' => $word_count,
                'reading_time' => $reading_time,
                'seo_score' => rand(75, 95),
                'mock' => true
            ];
            */
        }
    }
    
    /**
     * Estimate word count from length selection
     */
    private static function estimate_word_count($length)
    {
        switch ($length) {
            case 'Short (200-400 words)':
                return rand(250, 350);
            case 'Medium (500-800 words)':
                return rand(600, 750);
            case 'Long (900-1500 words)':
                return rand(1100, 1400);
            default:
                return 600;
        }
    }
    
    /**
     * Generate mock content for development
     */
    private static function generate_mock_content($payload)
    {
        $style = $payload['blog82ai_style'] ?? 'Friendly';
        $language = $payload['blog82ai_language'] ?? 'English';
        $title = $payload['blog82ai_title'] ?? 'AI Generated Blog Post';
        
        $content = "<h2>Introduction</h2>\n\n";
        $content .= "<p>Welcome to this comprehensive guide about {$title}. In this {$style} article, we'll explore the key aspects and provide valuable insights in {$language}.</p>\n\n";
        
        $content .= "<h2>Main Content</h2>\n\n";
        $content .= "<p>This section contains the main content of your blog post. The AI has generated this content based on your specifications:</p>\n\n";
        $content .= "<ul>\n";
        $content .= "<li><strong>Style:</strong> {$style}</li>\n";
        $content .= "<li><strong>Language:</strong> {$language}</li>\n";
        $content .= "<li><strong>Length:</strong> " . ($payload['blog82ai_length'] ?? 'Medium') . "</li>\n";
        $content .= "</ul>\n\n";
        
        if ($payload['blog82ai_images'] ?? false) {
            $content .= "<p><img src=\"https://via.placeholder.com/600x300/0073aa/ffffff?text=Content+Image\" alt=\"Relevant content image\" /></p>\n\n";
        }
        
        $content .= "<h2>Key Points</h2>\n\n";
        $content .= "<p>Here are the most important takeaways from this article:</p>\n\n";
        $content .= "<ol>\n";
        $content .= "<li>Understanding the fundamentals is crucial for success</li>\n";
        $content .= "<li>Practical application leads to better results</li>\n";
        $content .= "<li>Continuous learning ensures long-term growth</li>\n";
        $content .= "</ol>\n\n";
        
        if ($payload['blog82ai_faq'] ?? false) {
            $content .= "<h2>Frequently Asked Questions</h2>\n\n";
            $content .= "<h3>What makes this approach effective?</h3>\n";
            $content .= "<p>This approach is effective because it combines proven strategies with innovative techniques.</p>\n\n";
            $content .= "<h3>How long does it take to see results?</h3>\n";
            $content .= "<p>Results can typically be seen within 2-4 weeks of consistent implementation.</p>\n\n";
        }
        
        if ($payload['blog82ai_conclusion'] ?? false) {
            $content .= "<h2>Conclusion</h2>\n\n";
            $content .= "<p>In conclusion, {$title} represents an important topic that deserves careful consideration. By following the guidelines outlined in this article, you'll be well-equipped to achieve your goals.</p>\n\n";
        }
        
        if ($payload['blog82ai_cta'] ?? false) {
            $content .= "<div class=\"cta-section\" style=\"background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;\">\n";
            $content .= "<h3>Ready to Get Started?</h3>\n";
            $content .= "<p>Take action today and implement these strategies in your own journey. <a href=\"#\" style=\"color: #0073aa; font-weight: bold;\">Contact us</a> to learn more about how we can help you succeed.</p>\n";
            $content .= "</div>\n\n";
        }
        
        return $content;
    }
    
    /**
     * Get license status
     */
    public static function get_license_status($license_key, $domain)
    {
        return self::request('license_status', [
            'license_key' => $license_key,
            'domain' => $domain
        ]);
    }
    
    /**
     * Test API connectivity
     */
    public static function test_connection()
    {
        try {
            $env_info = Blog82AI_API_Routes::get_environment_info();
            $base_url = $env_info['base_url'];
            
            // Try to ping the base URL with proper SSL handling
            $response = wp_remote_get($base_url, [
                'timeout' => 30, // Increased timeout for connection test
                'headers' => [
                    'User-Agent' => self::USER_AGENT
                ],
                'sslverify' => self::should_verify_ssl()
            ]);
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("Blogibot Connection Test: GET {$base_url}");
                error_log("Blogibot SSL Verify: " . (self::should_verify_ssl() ? 'enabled' : 'disabled'));
            }
            
            if (is_wp_error($response)) {
                $error_message = $response->get_error_message();
                error_log("Blogibot Connection Test Error: {$error_message}");
                
                return [
                    'success' => false,
                    'error' => $error_message,
                    'environment' => $env_info
                ];
            }
            
            $status_code = wp_remote_retrieve_response_code($response);
            
            return [
                'success' => $status_code < 400,
                'status_code' => $status_code,
                'environment' => $env_info,
                'message' => $status_code < 400 ? 'API connection successful' : 'API connection failed'
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage(),
                'environment' => Blog82AI_API_Routes::get_environment_info()
            ];
        }
    }
    
    /**
     * Get environment information for debugging
     */
    public static function get_debug_info()
    {
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            return null;
        }
        
        return [
            'environment' => Blog82AI_API_Routes::get_environment_info(),
            'endpoints' => Blog82AI_API_Routes::debug_list_all_endpoints(),
            'wordpress_version' => get_bloginfo('version'),
            'php_version' => PHP_VERSION,
            'plugin_version' => defined('BLOGIBOT_VERSION') ? BLOGIBOT_VERSION : '1.0.0'
        ];
    }
}
