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

/**
 * Central API Routes Configuration
 * Master reference for all API endpoints
 * 
 * Usage Examples:
 * - Get endpoint URL: Blog82AI_API_Routes::get_endpoint_url('blog_regenerate')
 * - Get endpoint config: Blog82AI_API_Routes::get_endpoint_config('blog_regenerate')
 * - Validate payload: Blog82AI_API_Routes::validate_payload('blog_regenerate', $payload)
 * - Get environment info: Blog82AI_API_Routes::get_environment_info()
 */
class Blog82AI_API_Routes
{
    /**
     * Get the base API URL based on environment
     */
    public static function get_base_url()
    {
        $env = defined('BLOGIBOT_API_ENV') ? BLOGIBOT_API_ENV : 'production';
        
        switch ($env) {
            case 'local':
            case 'development':
                return defined('BLOGIBOT_API_SANDBOX') ? BLOGIBOT_API_SANDBOX : 'https://licenseapp.test/api/';
            case 'production':
            default:
                return defined('BLOGIBOT_API_PRODUCTION') ? BLOGIBOT_API_PRODUCTION : 'https://myapps.wontonee.com/api/';
        }
    }
    
    /**
     * Get the full URL for a specific endpoint
     */
    public static function get_endpoint_url($endpoint_key)
    {
        $base_url = self::get_base_url();
        $endpoints = self::get_endpoints();
        
        if (!isset($endpoints[$endpoint_key])) {
            throw new InvalidArgumentException("Endpoint '{$endpoint_key}' not found");
        }
        
        return rtrim($base_url, '/') . $endpoints[$endpoint_key]['path'];
    }
    
    /**
     * Get endpoint configuration
     */
    public static function get_endpoint_config($endpoint_key)
    {
        $endpoints = self::get_endpoints();
        
        if (!isset($endpoints[$endpoint_key])) {
            throw new InvalidArgumentException("Endpoint '{$endpoint_key}' not found");
        }
        
        return $endpoints[$endpoint_key];
    }
    
    /**
     * Master list of all API endpoints
     * This serves as the central reference for every API URL
     */
    public static function get_endpoints()
    {
        return [
            // License Management Endpoints
            'license_register' => [
                'path' => '/register-license',
                'method' => 'POST',
                'description' => 'Register/activate a license key',
                'payload' => [
                    'license_key' => 'string (required) - The license key to register',
                    'domain' => 'string (required) - The domain to register the license for'
                ],
                'response' => [
                    'success' => 'boolean - Whether the registration was successful',
                    'message' => 'string - Success or error message',
                    'data' => 'object - License data if successful'
                ]
            ],
            
            'license_deregister' => [
                'path' => '/deregister-license',
                'method' => 'POST',
                'description' => 'Deregister/deactivate a license key',
                'payload' => [
                    'license_key' => 'string (required) - The license key to deregister',
                    'domain' => 'string (required) - The domain to deregister the license from'
                ],
                'response' => [
                    'success' => 'boolean - Whether the deregistration was successful',
                    'message' => 'string - Success or error message'
                ]
            ],
            
            'license_remove_registration' => [
                'path' => '/remove-license-registration',
                'method' => 'POST',
                'description' => 'Remove license registration from domain',
                'payload' => [
                    'license_key' => 'string (required) - The license key to remove',
                    'domain' => 'string (required) - The domain to remove the license from'
                ],
                'response' => [
                    'success' => 'boolean - Whether the removal was successful',
                    'message' => 'string - Success or error message',
                    'data' => 'object - Additional information if needed'
                ]
            ],
            
            'license_validate' => [
                'path' => '/validate-license',
                'method' => 'POST',
                'description' => 'Validate an existing license key',
                'payload' => [
                    'license_key' => 'string (required) - The license key to validate',
                    'domain' => 'string (required) - The domain to validate the license for'
                ],
                'response' => [
                    'valid' => 'boolean - Whether the license is valid',
                    'message' => 'string - Validation message',
                    'data' => 'object - License details if valid'
                ]
            ],
            
            'license_status' => [
                'path' => '/license-status',
                'method' => 'GET',
                'description' => 'Get the current status of a license',
                'payload' => [
                    'license_key' => 'string (required) - The license key to check',
                    'domain' => 'string (required) - The domain to check the license for'
                ],
                'response' => [
                    'status' => 'string - License status (active, expired, suspended, etc.)',
                    'expires_at' => 'string - License expiration date',
                    'data' => 'object - Additional license information'
                ]
            ],
            
            // Blog Generation Endpoints
            'blog_regenerate' => [
                'path' => '/regenerate-blog',
                'method' => 'POST',
                'description' => 'Regenerate blog title, content, or image using AI',
                'payload' => [
                    'api_key' => 'string (required) - Valid API key',
                    'domain' => 'string (required) - Domain for license validation',
                    'action' => 'string (required) - Action type: "title", "content", or "image"',
                    'title' => 'string (required) - Current blog title to regenerate from'
                ],
                'response' => [
                    'status' => 'string - Response status (success, error)',
                    'data' => 'object - Regenerated content data',
                    'title' => 'string - New title (if action=title)',
                    'meta_title' => 'string - SEO meta title',
                    'meta_description' => 'string - SEO meta description',
                    'focus_keywords' => 'string - Focus keywords',
                    'tags' => 'string - Generated tags',
                    'blog_content' => 'string - Full HTML blog content (if action=content)',
                    'focus_keyphrase' => 'string - Focus keyphrase',
                    'word_count' => 'integer - Content word count',
                    'yoast_meta' => 'object - Yoast SEO metadata',
                    'image' => 'object - Image data (if action=image)',
                    'url' => 'string - Image URL (if action=image)',
                    'description' => 'string - Image description (if action=image)',
                    'mime_type' => 'string - Image MIME type (if action=image)',
                    'filename' => 'string - Image filename (if action=image)',
                    'size' => 'integer - File size in bytes (if action=image)',
                    'is_temporary' => 'boolean - Whether image is temporary (if action=image)'
                ]
            ],
            
            'blog_generate' => [
                'path' => '/generate-blog',
                'method' => 'POST',
                'description' => 'Generate a new blog post using AI',
                'payload' => [
                    'license_key' => 'string (required) - Valid license key',
                    'topic' => 'string (required) - Blog topic or title',
                    'category' => 'string (optional) - Blog category',
                    'keywords' => 'array (optional) - Target keywords'
                ],
                'response' => [
                    'success' => 'boolean - Whether generation was successful',
                    'data' => 'object - Generated blog content'
                ]
            ],
            
            'blog_generate_advanced' => [
                'path' => '/generate-blog-advanced',
                'method' => 'POST',
                'description' => 'Generate an advanced blog post with full customization options',
                'payload' => [
                    'api_key' => 'string (required) - Valid API key',
                    'domain' => 'string (required) - Domain for license validation',
                    'blog82ai_category' => 'string (required) - WordPress category name for AI context',
                    'blog82ai_language' => 'string (required) - Language: English,Hindi,Spanish,French,German,Italian,Portuguese,Russian,Chinese,Japanese',
                    'blog82ai_length' => 'string (required) - Length: Short (200-400 words),Medium (500-800 words),Long (900-1500 words)',
                    'blog82ai_style' => 'string (required) - Style: Formal,Conversational,Technical,Friendly',
                    'blog82ai_title' => 'string (optional) - Custom title (max 200 chars)',
                    'blog82ai_keyphrase' => 'string (optional) - Target keyphrase (max 100 chars)',
                    'blog82ai_meta_title' => 'string (optional) - SEO meta title (max 60 chars)',
                    'blog82ai_meta_description' => 'string (optional) - SEO meta description (max 160 chars)',
                    'blog82ai_images' => 'boolean (optional) - Include AI-generated images',
                    'blog82ai_conclusion' => 'boolean (optional) - Include conclusion section',
                    'blog82ai_faq' => 'boolean (optional) - Include FAQ section',
                    'blog82ai_cta' => 'boolean (optional) - Include call-to-action'
                ],
                'response' => [
                    'success' => 'boolean - Whether generation was successful',
                    'data' => 'object - Generated blog content with preview data',
                    'word_count' => 'integer - Actual word count',
                    'reading_time' => 'string - Estimated reading time',
                    'seo_score' => 'integer - SEO optimization score (0-100)'
                ]
            ],
            
            'image_generate' => [
                'path' => '/generate-image',
                'method' => 'POST',
                'description' => 'Generate an AI image based on blog content or custom prompt',
                'payload' => [
                    'api_key' => 'string (required) - Valid API key',
                    'domain' => 'string (required) - Domain for license validation',
                    'image_description' => 'string (required) - Description for AI image generation',
                    'style' => 'string (optional) - Image style: photorealistic, artistic, cartoon, etc.',
                    'quality' => 'string (optional) - Image quality: high quality, standard, draft',
                    'aspect_ratio' => 'string (optional) - Aspect ratio: 16:9, 4:3, 1:1, 9:16',
                    'save_image' => 'boolean (optional) - Whether to save image on server',
                    'filename' => 'string (optional) - Custom filename for saved image'
                ],
                'response' => [
                    'status' => 'string - Generation status (success, error)',
                    'image' => 'object - Generated image data',
                    'description' => 'string - Image description used',
                    'mime_type' => 'string - Image MIME type',
                    'generated_at' => 'string - ISO timestamp of generation',
                    'model' => 'string - AI model used for generation',
                    'saved' => 'boolean - Whether image was saved',
                    'filename' => 'string - Final filename with timestamp',
                    'temp_path' => 'string - Temporary server path',
                    'url' => 'string - Direct URL to generated image',
                    'size' => 'integer - File size in bytes',
                    'expires_at' => 'string - Expiration timestamp for temp images',
                    'is_temporary' => 'boolean - Whether image is temporary'
                ]
            ],
            
            // Content Sync Endpoints
            'content_sync' => [
                'path' => '/sync-content',
                'method' => 'POST',
                'description' => 'Sync content data for analysis and fingerprinting',
                'payload' => [
                    'license_key' => 'string (required) - Valid license key',
                    'domain' => 'string (required) - Domain for license validation',
                    'posts' => 'array (required) - Array of post objects to sync'
                ],
                'response' => [
                    'status' => 'string - Sync status (success, error)',
                    'message' => 'string - Sync result message',
                    'results' => 'object - Detailed sync results with fingerprints'
                ]
            ],
            
            // Feed Management Endpoints (Future)
            'feed_sources' => [
                'path' => '/feed-sources',
                'method' => 'GET',
                'description' => 'Get available RSS feed sources',
                'payload' => [
                    'license_key' => 'string (required) - Valid license key',
                    'category' => 'string (optional) - Filter by category'
                ],
                'response' => [
                    'sources' => 'array - List of available feed sources'
                ]
            ],
            
            'feed_fetch' => [
                'path' => '/fetch-feed',
                'method' => 'POST',
                'description' => 'Fetch posts from RSS feeds',
                'payload' => [
                    'license_key' => 'string (required) - Valid license key',
                    'feed_url' => 'string (required) - RSS feed URL',
                    'limit' => 'integer (optional) - Number of posts to fetch'
                ],
                'response' => [
                    'success' => 'boolean - Whether fetch was successful',
                    'posts' => 'array - Fetched posts data'
                ]
            ]
        ];
    }
    
    /**
     * Get all endpoints for a specific category
     */
    public static function get_endpoints_by_category($category)
    {
        $endpoints = self::get_endpoints();
        $filtered = [];
        
        foreach ($endpoints as $key => $config) {
            if (strpos($key, $category . '_') === 0) {
                $filtered[$key] = $config;
            }
        }
        
        return $filtered;
    }
    
    /**
     * Validate endpoint payload structure
     */
    public static function validate_payload($endpoint_key, $payload)
    {
        $config = self::get_endpoint_config($endpoint_key);
        $required_fields = [];
        $errors = [];
        
        // Extract required fields
        foreach ($config['payload'] as $field => $description) {
            if (strpos($description, '(required)') !== false) {
                $required_fields[] = $field;
            }
        }
        
        // Check required fields
        foreach ($required_fields as $field) {
            if (!isset($payload[$field]) || ($payload[$field] === '' || $payload[$field] === null)) {
                $errors[] = "Missing required field: {$field}";
            }
        }
        
        // Additional validation for specific fields
        if (isset($payload['blog82ai_category']) && is_string($payload['blog82ai_category']) && strlen(trim($payload['blog82ai_category'])) === 0) {
            $errors[] = "Category name cannot be empty";
        }
        
        return [
            'valid' => empty($errors),
            'errors' => $errors
        ];
    }
    
    /**
     * Get current environment info
     */
    public static function get_environment_info()
    {
        $env = defined('BLOGIBOT_API_ENV') ? BLOGIBOT_API_ENV : 'production';
        
        return [
            'environment' => $env,
            'base_url' => self::get_base_url(),
            'is_production' => $env === 'production',
            'is_local' => in_array($env, ['local', 'development'])
        ];
    }
    
    /**
     * Debug: List all endpoints with their full URLs
     */
    public static function debug_list_all_endpoints()
    {
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            return null;
        }
        
        $endpoints = self::get_endpoints();
        $debug_info = [
            'environment' => self::get_environment_info(),
            'endpoints' => []
        ];
        
        foreach ($endpoints as $key => $config) {
            $debug_info['endpoints'][$key] = [
                'full_url' => self::get_endpoint_url($key),
                'method' => $config['method'],
                'description' => $config['description']
            ];
        }
        
        return $debug_info;
    }
}
