<?php
/**
 * Aysa API Configuration
 * Centralized API configuration with environment support
 * 
 * @package Aysa
 * @since 1.0.0
 */

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

class Aysa_API_Config {
    
    const ENV_DEVELOPMENT = 'development';
    const ENV_PRODUCTION = 'production';
    
    /**
     * Current environment - can be changed via WordPress option or constant
     */
    private static $environment = null;
    
    
    /**
     * API Configuration for different environments
     */
    private static $config = [
        self::ENV_DEVELOPMENT => [
            'base_url' => 'https://api.aysa.ai/',
            'endpoints' => [
                // Core endpoints
                'version_check' => 'https://download.aysa.ai/wp-update/check.php',
                'user_verify' => 'api/AysaPluginUser/fetchUserId',
                'domain_authority' => 'api/AysaPluginUser/domain-authority',
                
                // Project endpoints
                'project_by_domain' => 'api/Project/getbydomain',
                'seo_settings' => 'api/SeoSettings/ByProject',
                'project_domain_authority' => 'api/ProjectDomainAuthority',
                'project_domain_authority_by_secret' => 'api/ProjectDomainAuthority/BySecret/{secret}',
                
                // Research and tasks
                'research_tasks' => 'api/ResearchTasks',
                'research_tasks_by_project' => 'api/ResearchTasks/ByProject',
                'research_task_details' => 'api/ResearchTasks/TaskDetails',
                'associations_count' => 'api/AssociationsTask/ToAssociateCount',
                'domain_authority_avg' => 'api/aysa-plugin/datasks/domain-authority-avg',
                'external_links' => 'api/AysaKeyowrdsTable/external-links',
                
                // Technical optimization
                'redirects' => 'api/Redirect',
                'create_redirect' => 'api/Redirect',
                'auto_create_redirect' => 'api/Redirect/auto-create',
                'gone_urls' => 'api/GoneUrl',
                'unprocessed_bulk' => 'api/unprocessed/bulk-process',
                'schema_generate' => 'api/Schema/generate',
                'schema_generate_bulk' => 'api/Schema/generate-bulk',
                
                // Page speed and performance
                'pagespeed_metrics' => 'api/pagespeed/metrics',
                'pagespeed_metrics_get' => 'api/pagespeed/metrics/{projectId}',
                'pagespeed_overview' => 'api/pagespeed/overview',
                'pagespeed_overview_get' => 'api/pagespeed/overview/{projectId}',
                
                // Competitor analysis
                'keywords_gap' => 'api/keywordsgap/keywords-gap',
                'dataforseo_domain_rank' => 'api/dataforseo/labs/domain/rank/overview',
                'ranked_keywords' => 'api/seo/ranked-keywords',
                
                // General information
                'general_information_by_project' => 'api/generalinformation/byproject/{projectId}',
                
                // Associations and keywords
                'associations' => 'api/Association',
                'associations_set_tracked' => 'api/Association/setistracked',
                'keyword_associations' => 'api/ChatGPT/generate-keyword-associations',
                'upsert_entity' => 'api/Association/upsert',
                'insert_many_keywords' => 'api/Association/insertmany',
                'delete_entity_associations' => 'api/Association/by-entity/{entityId}/{entityType}/{projectId}',
                
                // Search intent
                'search_intent_batch' => 'api/SearchIntent/batch',
                'search_intent_by_project' => 'api/SearchIntent/project/{projectId}',
                
                // Content generation
                'product_category_title' => 'api/chatgpt/product-or-category-title',
                
                // Support
                'support_report_issue' => 'api/Support/ReportIssue',
                'support_contact' => 'api/Support/ContactSupport',
                
                // Orders
                'process_order' => 'api/order/process-order',
                
                // Credit Analytics
                'credit_history' => 'api/CreditHistory/project/{projectId}',
                'credit_summary' => 'api/CreditHistory/project/{projectId}/summary',
                'credit_balance' => 'api/AysaCredits/get-total-credits/{projectId}',
                
                // Link Building
                'wordtolink_search' => 'api/WordToLink/SearchByUrl/{userId}/{urlPart}',
                'cancel_wordtolink' => 'api/order/remove-wallet-product/{wtlId}'
            ]
        ],
        
        self::ENV_PRODUCTION => [
            'base_url' => 'https://api.aysa.ai/',
            'endpoints' => [
                // Core endpoints
                'version_check' => 'https://download.aysa.ai/wp-update/check.php',
                'user_verify' => 'api/AysaPluginUser/fetchUserId',
                'domain_authority' => 'api/AysaPluginUser/domain-authority',
                
                // Project endpoints
                'project_by_domain' => 'api/Project/getbydomain',
                'seo_settings' => 'api/SeoSettings/ByProject',
                'project_domain_authority' => 'api/ProjectDomainAuthority',
                'project_domain_authority_by_secret' => 'api/ProjectDomainAuthority/BySecret/{secret}',
                
                // Research and tasks
                'research_tasks' => 'api/ResearchTasks',
                'research_tasks_by_project' => 'api/ResearchTasks/ByProject',
                'research_task_details' => 'api/ResearchTasks/TaskDetails',
                'associations_count' => 'api/AssociationsTask/ToAssociateCount',
                'domain_authority_avg' => 'api/aysa-plugin/datasks/domain-authority-avg',
                'external_links' => 'api/AysaKeyowrdsTable/external-links',
                
                // Technical optimization
                'redirects' => 'api/Redirect',
                'create_redirect' => 'api/Redirect',
                'auto_create_redirect' => 'api/Redirect/auto-create',
                'gone_urls' => 'api/GoneUrl',
                'unprocessed_bulk' => 'api/unprocessed/bulk-process',
                'schema_generate' => 'api/Schema/generate',
                'schema_generate_bulk' => 'api/Schema/generate-bulk',
                
                // Page speed and performance
                'pagespeed_metrics' => 'api/pagespeed/metrics',
                'pagespeed_metrics_get' => 'api/pagespeed/metrics/{projectId}',
                'pagespeed_overview' => 'api/pagespeed/overview',
                'pagespeed_overview_get' => 'api/pagespeed/overview/{projectId}',
                
                // Competitor analysis
                'keywords_gap' => 'api/keywordsgap/keywords-gap',
                'dataforseo_domain_rank' => 'api/dataforseo/labs/domain/rank/overview',
                'ranked_keywords' => 'api/seo/ranked-keywords',
                
                // General information
                'general_information_by_project' => 'api/generalinformation/byproject/{projectId}',
                
                // Associations and keywords
                'associations' => 'api/Association',
                'associations_set_tracked' => 'api/Association/setistracked',
                'keyword_associations' => 'api/ChatGPT/generate-keyword-associations',
                'upsert_entity' => 'api/Association/upsert',
                'insert_many_keywords' => 'api/Association/insertmany',
                'delete_entity_associations' => 'api/Association/by-entity/{entityId}/{entityType}/{projectId}',
                
                // Search intent
                'search_intent_batch' => 'api/SearchIntent/batch',
                'search_intent_by_project' => 'api/SearchIntent/project/{projectId}',
                
                // Content generation
                'product_category_title' => 'api/chatgpt/product-or-category-title',
                
                // Support
                'support_report_issue' => 'api/Support/ReportIssue',
                'support_contact' => 'api/Support/ContactSupport',
                
                // Orders
                'process_order' => 'api/order/process-order',
                
                // Credit Analytics
                'credit_history' => 'api/CreditHistory/project/{projectId}',
                'credit_summary' => 'api/CreditHistory/project/{projectId}/summary',
                
                // Link Building
                'wordtolink_search' => 'api/WordToLink/SearchByUrl/{userId}/{urlPart}',
                'cancel_wordtolink' => 'api/order/remove-wallet-product/{wtlId}'
            ]
        ]
    ];
    
    /**
     * Get current environment
     * 
     * @return string
     */
    public static function get_environment() {
        if (self::$environment === null) {
            // Check for WordPress constant first
            if (defined('AYSA_API_ENVIRONMENT')) {
                self::$environment = AYSA_API_ENVIRONMENT;
            }
            // Check for WordPress option
            elseif ($env = get_option('aysa_api_environment')) {
                self::$environment = $env;
            }
            // Default to production
            else {
                self::$environment = self::ENV_PRODUCTION;
            }
            
            // Validate environment
            if (!in_array(self::$environment, [self::ENV_DEVELOPMENT, self::ENV_PRODUCTION])) {
                self::$environment = self::ENV_PRODUCTION;
            }
        }
        
        return self::$environment;
    }
    
    /**
     * Set environment
     * 
     * @param string $environment
     * @return bool
     */
    public static function set_environment($environment) {
        if (!in_array($environment, [self::ENV_DEVELOPMENT, self::ENV_PRODUCTION])) {
            return false;
        }
        
        self::$environment = $environment;
        update_option('aysa_api_environment', $environment);
        return true;
    }
    
    /**
     * Get base URL for current environment
     * 
     * @return string
     */
    public static function get_base_url() {
        if (defined('AYSA_API_BASE_URL_OVERRIDE') && is_string(AYSA_API_BASE_URL_OVERRIDE) && trim(AYSA_API_BASE_URL_OVERRIDE) !== '') {
            return rtrim((string) AYSA_API_BASE_URL_OVERRIDE, '/') . '/';
        }

        $option_override = get_option('aysa_api_base_url_override', '');
        if (is_string($option_override) && trim($option_override) !== '') {
            return rtrim(trim($option_override), '/') . '/';
        }

        $env = self::get_environment();
        $base = (string) (self::$config[$env]['base_url'] ?? '');
        if ($base === '') {
            $base = 'https://api.aysa.ai/';
        }
        return rtrim($base, '/') . '/';
    }
    
    /**
     * Get endpoint URL for current environment
     * 
     * @param string $endpoint_key
     * @param array $params Optional parameters to append to URL
     * @return string|false
     */
    public static function get_endpoint_url($endpoint_key, $params = []) {
        $env = self::get_environment();
        
        if (!isset(self::$config[$env]['endpoints'][$endpoint_key])) {
            aysa_debug_log("[AYSA API Config] Endpoint '$endpoint_key' not found for environment '$env'");
            return false;
        }
        
        // Use resolved base URL (supports local override constants/options).
        $base_url = rtrim(self::get_base_url(), '/');
        
        $endpoint = self::$config[$env]['endpoints'][$endpoint_key];
        if (preg_match('/^https?:\\/\\//i', $endpoint) === 1) {
            $url = $endpoint;
        } else {
            $url = $base_url . '/' . ltrim($endpoint, '/');
        }
        
        // Add parameters if provided
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        
        return $url;
    }
    
    /**
     * Get full endpoint URL with parameters replaced
     * 
     * @param string $endpoint_key
     * @param array $url_params Parameters to replace in URL (e.g., {id} => 123)
     * @param array $query_params Query parameters to append
     * @return string|false
     */
    public static function get_endpoint_url_with_params($endpoint_key, $url_params = [], $query_params = []) {
        $env = self::get_environment();
        
        if (!isset(self::$config[$env]['endpoints'][$endpoint_key])) {
            aysa_debug_log("[AYSA API Config] Endpoint '$endpoint_key' not found for environment '$env'");
            return false;
        }
        
        // Use resolved base URL (supports local override constants/options).
        $base_url = rtrim(self::get_base_url(), '/');
        
        $endpoint = self::$config[$env]['endpoints'][$endpoint_key];
        
        // Replace URL parameters
        foreach ($url_params as $key => $value) {
            $endpoint = str_replace('{' . $key . '}', $value, $endpoint);
        }
        
        if (preg_match('/^https?:\\/\\//i', $endpoint) === 1) {
            $url = $endpoint;
        } else {
            $url = $base_url . '/' . ltrim($endpoint, '/');
        }
        
        // Add query parameters if provided
        if (!empty($query_params)) {
            $url .= '?' . http_build_query($query_params);
        }
        
        return $url;
    }
    
    /**
     * Get all available environments
     * 
     * @return array
     */
    public static function get_available_environments() {
        return [
            self::ENV_DEVELOPMENT => 'Development (API override only)',
            self::ENV_PRODUCTION => 'Production (Live API)'
        ];
    }
    
    /**
     * Get all endpoints for current environment
     * 
     * @return array
     */
    public static function get_all_endpoints() {
        $env = self::get_environment();
        return self::$config[$env]['endpoints'];
    }
    
    /**
     * Get JavaScript configuration for current environment
     * 
     * @return array
     */
    public static function get_js_config() {
        return [
            'environment' => self::get_environment(),
            'baseUrl' => self::get_base_url(),
            'endpoints' => self::get_all_endpoints()
        ];
    }

    /**
     * Get API base URL for current environment
     * Alias for get_base_url() for consistency with other methods
     * 
     * @return string
     */
    public static function get_api_base_url() {
        return self::get_base_url();
    }
}
