<?php
/**
 * 
 *
 * This file contains the functions for managing free version of FluentC
 *
 * @category Translation
 * @package  FluentCPlugin
 * @author   FluentC <wp@fluentc.io>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     https://www.fluentc.ai
 */
namespace FluentC\Services;

use FluentC\Models\Body;


if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class FluentC_Free
{
    public function handle_api_call() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_die('Security check failed');
        }
        
        // Handle API calls here
        $response = array(
            'success' => true,
            'message' => 'API call successful',
            'data' => $_POST
        );
        
        wp_send_json($response);
    }

    
    
    /**
     * Handle fetching page HTML content
     */
    public function handle_fetch_page_html() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Get the page URL from the request
        $page_url = sanitize_url($_POST['page_url']);
        
        if (empty($page_url)) {
            wp_send_json_error('Page URL is required');
            return;
        }
        
        // Check if this request allows external URLs (for shortcode usage)
        $allow_external = isset($_POST['allow_external']) && $_POST['allow_external'] === 'true';
        
        // Validate URL format
        $parsed_page = parse_url($page_url);
        if (!$parsed_page) {
            wp_send_json_error('Invalid URL provided');
            return;
        }
        
        // Only enforce same-domain restriction for admin usage (not shortcode)
        if (!$allow_external) {
            $site_url = home_url();
            $parsed_site = parse_url($site_url);
            
            if (!$parsed_site) {
                wp_send_json_error('Invalid site URL configuration');
                return;
            }
            
            // Check if the domain matches (only for admin usage)
            if ($parsed_page['host'] !== $parsed_site['host']) {
                wp_send_json_error('URL must be from the same WordPress site');
                return;
            }
        }
        
        // Add basic URL validation for external URLs
        if ($allow_external) {
            // Ensure it's HTTP or HTTPS
            if (!in_array($parsed_page['scheme'], ['http', 'https'])) {
                wp_send_json_error('Only HTTP and HTTPS URLs are supported');
                return;
            }
            
            // Basic security check - prevent access to localhost/private IPs
            $host = $parsed_page['host'];
            if (filter_var($host, FILTER_VALIDATE_IP)) {
                if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
                    wp_send_json_error('Private IP addresses are not allowed');
                    return;
                }
            }
        }
        
        // Fetch the HTML content
        $response = wp_remote_get($page_url, array(
            'timeout' => 30,
            'user-agent' => 'FluentC Translation Plugin',
            'headers' => array(
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            ),
        ));
        
        if (is_wp_error($response)) {
            wp_send_json_error('Failed to fetch page: ' . $response->get_error_message());
            return;
        }
        
        $http_code = wp_remote_retrieve_response_code($response);
        if ($http_code !== 200) {
            wp_send_json_error('Failed to fetch page. HTTP status: ' . $http_code);
            return;
        }
        
        $html_content = wp_remote_retrieve_body($response);
        
        if (empty($html_content)) {
            wp_send_json_error('No content found at the specified URL');
            return;
        }
        
        // Clean up the HTML and remove potential script tags for security
        $html_content = $this->sanitize_html_content($html_content);
        
        wp_send_json_success(array(
            'html' => $html_content,
            'url' => $page_url,
            'size' => strlen($html_content),
            'fetched_at' => current_time('mysql')
        ));
    }
    
    /**
     * Sanitize HTML content for processing
     */
    private function sanitize_html_content($html) {
        // Remove script tags and their content for security
        $html = preg_replace('/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/mi', '', $html);
        
        // Remove style tags but keep the content structure
        $html = preg_replace('/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/mi', '', $html);
        
        // Remove comments
        $html = preg_replace('/<!--(.|\s)*?-->/', '', $html);
        
        // Normalize whitespace
        $html = preg_replace('/\s+/', ' ', $html);
        
        return trim($html);
    }
    
    /**
     * Handle getting language options from FluentC API
     */
    public function handle_get_language_options() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Check if user has a valid API key
        $user_api_key = get_option('fluentc_api_key', '');
        if (empty($user_api_key) || trim($user_api_key) === '') {
            // For users without API keys, get full language list using free key but limit target languages
            $free_api_key = "13c25c70-a4fa-4232-9d2c-1c451e71c3b7";
            
            // Make API call to FluentC to get the full language list
            $api_response = wp_remote_get('https://dashboard.fluentc.io/ai_agent/languages', array(
                'timeout' => 15,
                'headers' => array(
                    'Authorization' => $free_api_key,
                    'Content-Type' => 'application/json',
                    'User-Agent' => 'FluentC WordPress Plugin '
                )
            ));
            
            if (is_wp_error($api_response)) {
                error_log('FluentC Language API Error (Free): ' . $api_response->get_error_message());
                // Fallback to hardcoded languages if API fails
                $limited_target_languages = array(
                    array('code' => 'en', 'name' => 'English', 'direction' => 'ltr'),
                    array('code' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'),
                    array('code' => 'fr', 'name' => 'French', 'direction' => 'ltr'),
                    array('code' => 'de', 'name' => 'German', 'direction' => 'ltr'),
                    array('code' => 'zh', 'name' => 'Chinese', 'direction' => 'ltr'),
                    array('code' => 'ar', 'name' => 'Arabic', 'direction' => 'rtl')
                );
                
                wp_send_json_success(array(
                    'targetLanguages' => $limited_target_languages,
                    'sourceLanguages' => $limited_target_languages
                ));
                return;
            }
            
            $http_code = wp_remote_retrieve_response_code($api_response);
            $response_body = wp_remote_retrieve_body($api_response);
            
            if ($http_code !== 200) {
                error_log("FluentC Language API returned {$http_code}: {$response_body}");
                // Fallback to hardcoded languages if API fails
                $limited_target_languages = array(
                    array('code' => 'en', 'name' => 'English', 'direction' => 'ltr'),
                    array('code' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'),
                    array('code' => 'fr', 'name' => 'French', 'direction' => 'ltr'),
                    array('code' => 'de', 'name' => 'German', 'direction' => 'ltr'),
                    array('code' => 'zh', 'name' => 'Chinese', 'direction' => 'ltr'),
                    array('code' => 'ar', 'name' => 'Arabic', 'direction' => 'rtl')
                );
                
                wp_send_json_success(array(
                    'targetLanguages' => $limited_target_languages,
                    'sourceLanguages' => $limited_target_languages
                ));
                return;
            }
            
            $language_data = json_decode($response_body, true);
            
            if (!$language_data || !is_array($language_data)) {
                error_log('FluentC Language API returned invalid JSON: ' . $response_body);
                // Fallback to hardcoded languages if API fails
                $limited_target_languages = array(
                    array('code' => 'en', 'name' => 'English', 'direction' => 'ltr'),
                    array('code' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'),
                    array('code' => 'fr', 'name' => 'French', 'direction' => 'ltr'),
                    array('code' => 'de', 'name' => 'German', 'direction' => 'ltr'),
                    array('code' => 'zh', 'name' => 'Chinese', 'direction' => 'ltr'),
                    array('code' => 'ar', 'name' => 'Arabic', 'direction' => 'rtl')
                );
                
                wp_send_json_success(array(
                    'targetLanguages' => $limited_target_languages,
                    'sourceLanguages' => $limited_target_languages
                ));
                return;
            }
            
            // Process the full language list from API
            $all_source_languages = array();
            $all_target_languages = array();
            
            // Process supported languages (target languages)
            if (isset($language_data['supported_languages']) && is_array($language_data['supported_languages'])) {
                foreach ($language_data['supported_languages'] as $lang) {
                    if (isset($lang['code']) && isset($lang['name'])) {
                        $formatted_lang = array(
                            'code'      => $lang['code'],
                            'name'      => $lang['name'],
                            'direction' => $lang['direction'] ?? 'ltr'
                        );
                        $all_target_languages[] = $formatted_lang;
                    }
                }
            }
            
            // Process source languages (should be full list)
            if (isset($language_data['source_languages']) && is_array($language_data['source_languages'])) {
                foreach ($language_data['source_languages'] as $lang) {
                    if (isset($lang['code']) && isset($lang['name'])) {
                        $all_source_languages[] = array(
                            'code'      => $lang['code'],
                            'name'      => $lang['name'],
                            'direction' => $lang['direction'] ?? 'ltr'
                        );
                    }
                }
            } else if (!empty($all_target_languages)) {
                // Fallback to use target languages for source if source_languages is not provided
                $all_source_languages = $all_target_languages;
            }
            
            // Define allowed target languages for free users (limit only target, not source!)
            $allowed_target_codes = ['en', 'es', 'fr', 'de', 'zh', 'ar'];
            
            // Filter target languages to only include allowed ones for free users
            $limited_target_languages = array_filter($all_target_languages, function($lang) use ($allowed_target_codes) {
                return in_array($lang['code'], $allowed_target_codes);
            });
            
            // Re-index the array to ensure proper JSON encoding
            $limited_target_languages = array_values($limited_target_languages);
            
            // Return full source languages but limited target languages
            wp_send_json_success(array(
                'targetLanguages' => $limited_target_languages,
                'sourceLanguages' => $all_source_languages  // FULL LIST for source languages
            ));
            return;
        }
        
        // Validate the user's API key format (basic validation)
        if (!$this->is_valid_api_key_format($user_api_key)) {
            wp_send_json_error('Invalid API key format. Please check your API key and try again.');
            return;
        }
        
        // Use the user's API key for full language options
        $api_key = $user_api_key;
        
        // Make API call to FluentC to get available languages
        $api_response = wp_remote_get('https://dashboard.fluentc.io/ai_agent/languages', array(
            'timeout' => 15,
            'headers' => array(
                'Authorization' => $api_key,
                'Content-Type' => 'application/json',
                'User-Agent' => 'FluentC WordPress Plugin '
            )
        ));
        
        if (is_wp_error($api_response)) {
            error_log('FluentC Language API Error: ' . $api_response->get_error_message());
            wp_send_json_error('Failed to connect to FluentC API: ' . $api_response->get_error_message());
            return;
        }
        
        $http_code = wp_remote_retrieve_response_code($api_response);
        $response_body = wp_remote_retrieve_body($api_response);
        
        if ($http_code === 401 || $http_code === 403) {
            wp_send_json_error('Invalid API key. Please check your API key and try again.');
            return;
        }
        
        if ($http_code !== 200) {
            error_log("FluentC Language API returned {$http_code}: {$response_body}");
            wp_send_json_error("FluentC API returned HTTP {$http_code}. Please try again later.");
            return;
        }
        
        $language_data = json_decode($response_body, true);
        
        if (!$language_data || !is_array($language_data)) {
            error_log('FluentC Language API returned invalid JSON: ' . $response_body);
            wp_send_json_error('Invalid response from FluentC API. Please try again.');
            return;
        }
        
        // Process the languages from the API response
        $target_languages = array();
        //$source_languages = array(
        //    array('code' => 'auto', 'name' => 'Auto-detect')
        //);
        
        // Process target languages
        if (isset($language_data['supported_languages']) && is_array($language_data['supported_languages'])) {
            foreach ($language_data['supported_languages'] as $lang) {
                if (isset($lang['code']) && isset($lang['name'])) {
                    $formatted_lang = array(
                        'code'      => $lang['code'],
                        'name'      => $lang['name'],
                        'direction' => $lang['direction'] ?? 'ltr'
                    );
                    $target_languages[] = $formatted_lang;
                }
            }
        }
        
        // Process source languages
		if (isset($language_data['source_languages']) && is_array($language_data['source_languages'])) {
			foreach ($language_data['source_languages'] as $lang) {
				if (isset($lang['code']) && isset($lang['name'])) {
					$source_languages[] = array(
						'code'      => $lang['code'],
						'name'      => $lang['name'],
						'direction' => $lang['direction'] ?? 'ltr'
					);
				}
			}
		} else if (!empty($target_languages)) {
            // Fallback to use target languages for source if source_languages is not provided
            foreach ($target_languages as $lang) {
                $source_languages[] = $lang;
            }
        }
        
        if (empty($target_languages)) {
            wp_send_json_error('No valid languages found in FluentC API response. Please try again later.');
            return;
        }
        
        // Prepare response data
        $response_data = array(
            'targetLanguages' => $target_languages,
            'sourceLanguages' => $source_languages
        );
        
        // WordPress wp_send_json_success() returns: {"success":true,"data":{...}}
        wp_send_json_success($response_data);
    }
    
    /**
     * Validate API key format
     * 
     * @param string $api_key The API key to validate
     * @return bool True if format is valid
     */
    private function is_valid_api_key_format($api_key) {
        $trimmed_key = trim($api_key);
        
        // Reject the free API key - users should never be able to save this
        if ($trimmed_key === '13c25c70-a4fa-4232-9d2c-1c451e71c3b7') {
            return false;
        }
        
        // Basic format validation - adjust pattern as needed for your API key format
        // This example assumes UUID format, but you should adjust to match your actual format
        $pattern = '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/';
        return preg_match($pattern, $trimmed_key) === 1;
    }
    
    /**
     * Handle translation content request
     */
    public function handle_translate_content() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Determine which API key to use
        $user_api_key = get_option('fluentc_api_key', '');
        if (!empty($user_api_key) && trim($user_api_key) !== '') {
            // Use user's API key if they have one
            $api_key = trim($user_api_key);
        } else {
            // Use hardcoded free API key for testing when user has no key
            $api_key = "13c25c70-a4fa-4232-9d2c-1c451e71c3b7";
        }
        
        // Get request parameters
        $input = sanitize_textarea_field($_POST['input']);
        $input_format = sanitize_text_field($_POST['input_format']) ?: 'text';
        $target_language = sanitize_text_field($_POST['target_language']);
        $source_language = sanitize_text_field($_POST['source_language']);
        $mode = sanitize_text_field($_POST['mode']) ?: 'real-time';
        
        if (empty($input) || empty($target_language)) {
            wp_send_json_error('Input text and target language are required');
            return;
        }
        
        // Prepare request data
        $request_data = array(
            'input' => $input,
            'input_format' => $input_format,
            'target_language' => $target_language,
            'mode' => $mode
        );
        
        // Add source language if provided
        if (!empty($source_language)) {
            $request_data['source_language'] = $source_language;
        }
        
        // Make API call to FluentC
        $api_response = wp_remote_post('https://dashboard.fluentc.io/ai_agent/translate', array(
            'timeout' => 30,
            'headers' => array(
                'Authorization' => $api_key,
                'Content-Type' => 'application/json',
                'User-Agent' => 'FluentC WordPress Plugin '
            ),
            'body' => json_encode($request_data)
        ));
        
        if (is_wp_error($api_response)) {
            error_log('FluentC Translation API Error: ' . $api_response->get_error_message());
            wp_send_json_error('Translation service temporarily unavailable: ' . $api_response->get_error_message());
            return;
        }
        
        $http_code = wp_remote_retrieve_response_code($api_response);
        $response_body = wp_remote_retrieve_body($api_response);
        
        if ($http_code === 200) {
            $translation_data = json_decode($response_body, true);
            
            if ($mode === 'real-time') {
                wp_send_json_success(array(
                    'status' => $translation_data['status'] ?? 'complete',
                    'translation' => $translation_data['translation'] ?? '',
                    'tokenCount' => $translation_data['token_count'] ?? 0,
                    'sourceLanguageDetected' => $translation_data['source_language_detected'] ?? $source_language
                ));
            } else {
                // Batch mode returns job_id
                wp_send_json_success(array(
                    'jobId' => $translation_data['job_id'] ?? null
                ));
            }
        } else {
            $error_data = json_decode($response_body, true);
            $error_message = $error_data['error'] ?? "Translation failed with HTTP {$http_code}";
            error_log("FluentC Translation API returned {$http_code}: {$response_body}");
            wp_send_json_error($error_message);
        }
    }
    
    /**
     * Handle get translation results request
     */
    public function handle_get_translation_results() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        // Determine which API key to use - must filter out the free API key if it was previously saved
        $user_api_key = get_option('fluentc_api_key', '');
        $free_api_key = "13c25c70-a4fa-4232-9d2c-1c451e71c3b7";
        
        // Debug logging
        error_log("FluentC Translation Results - Raw user API key from DB: " . ($user_api_key ? 'XXXXX-' . substr($user_api_key, -4) : 'empty'));
        
        if (!empty($user_api_key) && trim($user_api_key) !== '' && trim($user_api_key) !== $free_api_key) {
            // Use user's API key if they have a valid one (not the free key)
            $api_key = trim($user_api_key);
            error_log("FluentC Translation Results - Using user API key: XXXXX-" . substr($api_key, -4));
        } else {
            // Use hardcoded free API key for testing when user has no key or has the free key saved
            $api_key = $free_api_key;
            error_log("FluentC Translation Results - Using free API key for testing");
        }
        
        // Get request parameters
        $job_id = sanitize_text_field($_POST['job_id']);
        
        if (empty($job_id)) {
            wp_send_json_error('Job ID is required');
            return;
        }
        
        error_log("FluentC Translation Results - Job ID: {$job_id}");
        error_log("FluentC Translation Results - API Endpoint: https://dashboard.fluentc.io/ai_agent/results");
        
        // Make API call to FluentC
        $api_response = wp_remote_post('https://dashboard.fluentc.io/ai_agent/results', array(
            'timeout' => 15,
            'headers' => array(
                'Authorization' => $api_key,
                'Content-Type' => 'application/json',
                'User-Agent' => 'FluentC WordPress Plugin '
            ),
            'body' => json_encode(array(
                'job_id' => $job_id
            ))
        ));
        
        if (is_wp_error($api_response)) {
            error_log('FluentC Translation Results API Error: ' . $api_response->get_error_message());
            wp_send_json_error('Failed to get translation results: ' . $api_response->get_error_message());
            return;
        }
        
        $http_code = wp_remote_retrieve_response_code($api_response);
        $response_body = wp_remote_retrieve_body($api_response);
        
        // Debug logging
        error_log("FluentC Translation Results - HTTP Code: {$http_code}");
        error_log("FluentC Translation Results - Response Body Length: " . strlen($response_body));
        error_log("FluentC Translation Results - Response Body (First 500 chars): " . substr($response_body, 0, 500));
        error_log("FluentC Translation Results - Full Response Body: {$response_body}");
        
        // Check if response body is empty
        if (empty($response_body)) {
            error_log("FluentC Translation Results - Empty response body received");
            wp_send_json_error('Empty response received from translation API');
            return;
        }
        
        if ($http_code === 200) {
            $result_data = json_decode($response_body, true);
            
            // Check if JSON parsing was successful
            if (json_last_error() !== JSON_ERROR_NONE) {
                $json_error = json_last_error_msg();
                error_log("FluentC Translation Results - JSON Error: {$json_error}");
                error_log("FluentC Translation Results - Response appears to be: " . (is_string($response_body) && strlen($response_body) < 200 ? $response_body : 'Large response (see full body above)'));
                
                // Check if response looks like HTML (common error response)
                if (strpos(trim($response_body), '<') === 0) {
                    wp_send_json_error('API returned HTML instead of JSON. This may indicate an authentication or server error.');
                    return;
                }
                
                wp_send_json_error("Failed to parse API response: {$json_error}");
                return;
            }
            
            // Debug logging to see the actual structure
            error_log("FluentC Translation Results - Parsed Data: " . print_r($result_data, true));
            
            // Check if we have valid data
            if (!is_array($result_data)) {
                error_log("FluentC Translation Results - Unexpected response structure: " . gettype($result_data));
                wp_send_json_error('Unexpected response structure from translation API');
                return;
            }
            
            // Check each field individually and log if missing
            $status = $result_data['status'] ?? null;
            $translation = $result_data['translation'] ?? null;
            $token_count = $result_data['token_count'] ?? null;
            $source_language_detected = $result_data['source_language_detected'] ?? null;
            
            if ($status === null) {
                error_log("FluentC Translation Results - Missing 'status' field in response");
            }
            if ($translation === null) {
                error_log("FluentC Translation Results - Missing 'translation' field in response");
            }
            if ($token_count === null) {
                error_log("FluentC Translation Results - Missing 'token_count' field in response");
            }
            if ($source_language_detected === null) {
                error_log("FluentC Translation Results - Missing 'source_language_detected' field in response");
            }
            
            wp_send_json_success(array(
                'status' => $status ?? 'unknown',
                'translation' => $translation ?? '',
                'tokenCount' => $token_count ?? 0,
                'sourceLanguageDetected' => $source_language_detected ?? '',
                'estimatedWaitSeconds' => $result_data['estimated_wait_seconds'] ?? 0,
                'nextPollAfter' => $result_data['next_poll_after'] ?? 0,
                'error' => $result_data['error'] ?? null
            ));
        } else {
            $error_data = json_decode($response_body, true);
            $error_message = $error_data['error'] ?? "Failed to get translation results with HTTP {$http_code}";
            error_log("FluentC Translation Results API returned {$http_code}: {$response_body}");
            wp_send_json_error($error_message);
        }
    }
    
    /**
     * Handle process HTML request
     */
    public function handle_process_html() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
        
        $this->heartbeat();
        
        // Determine which API key to use
        $user_api_key = get_option('fluentc_api_key', '');
        if (!empty($user_api_key) && trim($user_api_key) !== '') {
            // Use user's API key if they have one
            $api_key = trim($user_api_key);
        } else {
            // Use hardcoded free API key for testing when user has no key
            $api_key = "13c25c70-a4fa-4232-9d2c-1c451e71c3b7";
        }
        
        // Get request parameters
        $html = wp_unslash($_POST['html']);
        $html = base64_encode($html);
        error_log("HTML: " . $html);

        // Ensure the HTML is valid UTF-8 to prevent json_encode from failing.
        if (function_exists('mb_check_encoding') && !mb_check_encoding($html, 'UTF-8')) {
            $html = mb_convert_encoding($html, 'UTF-8', 'auto');
        }

        $base64_encode = isset($_POST['base64_encode']) ? (bool)$_POST['base64_encode'] : true;
        $source_language = sanitize_text_field($_POST['source_language']) ?: 'en';
        
        if (empty($html)) {
            wp_send_json_error('HTML content is required');
            return;
        }
        
        // Prepare GraphQL query
        $query = '
            query ProcessHtml($html: String!, $base64Encode: Boolean, $sourceLanguage: String) {
                processHtml(
                    html: $html
                    base64Encode: $base64Encode
                    sourceLanguage: $sourceLanguage
                ) {
                    count
                    processedAt
                    textNodes
                }
            }
        ';
        
        $variables = array(
            'html' => $html,
            'base64Encode' => $base64_encode,
            'sourceLanguage' => $source_language
        );
        
        $request_body = json_encode(array(
            'query' => $query,
            'variables' => $variables
        ));

        if ($request_body === false) {
            wp_send_json_error('Failed to encode request for HTML processing: ' . json_last_error_msg());
            return;
        }
        
        // Make GraphQL API call to FluentC
        $api_response = wp_remote_post('https://dashboard.fluentc.ai/graphql', array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'FluentC WordPress Plugin '
            ),
            'body' => $request_body
        ));
        
        if (is_wp_error($api_response)) {
            error_log('FluentC GraphQL API Error: ' . $api_response->get_error_message());
            wp_send_json_error('HTML processing service temporarily unavailable: ' . $api_response->get_error_message());
            return;
        }
        
        $http_code = wp_remote_retrieve_response_code($api_response);
        $response_body = wp_remote_retrieve_body($api_response);
        
        if ($http_code === 200) {
            $graphql_data = json_decode($response_body, true);
            
            if (isset($graphql_data['errors'])) {
                $error_message = 'GraphQL errors: ' . json_encode($graphql_data['errors']);
                error_log('FluentC GraphQL Errors: ' . $error_message);
                wp_send_json_error($error_message);
                return;
            }
            
            $process_html_data = $graphql_data['data']['processHtml'] ?? null;
            
            if ($process_html_data) {
                wp_send_json_success(array(
                    'count' => $process_html_data['count'] ?? 0,
                    'processedAt' => $process_html_data['processedAt'] ?? null,
                    'textNodes' => $process_html_data['textNodes'] ?? array()
                ));
            } else {
                wp_send_json_error('Invalid response from HTML processing service');
            }
        } else {
            $error_data = json_decode($response_body, true);
            $error_message = $error_data['error'] ?? "HTML processing failed with HTTP {$http_code}";
            error_log("FluentC GraphQL API returned {$http_code}: {$response_body}");
            wp_send_json_error($error_message);
        }
    }

    /**
     * Handle live translation previews on the front-end.
     * This hooks into 'init' and checks for a 'translate' GET parameter.
     */
    public function handle_live_translation() {
        // Only proceed if the 'translate' parameter is set in the URL.
        if (!isset($_GET['translate'])) {
            return;
        }

        // Allow for all users if they're using the shortcode functionality
        // Keep admin requirement for direct URL translation, but allow public for shortcode
        if (is_admin()) {
            return;
        }
        
        // The rest of the existing logic remains the same...
        $this->heartbeat();
        ob_start(array($this, 'translate_output_buffer'));
    }

    /**
     * Callback for ob_start to translate the page's output buffer.
     * @param string $buffer The HTML content of the page.
     * @return string The translated HTML content.
     */
    public function translate_output_buffer($buffer) {
        $target_language = sanitize_text_field($_GET['translate']);
        $source_language = sanitize_text_field($_GET['source'] ?? 'en'); // Default source to 'en' if not provided
        if (empty($target_language)) {
            return $buffer; // Return original content if language is not set
        }

        // Determine which API key to use
        $user_api_key = get_option('fluentc_api_key', '');
        if (!empty($user_api_key) && trim($user_api_key) !== '') {
            // Use user's API key if they have one
            $api_key = trim($user_api_key);
        } else {
            // Use hardcoded free API key for testing when user has no key
            $api_key = "13c25c70-a4fa-4232-9d2c-1c451e71c3b7";
        }
      
        $html = base64_encode($buffer);
        
        // Get the current request path
        $path = $this->get_request_path();
        
        // Prepare GraphQL query
        $query = '
            query translateHtml($html: String!, $sourceLanguage: String!, $targetLanguage: String!, $siteId: String!, $path: String) {
                translateHtml(
                    html: $html
                    base64Encode: true
                    sourceLanguage: $sourceLanguage
                    targetLanguage: $targetLanguage
                    siteId: $siteId
                    path: $path
                ) {
                    body
                }
            }
        ';
        
        $variables = array(
            'html' => $html,
            'sourceLanguage' => $source_language,
            'targetLanguage' => $target_language,
            'siteId' => $api_key,
            'path' => $path
        );
        
        $request_body = json_encode(array(
            'query' => $query,
            'variables' => $variables
        ));

        if ($request_body === false) {
            error_log('FluentC GraphQL: Failed to encode request for HTML translation: ' . json_last_error_msg());
            return $buffer;
        }
        
        // Make GraphQL API call to FluentC
        $api_response = wp_remote_post('https://dashboard.fluentc.ai/graphql', array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'FluentC WordPress Plugin '
            ),
            'body' => $request_body
        ));
        
        if (is_wp_error($api_response)) {
            error_log('FluentC GraphQL API Error: ' . $api_response->get_error_message());
            return $buffer;
        }
        
        $http_code = wp_remote_retrieve_response_code($api_response);
        $response_body = wp_remote_retrieve_body($api_response);
        
        if ($http_code === 200) {
            $graphql_data = json_decode($response_body, true);
            
            if (isset($graphql_data['errors'])) {
                $error_message = 'GraphQL errors: ' . json_encode($graphql_data['errors']);
                error_log('FluentC GraphQL Errors: ' . $error_message);
                return $buffer;
            }
            
            $translated_html = $graphql_data['data']['translateHtml']['body'] ?? null;
            
            if ($translated_html) {
                return $translated_html;
            } else {
                error_log('FluentC GraphQL: translateHtml.body not found in response.');
                return $buffer;
            }
        } else {
            error_log("FluentC GraphQL API returned {$http_code}: {$response_body}");
            return $buffer;
        }
    }

     /**
 * Sends a heartbeat to the FluentC API
 *
 * @param string|null $widget_id The FluentC API key (can be null)
 * @return mixed The API response or null on error
 */
public function heartbeat($widget_id = null)
{
    $site_url = home_url();
    
    $query = <<<GRAPHQL
    {
      heartBeat(
        host: "$site_url",
        action:"free_page"
      ) {
        body {
          status
        }
      }
    }
    GRAPHQL;

    // Pass false to indicate this request doesn't require an API key
    $response = $this->makeGraphQLRequest($query, false);

    if ($response && isset($response->data)) {
        do_action('qm/info', 'FluentC Site setup post completed');
        return $response;
    }

    return null;
}
/**
     * Summary of makeGraphQLRequest
     * @param mixed $query
     * @return mixed
     */
    private function makeGraphQLRequest($query, $require_api_key = true)
    {
        // Only check for API key if this request requires one
        if ($require_api_key) {
            $widgetapikey = get_option('fluentc_api_key');
            if (empty($widgetapikey)) {
                return null;
            }
        }
        $response = wp_remote_post('https://dashboard.fluentc.ai/graphql', [
            'body' => wp_json_encode(['query' => $query]),
            'headers' => [
                'Content-Type' => 'application/json',
                'x-api-key' => "13c25c70-a4fa-4232-9d2c-1c451e71c3b7",
            ],
            'timeout' => 20,
        ]);

        if (is_wp_error($response)) {
            do_action('qm/error', 'Error in request: ' . $response->get_error_message());
            return null;
        }

        $body = wp_remote_retrieve_body($response);
        $status = wp_remote_retrieve_response_code($response);

        $response_data = json_decode($body);

        if ($status !== 200 || !$response_data) {
            $this->handleRequestError($status, $response_data);
            return null;
        }

        return $response_data;
    }

    /**
     * Render the translator shortcode
     */
    public function render_translator_shortcode($atts) {
        // Mark that shortcode is being used
        $this->shortcode_used = true;
        
        // Parse attributes (for future extensibility) 
        $atts = shortcode_atts(array(
            'id' => 'fluentc-translator-' . wp_generate_uuid4()
        ), $atts, 'fluentc_translator');
        
        // Return the container div where React will mount
        return '<div id="' . esc_attr($atts['id']) . '" class="fluentc-translator-widget"></div>';
    }

    /**
     * Conditionally enqueue assets only when shortcode is used
     */
    public function maybe_enqueue_shortcode_assets() {
        global $post;
        
        // Check if shortcode is present in post content
        if (is_object($post) && has_shortcode($post->post_content, 'fluentc_translator')) {
            $this->enqueue_frontend_assets();
        }
    }

    /**
     * Get the current request path without language code
     *
     * @return string The request path
     */
    private function get_request_path() {
        // Start with the REQUEST_URI
        $request_uri = $_SERVER['REQUEST_URI'] ?? '/';
        
        // Parse the URL to get just the path
        $parsed = parse_url($request_uri);
        $path = $parsed['path'] ?? '/';
        
        // Get the home URL to determine if WordPress is in a subdirectory
        $home_url = home_url('/');
        $home_path = parse_url($home_url, PHP_URL_PATH);
        
        // Remove the home path from the beginning if WordPress is in a subdirectory
        if (!empty($home_path) && $home_path !== '/' && strpos($path, $home_path) === 0) {
            $path = substr($path, strlen($home_path));
        }
        
        // Ensure path starts with /
        if (empty($path) || $path[0] !== '/') {
            $path = '/' . $path;
        }
        
        // Remove trailing slash unless it's just "/"
        if (strlen($path) > 1 && substr($path, -1) === '/') {
            $path = rtrim($path, '/');
        }
        
        return $path;
    }
}