<?php
/**
 * FluentC WordPress Plugin File.
 *
 * This file contains the WordPress functions for the Admin section
 *
 * @package FluentCPlugin
 * @author  FluentC <wp@fluentc.io>
 */

namespace FluentC\Actions;

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

use FluentC\Models\Hooks;
use FluentC\Services\Cache;
use FluentC\Services\Url;
use FluentC\Services\Scan;
use FluentC\Services\Widget;
use FluentC\Services\Connect;
use FluentC\Services\FluentC_Translations;
use FluentC\Services\Translation_Processor;
use FluentC\Services\API_Key_Validator;
use FluentC\Services\Support_Report;
use FluentC\Services\FluentC_Free;

/**
 * Admin Functions
 *
 * @since 1.2
 */
class Admin implements Hooks
{

    /**
     * FluentC Widget class
     *
     * @var object
     */
    protected $fluentc_widget_c;

    /**
     * FluentC Widget class
     *
     * @var object
     */
    protected $fluentc_scan;
    /**
     * FluentC Widget class
     *
     * @var object
     */
    protected $translations;
    /**
     * FluentC URL class
     *
     * @var object
     */
    protected $fluentc_url;
    /**
     * FluentC connection class
     *
     * @var object
     */
    protected $fluentc_connect;
    /**
     * FluentC connection class
     *
     * @var object
     */
    protected $fluentc_cache;
    /**
     * FluentC translation processor class
     *
     * @var Translation_Processor
     */
    protected $fluentc_processor;
    /**
     * FluentC API class
     *
     * @var API_Key_Validator
     */
    protected $fluentc_api;
    /**
     * FluentC API class
     *
     * @var API_Key_Validator
     */
    protected $fluentc_free;

    /**
     * Constructor.
     *
     * @since 1.2
     */
    public function __construct()
    {
        $this->fluentc_widget_c = new Widget();
        $this->fluentc_connect  = new Connect();
        $this->fluentc_cache    = new Cache();
        $this->fluentc_url      = new Url();
        $this->fluentc_scan      = new Scan();
        $this->translations = new FluentC_Translations();
        $this->fluentc_processor = new Translation_Processor();
        $this->fluentc_api = new API_Key_Validator();
        $this->fluentc_free = new FluentC_Free();
    }
    /**
     * Hooks for Autoloading
     *
     * @since 1.2
     */
    public function hooks()
    {
       // These hooks should always be active for the admin area
    add_action('admin_post_fluentc_save_settings_action', array($this, 'fluentc_admin_save_settings'));
    add_action('wp_ajax_fluentc_save_settings_action', array($this, 'ajax_save_api_key'));
    add_action('wp_ajax_fluentc_delete_api_key', array($this, 'ajax_delete_api_key'));
    add_action('admin_notices', array($this, 'check_fluentc_apikey'), 10, 1);
    add_action('admin_enqueue_scripts', array($this, 'fluentc_apikey_enqueue_script'), 10, 1);
    add_filter('query_vars', array($this, 'fluentc_var'), 10, 3);
    add_action('wp_ajax_dismiss_fluentc_apikey_warning', array($this, 'dismiss_fluentc_apikey_warning'));
    add_action('enqueue_block_editor_assets', array($this, 'fluentc_block_script'));
    add_action('init', array($this, 'register_fluentc_block'));
    add_action('fluentc_activation_setup', array($this, 'fluentc_setup'));
    add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    // Always add settings page links regardless of API key.
	add_action('plugin_action_links_fluentc-translation/fluentc_wordpress_plugin.php', array($this, 'add_settings_link'));
    
    add_action('wp_ajax_fluentc_api_call', array($this->fluentc_free, 'handle_api_call'));
	add_action('wp_ajax_fluentc_fetch_page_html', array($this->fluentc_free, 'handle_fetch_page_html'));
	add_action('wp_ajax_fluentc_get_language_options', array($this->fluentc_free, 'handle_get_language_options'));
	add_action('wp_ajax_fluentc_translate_content', array($this->fluentc_free, 'handle_translate_content'));
	add_action('wp_ajax_fluentc_get_translation_results', array($this->fluentc_free, 'handle_get_translation_results'));
	add_action('wp_ajax_fluentc_process_html', array($this->fluentc_free, 'handle_process_html'));

     // Handle live translation previews
     add_action('init', array($this->fluentc_free, 'handle_live_translation'));

    // Dashboard AJAX endpoints
    add_action('wp_ajax_fluentc_get_dashboard_data', array($this, 'ajax_get_dashboard_data'));
    add_action('wp_ajax_fluentc_sync_settings', array($this, 'ajax_sync_settings'));
    add_action('wp_ajax_fluentc_start_site_scan', array($this, 'ajax_start_site_scan'));
    add_action('wp_ajax_fluentc_get_scan_status', array($this, 'ajax_get_scan_status'));

    add_action('query_vars', function($vars) {
        $vars[] = 'translate';
        $vars[] = 'source';
        return $vars;
    });

    
      // Only add these hooks if API key is valid
      if ($this->fluentc_api->has_valid_api_key()) {
        add_action('wp_ajax_fluentc_generate_support_report', array($this, 'ajax_generate_support_report'));
        add_action('fluentc_admin_settings_page', array($this, 'get_fluentc_languages'));
        add_action('fluentc_admin_settings_page', array($this, 'fluentc_admin_get_settings'));
        add_action('fluentc_admin_tab_three_page', array($this, 'get_cache_form'));
        add_action('fluentc_admin_tab_three_page', array($this, 'get_support_report_section'));
        add_action('fluentc_admin_tab_one_page', array($this, 'get_scan_form'));
        add_action('fluentc_admin_settings_page_save', array($this, 'settings_save'));
        add_action('admin_post_fluentc_clean_cache_action', array($this, 'fluentc_admin_clean_cache'));
        add_action('admin_post_fluentc_scan_site_action', array($this, 'fluentc_admin_scan_site'));
        add_action('wp_update_nav_menu', array($this, 'update_menu_cache'));
        add_action('edited_category', array($this, 'update_menu_cache'), 10, 2);
        add_action('woocommerce_update_product', array($this, 'update_product_cache'), 10, 1);
        add_action('init', array($this, 'integrate_fluentc_languages'));
        add_action('admin_menu', array($this, 'fluentc_sub_menu'));
        add_action('wp_ajax_fluentc_inline_edit', array($this->translations, 'handle_inline_edit'));
        add_action('wp_ajax_fluentc_delete_translation', array($this->translations, 'handle_delete_translation'));
        add_action('wp_ajax_fluentc_search_translations', array($this->translations, 'handle_search_translations'));
        add_action('wp_ajax_fluentc_get_translations', array($this->translations, 'handle_get_translations'));
        add_action('wp_ajax_fluentc_get_sitemap', array($this, 'handle_get_sitemap'));
        add_action('wp_ajax_fluentc_validate_pages', array($this, 'handle_validate_pages'));
        add_action('wp_ajax_fluentc_get_latest_batch_status', array($this, 'handle_latest_batch_status'));
    }
      
    }
    /**
     * Set FluentC Vars
     *
     * @param mixed $vars WordPress vars.
     */
    public function fluentc_var( $vars )
    {
        $vars[] = 'fluentc'; // 'fluentc' is the name of path variable.
        return $vars;
    }

    /**
     * Adds a menu item to the WordPress admin dashboard for the plugin settings
     */
    public function fluentc_sub_menu()
    {
        add_submenu_page('fluentc-settings', 'Edit Translations', 'Edit Translations', 'manage_options', 'fluentc-manage-translations', array($this->translations, 'display_translations_page'));
    }

    /**
     * Adds scripts to Management Page
     */
    public function enqueue_admin_scripts($hook)
    {
    
            $this->translations->enqueue_scripts();
    
    }
    /**
	 * 
	 *  Add settings link to plugins page
	 */
public function add_settings_link($links) {
    $settings_link = '<a href="' . admin_url('admin.php?page=fluentc-settings') . '">' . 
                     __('Settings', 'fluentc-translation') . '</a>';
    array_unshift($links, $settings_link);
    return $links;
}
    /**
     * GET from fluentc.ai
     */
    public function fluentc_admin_get_settings()
    {
        if (isset($_GET['fluentc']) ) {
            $api_key = sanitize_text_field(wp_unslash($_GET['fluentc']));
            $this->save_settings($api_key);
            $this->fluentc_cache->clean();
            wp_safe_redirect(admin_url('admin.php?page=fluentc-settings'));
            exit;
        }
    }
    /**
     * Save Function sanitize_text_field( wp_unslash( $_POST['faq_highlighted'] ) )
     */
    public function fluentc_admin_save_settings()
    {
        if (isset($_POST['submit']) ) {
            if (isset($_POST['fluentc_settings_nonce_field']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['fluentc_settings_nonce_field'])), 'fluentc_save_settings_action') ) {
                try {
                    $api_key = isset($_POST['fluentc_api_key']) ? sanitize_text_field(wp_unslash($_POST['fluentc_api_key'])) : '';
                    $this->save_settings($api_key);
                    add_settings_error('fluentc-settings', 'fluentc_api_key_saved', 'FluentC API key saved.', 'updated');
                    do_action('fluentc_admin_settings_page_save');
                    wp_safe_redirect(admin_url('admin.php?page=fluentc-settings'));
                    exit;
                } catch ( \Exception $e ) {
                    add_settings_error('fluentc-settings', 'fluentc_api_key_error', 'Error saving FluentC API key: ' . $e->getMessage(), 'error');
                }
            } else {
                // Handle the case where the nonce check fails.
                wp_die('Security check failed');
            }
        }
    }
    /**
     * Handle getting sitemap from WordPress
     */
    public function handle_validate_pages() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
    
        if (empty($_POST['page_urls'])) {
            wp_send_json_error('No page URLs provided.');
            return;
        }
    
        // The URLs are sent as a JSON string from FormData
        $page_urls_json = wp_unslash($_POST['page_urls']);
        $page_urls = json_decode($page_urls_json, true);
    
        if (!is_array($page_urls) || empty($page_urls)) {
            wp_send_json_error('Invalid format for page URLs.');
            return;
        }
    
        $api_key = get_option('fluentc_api_key');
        if (empty($api_key)) {
            wp_send_json_error('FluentC API Key is not set.');
            return;
        }
    
        $languages = $this->fluentc_connect->get_display_language_list($api_key);
        if (empty($languages)) {
            wp_send_json_error('No translation languages are configured in FluentC.');
            return;
        }
    
        // Determine source language to exclude it from testing
        $source_language = substr(get_locale(), 0, 2);

        // Filter out the source language to get only target languages
        $target_languages = array_values(array_filter($languages, function ($language) use ($source_language) {
            // $language is an array e.g., ['German', 'de']
            return isset($language[1]) && $language[1] !== $source_language;
        }));

        if (empty($target_languages)) {
            wp_send_json_error('No target languages are configured for validation. Please add a language other than the source language.');
            return;
        }
    
        // Pick the first available target language for testing
        $test_lang_code = $target_languages[0][1];
        $all_lang_codes = wp_list_pluck($languages, 1);
        $results = [];
    
        foreach ($page_urls as $page_url) {
            $sanitized_url = esc_url_raw($page_url);
            $path = wp_parse_url($sanitized_url, PHP_URL_PATH);
            if (is_null($path)) {
                $path = '/';
            }
    
            // Remove any existing language code from the path to avoid duplication
            $path_parts = explode('/', trim($path, '/'));
            if (!empty($path_parts) && in_array($path_parts[0], $all_lang_codes)) {
                array_shift($path_parts);
                $path = '/' . implode('/', $path_parts);
            }
    
            $translated_url = home_url(trailingslashit($test_lang_code) . ltrim($path, '/'));
    
            $response = wp_remote_get($translated_url, ['timeout' => 15]);
    
            $result_item = [
                'original_url' => $sanitized_url,
                'tested_url'   => $translated_url,
            ];
    
            if (is_wp_error($response)) {
                $result_item['status'] = 'error';
                $result_item['message'] = $response->get_error_message();
            } else {
                $status_code = wp_remote_retrieve_response_code($response);
                $result_item['status'] = $status_code;
                if ($status_code === 200) {
                    $result_item['message'] = 'Page is accessible and returns a 200 status.';
                } else {
                    $result_item['message'] = 'Page returned HTTP status ' . $status_code . '.';
                }
            }
            $results[] = $result_item;
        }
    
        $all_pages_valid = !empty($results) && !array_filter($results, static function ($result_item) {
            if (!isset($result_item['status'])) {
                return true;
            }

            // Cast numeric status codes and treat non-200 or error states as failures.
            return (int) $result_item['status'] !== 200;
        });

        if ($all_pages_valid) {
            update_option('fluentc_validation_completed_at', time());
        }

        wp_send_json_success($results);
    }

    /**
     * Handle getting sitemap from WordPress
     */
    public function handle_get_sitemap() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }

        $sitemaps = ['wp-sitemap.xml', 'sitemap_index.xml', 'sitemap.xml'];
        $found_urls = [];

        foreach ($sitemaps as $sitemap_file) {
            $sitemap_url = home_url('/' . $sitemap_file);
            $response = wp_remote_get($sitemap_url, array('timeout' => 15));

            if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
                continue;
            }
            
            $sitemap_content = wp_remote_retrieve_body($response);

            if (empty($sitemap_content)) {
                continue;
            }

            libxml_use_internal_errors(true);
            $xml = simplexml_load_string($sitemap_content);
            libxml_clear_errors();

            if ($xml === false) {
                continue;
            }

            $urls_to_parse = [];
            // Check if it's a sitemap index
            if (isset($xml->sitemap[0])) {
                $first_sitemap_url = (string)$xml->sitemap[0]->loc;
                $child_response = wp_remote_get($first_sitemap_url, array('timeout' => 15));
                if (!is_wp_error($child_response) && wp_remote_retrieve_response_code($child_response) === 200) {
                    $child_sitemap_content = wp_remote_retrieve_body($child_response);
                    
                    libxml_use_internal_errors(true);
                    $child_xml = simplexml_load_string($child_sitemap_content);
                    libxml_clear_errors();

                    if ($child_xml && isset($child_xml->url)) {
                       $urls_to_parse = $child_xml->url;
                    }
                }
            } elseif (isset($xml->url)) { // It's a regular sitemap
                $urls_to_parse = $xml->url;
            }
            
            foreach($urls_to_parse as $url_entry) {
                if (count($found_urls) < 5) {
                    $found_urls[] = (string)$url_entry->loc;
                } else {
                    break;
                }
            }

            // If we found any URLs, we are done.
            if (!empty($found_urls)) {
                break;
            }
        }

        if (!empty($found_urls)) {
            wp_send_json_success([
                'message' => 'Sitemap URLs fetched successfully.',
                'urls' => $found_urls
            ]);
        } else {
            wp_send_json_error('A valid sitemap was not found.');
        }
    }

    /**
     * Handle getting latest batch status
     */
    public function handle_latest_batch_status() {
        // Verify nonce.
        if (!wp_verify_nonce($_POST['nonce'], 'fluentc_nonce')) {
            wp_send_json_error('Security check failed');
            return;
        }
        try {
            // Use the site_id from the request if provided, otherwise fall back to the stored API key.
            $site_id = !empty($_POST['site_id']) ? sanitize_text_field($_POST['site_id']) : get_option('fluentc_api_key');
            
            if (empty($site_id)) {
                $site_id = get_option('fluentc_api_key');
                if (empty($site_id)) {
                    
                    wp_send_json_error(array('message' => 'Could not determine Site ID (API Key).'));
                    return;
                }
                
            }

            $response = $this->fluentc_connect->get_latest_batch_status($site_id);
            error_log(print_r($response, true));
            wp_send_json_success($response);
        } catch (\Exception $e) {
            wp_send_json_error(array('message' => 'Error getting latest batch status: ' . $e->getMessage()));
        }
    }

    /**
     * Handle AJAX request to save API key
     *
     * @since 1.2.1
     */
    public function ajax_save_api_key() {
        $nonce = isset($_POST['fluentc_settings_nonce_field']) ? sanitize_text_field(wp_unslash($_POST['fluentc_settings_nonce_field'])) : '';
    
        if (!wp_verify_nonce($nonce, 'fluentc_save_settings_action')) {
            wp_send_json_error(array('message' => 'Security check failed. Please refresh and try again.'), 403);
        }
    
        try {
            $api_key = isset($_POST['fluentc_api_key']) ? sanitize_text_field(wp_unslash($_POST['fluentc_api_key'])) : '';
            
            // Validate API key format if not empty
            if (!empty(trim($api_key))) {
                $trimmed_key = trim($api_key);
                
                // Check if they're trying to save the free API key
                if ($trimmed_key === '13c25c70-a4fa-4232-9d2c-1c451e71c3b7') {
                    wp_send_json_error(array('message' => 'The free testing API key cannot be saved. Please use your own FluentC API key.'), 400);
                    return;
                }
                
                if (!$this->validate_api_key_format($api_key)) {
                    wp_send_json_error(array('message' => 'Invalid API key format. Expected UUID format: 12345678-1234-1234-1234-123456789012'), 400);
                    return;
                }
            }
            
            $this->save_settings($api_key);
            wp_send_json_success(array('message' => 'API Key saved.'));
        } catch (\Exception $e) {
            wp_send_json_error(array('message' => 'Error saving FluentC API key: ' . $e->getMessage()), 500);
        }
    }

    /**
     * Handle AJAX request to delete API key
     *
     * @since 1.2.1
     */
    public function ajax_delete_api_key() {
        // Check user capabilities first
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to perform this action.'), 403);
            return;
        }
        
        // Check nonce - try both possible nonce fields
        $nonce = '';
        if (isset($_POST['nonce'])) {
            $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        } elseif (isset($_POST['fluentc_settings_nonce_field'])) {
            $nonce = sanitize_text_field(wp_unslash($_POST['fluentc_settings_nonce_field']));
        }
        
        // Verify nonce - try multiple nonce actions for compatibility
        $nonce_valid = false;
        if (!empty($nonce)) {
            $nonce_valid = wp_verify_nonce($nonce, 'fluentc_nonce') || 
                          wp_verify_nonce($nonce, 'fluentc_save_settings_action');
        }
        
        if (!$nonce_valid) {
            wp_send_json_error(array('message' => 'Security check failed. Please refresh the page and try again.'), 403);
            return;
        }
    
        try {
            // Clear the API key by setting it to empty
            $this->save_settings('');
            
            // Clear additional validation flags
            delete_option('fluentc_api_key_validated');
            delete_option('fluentc_api_key_validation_message');
            delete_option('fluentc_api_key_validation_time');
            
            wp_send_json_success(array('message' => 'API Key deleted successfully.'));
        } catch (\Exception $e) {
            error_log('FluentC: Error deleting API key: ' . $e->getMessage());
            wp_send_json_error(array('message' => 'Error deleting FluentC API key: ' . $e->getMessage()), 500);
        }
    }

    /**
     * Validate API key format
     *
     * @param string $api_key The API key to validate
     * @return bool True if format is valid
     */
    private function validate_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 UUID format validation - adjust pattern as needed for your API key format
        $pattern = '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i';
        return preg_match($pattern, $trimmed_key) === 1;
    }

    /**
     * Empty Cache
     */
    public function fluentc_admin_scan_site()
    {
        $scan_site_nonce_field = sanitize_text_field(wp_unslash($_POST['fluentc_scan_site_nonce_field'] ?? null));

        if (isset($_POST['submit']) && isset($scan_site_nonce_field) && wp_verify_nonce($scan_site_nonce_field, 'fluentc_scan_site_action') ) {
            try {
                $this->fluentc_processor->scan_and_send_urls_translate();
                do_action('fluentc_admin_scan_site');
                wp_safe_redirect(admin_url('admin.php?page=fluentc-settings'));
                exit;
            } catch ( \Exception $e ) {
            }
        } else {
            // Handle the case where the nonce check fails.
            wp_die('Security check failed');
        }
    }
    /**
     * Empty Cache
     */
    public function fluentc_admin_clean_cache()
    {
        $clean_cache_nonce_field = sanitize_text_field(wp_unslash($_POST['fluentc_clean_cache_nonce_field'] ?? null));

        if (isset($_POST['submit']) && isset($clean_cache_nonce_field) && wp_verify_nonce($clean_cache_nonce_field, 'fluentc_clean_cache_action') ) {
            try {
                $this->fluentc_cache->clean();
                do_action('fluentc_admin_clean_cache');
                wp_safe_redirect(admin_url('admin.php?page=fluentc-settings'));
                exit;
            } catch ( \Exception $e ) {
                add_settings_error('fluentc-settings', 'fluentc_api_key_error', 'Error Clearing Cache: ' . $e->getMessage(), 'error');
            }
        } else {
            // Handle the case where the nonce check fails.
            wp_die('Security check failed');
        }
    }
    /**
     * Sets up the FluentC account
     */
    public function fluentc_setup( )
    {
        // Get API key (can be null)
        $widgetapikey = get_option('fluentc_api_key', null);

        // Send heartbeat regardless of whether API key is set
        $this->fluentc_connect->heartbeat($widgetapikey);
    }

    /**
     * Saves the user's FluentC API key to the WordPress database
     *
     * @param string $api_key FluentC Key.
     */
    public function save_settings($api_key) {
        $old_api_key = get_option('fluentc_api_key', '');
        
        // Trim the API key to remove any whitespace
        $api_key = trim($api_key);
        
        // Only proceed with cache clearing if the API key has changed
        if ($old_api_key !== $api_key) {
            // Update the API key in WordPress options
            update_option('fluentc_api_key', $api_key);
            
            // Clear validation flags when key changes
            if (empty($api_key)) {
                // If API key is being cleared/deleted
                update_option('fluentc_api_key_validated', false);
                delete_option('fluentc_api_key_validation_message');
                delete_option('fluentc_api_key_validation_time');
            } else {
                // Reset validation status for new key
                delete_option('fluentc_api_key_validated');
                delete_option('fluentc_api_key_validation_message');
                delete_option('fluentc_api_key_validation_time');
            }
            
            // Clear all cached data related to languages and widget options
            if (isset($this->fluentc_cache)) {
                // Clear specific caches related to the old API key
                if (!empty($old_api_key)) {
                    $this->fluentc_cache->delete('regex_lang_' . $old_api_key, 'languages');
                    $this->fluentc_cache->delete('widget_options_' . $old_api_key, 'languages');
                    $this->fluentc_cache->delete('available_languages_' . $old_api_key, 'languages');
                    $this->fluentc_cache->delete('api_key_validation_' . md5($old_api_key), 'settings');
                }
                
                // Clear language group cache entirely to ensure fresh start
                $this->fluentc_cache->clean('languages');
                
                // Also clear settings cache which might contain API-dependent data
                $this->fluentc_cache->clean('settings');
                
                // Log if debugging is enabled
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('FluentC: Cache cleared after API key update');
                }
            }
            
            // Set a flag to flush rewrite rules since URL handling may change with new languages
            update_option('fluentc_need_flush_rewrite', true);
            
            // Fire action for additional cache clearing by other components
            do_action('fluentc_api_key_changed', $api_key, $old_api_key);
        } else {
            // Update the option anyway to refresh timestamp
            update_option('fluentc_api_key', $api_key);
        }
    }
    
    /**
     * Update all cache when the menu is updated
     */
    public function update_menu_cache()
    {

        $this->fluentc_cache->clean();
    }

    /**
     * Update all cache when the category is updated
     *
     * @param int $term_id taxonomy term.
     * @param int $tt_id   ttid.
     */
    public function update_category_cache( $term_id, $tt_id )
    {

        $this->fluentc_cache->clean();
    }

    /**
     * Update all cache when the product is updated
     *
     * @param int $product_id id of the product.
     */
    public function update_product_cache( $product_id )
    {

        // getall Language combinations.
        $this->fluentc_cache->clean();
    }
    /**
     * Update all cache when the pages and post is updated
     *
     * @param int $id id of the post.
     */
    public function update_post_and_pages( $id )
    {
        // Loop.
        // Source Lang . dispalyLange[1] . id.
        // Add_action publish_page.
        // add_action publish_pust.
        // Update the cache when a post is saved.
        $this->fluentc_cache->clean();
    }
    /**
     * GetFluentCLanguages and return them in table form
     */
    public function get_fluentc_languages()
    {
        $widgetapikey = get_option('fluentc_api_key');
        if ($widgetapikey ) {
            ?>
            <table class="wp-list-table widefat fixed">
                <thead>
                    <tr>
                        <td class="column-primary">Language</td>
                        <td class="column-name">Language Code</td>
                    </tr>
                </thead>
                <tbody>
            <?php
            $languages = $this->fluentc_connect->get_display_language_list($widgetapikey);

            foreach ( $languages as $language ) {
                ?>
                        <tr>
                            <td>
                <?php echo esc_html($language[0]); ?>
                            </td>
                            <td>
                <?php echo esc_html($language[1]); ?>
                            </td>
                        </tr>
                <?php
            }
            ?>
                </tbody>
            </table>
            <?php
        } else {
            echo esc_html('FluentC API Key Not Set');
        } 
        
    }

    /**
     * Return the Cache form
     */
    public function get_cache_form()
    {
        $action_url = esc_url(admin_url('admin-post.php'));

        ?>
        <hr />
        <h3>If you have made changes at FluentC.ai, Clearing Cache will update</h3>
        <form method="post" action='<?php echo esc_html($action_url); ?>'>

        <?php
        // Directly call wp_nonce_field to output its content.
        wp_nonce_field('fluentc_clean_cache_action', 'fluentc_clean_cache_nonce_field');
        ?>
            <input type="hidden" name="action" value="fluentc_clean_cache_action">
            <p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="Clear Cache">
            </p>
        </form>
        <h3>FluentC API Calls : <?php $apicalls = $this->fluentc_cache->get('apicalls', 'settings'); echo esc_html($apicalls); ?></h3>
        <button id="fluentc-scan-site" class="button button-primary" title="<?php _e('Scan your site to see all available pages for translation.', 'fluentc-translation'); ?>">
            <?php _e('Identify Pages for Translation', 'fluentc-translation'); ?>
        </button>
        <?php
    }

      /**
     * Return the scan form
     */
    public function get_scan_form()
    {
        echo "<hr/>";
        $fluentc_batch_request = $this->fluentc_cache->get('fluentc_batch_request','urls');
        if($fluentc_batch_request)
        { 
            ?><h3>Translation Progress: <?php
            $batch_status = $this->fluentc_processor->fetchJobStatus($fluentc_batch_request); 
            if(!$batch_status) {
            echo "No Batch Status";
            }
            else {
                $fluentc_batch_status = $batch_status->status;
                echo esc_html($fluentc_batch_status) ." </h3>"; 
             if('completed' != $fluentc_batch_status) {
                echo "Total Pages: ".$batch_status->totalSteps. "<br/>";
                echo "Total Pages Scanned: ".$batch_status->completedSteps. "<br/>";
                echo "Refresh to check status";
             }
             else {
                echo "Total Pages Scanned: ".$batch_status->totalSteps. "<br/>";
                echo "Date Last Scanned: ".$batch_status->createdAt. "<br/>";
    
            }
           
        }
    }
    else {
       
        echo "Start Translation Scan. Refresh for update";
    }
    }
    /**
     * Check if API Key is set
     */
    public function check_fluentc_apikey()
    {
        // Check if the user has dismissed the notice and if the dismissal period is still active.
        if (get_transient('fluentc_apikey_dismissed') ) {
            return;
        }

        // Check if the API key is stored in the settings.
        $widgetapikey = get_option('fluentc_api_key');
        if (empty($widgetapikey) ) {
            ?>
            <div class="notice notice-warning is-dismissible">
            <?php _e('<p><strong>FluentC API Key is missing.</strong> Please add your API key in settings to use the FluentC features.</p>', 'fluentc-translation'); ?>
            </div>
            <?php
            add_action('admin_notices', array( $this, 'fluentc_apikey_enqueue_script' ), 10, 1);
        }
    }

    /**
     * Script to update API Notice dismiss
     */
    public function fluentc_apikey_enqueue_script()
    {
        // Attach inline handler to an actual core script handle (avoid registering a script with null src).
        wp_enqueue_script( 'jquery' );
        wp_add_inline_script(
            'jquery',
            '
			jQuery(document).ready(function($) {
				$(document).on("click", ".notice-warning.is-dismissible button.notice-dismiss", function() {
					$.post(ajaxurl, {
						action: "dismiss_fluentc_apikey_warning"
					});
				});
			});
		'
        );
    }
    /**
     * Set transient to dismiss message for 7 days
     */
    public function dismiss_fluentc_apikey_warning()
    {
        // Set a transient for 7 days.
        set_transient('fluentc_apikey_dismissed', 'yes', 7 * DAY_IN_SECONDS);
        wp_die(); // This is required to terminate immediately and return a proper response.
    }

    /**
     * Handle the saving settings
     */
    public function settings_save()
    {
        // Validate Widget Key.
        $widgetapikey = get_option('fluentc_api_key');
        $languages    = $this->fluentc_connect->get_display_language_list($widgetapikey);
        if ($languages ) {
            //$this->fluentc_processor->scan_and_send_urls_translate();
            wp_safe_redirect(admin_url('admin.php?page=fluentc-settings'));
            exit;
        } else {
            echo esc_html('<strong>Widget has no languages setup, please visit FluentC and enable a language to translate</strong>');
        }
    }

    // Register the block script.
    public function fluentc_block_script()
    {
        wp_enqueue_script('fluentc-block-script', plugins_url('/include/script.js', __FILE__), array( 'wp-blocks' ), '1.0', true);
    }


    // Register the Block.
    public function register_fluentc_block()
    {
        register_block_type(
            'fluentc/fluentc-block',
            array(
            'editor_script'   => 'fluentc-block-script',
            'render_callback' => 'fluentc_block_render_callback',
            )
        );
    }

    // Render Callback Function
    public function fluentc_block_render_callback( $attributes )
    {
        return '<div id="fluentc-widget"></div>';
    }

    /**
     * Retrieve Available Language by Site Key and Insert into WordPress
     *
     * @return void
     * @since  1.2
     * @param  string $environment_id FluentC Environment ID.
     */
    public function integrate_fluentc_languages( )
    {
        $widgetapikey = get_option('fluentc_api_key');
        if(!$widgetapikey){
            return;
        }
        $languages = $this->fluentc_connect->get_display_language_list($widgetapikey);

        if (is_null($languages)) {
            return;
        }
        foreach ($languages as $language) {
            $name = $language[0];
            $slug = $language[1];

            // Check if the language term already exists.
            if (!term_exists($slug, 'language')) {
                wp_insert_term($name, 'language', array('slug' => $slug));
            }
        }
    
    }

    /**
 * AJAX handler for generating support report
 */
public function ajax_generate_support_report() {
    // Check nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'fluentc_support_report_nonce')) {
        wp_send_json_error('Invalid security token');
        return;
    }
    
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to perform this action');
        return;
    }
    
    try {
        // Initialize support report service
        $report_service = new \FluentC\Services\Support_Report();
        
        // Generate report
        $report = $report_service->generate_report();
        
        // Log that a support report was generated
        if (!empty($report)) {
            error_log('FluentC: Support report generated by user ' . get_current_user_id());
            // Optional: Track reports with a timestamp
            update_option('fluentc_last_support_report', current_time('mysql'));
        }
        
        // Send response
        wp_send_json_success($report);
    } catch (\Exception $e) {
        error_log('FluentC: Error generating support report: ' . $e->getMessage());
        wp_send_json_error('Error generating report: ' . $e->getMessage());
    }
    
    // This line should never be reached but added for completeness
    wp_die();
}

/**
     * Display notices related to API key validation
     */
    public function display_api_key_validation_notices() {
        // Skip on the settings page
        if (function_exists('get_current_screen') && get_current_screen()->id === 'toplevel_page_fluentc-settings') {
            return;
        }
        
        $api_key = get_option('fluentc_api_key', '');
        if (empty($api_key)) {
            return; // No key set, the other notice will handle this
        }
        
        // Check validation status
        $api_key_validated = get_option('fluentc_api_key_validated', false);
        
        if ($api_key && !$api_key_validated) {
            $validation_message = get_option('fluentc_api_key_validation_message', 'API key validation failed');
            echo '<div class="notice notice-error is-dismissible">';
            echo '<p><strong>FluentC API Key Error:</strong> ' . esc_html($validation_message) . '</p>';
            echo '<p>Please <a href="' . admin_url('admin.php?page=fluentc-settings') . '">check your API key</a> or contact FluentC support for assistance.</p>';
            echo '</div>';
        }
    }
/**
 * Future implementation: AJAX handler for submitting support report to FluentC
 * This function is a placeholder for future functionality
 */
public function ajax_submit_support_report() {
    // Check nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'fluentc_support_report_nonce')) {
        wp_send_json_error('Invalid security token');
        return;
    }
    
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to perform this action');
        return;
    }
    
    // This feature will be implemented in a future update
    wp_send_json_error('This feature is not yet implemented');
    
    wp_die();
}
    /**
 * Add support report section to the Advanced tab
 */
public function get_support_report_section() {
    ?>
    <hr />
    <h3>Support Report</h3>
    <p>
        Generate a diagnostic report to help FluentC support team troubleshoot issues with your installation.
        This report includes information about your WordPress setup, server environment, plugin configuration, and FluentC settings.
    </p>
    
    <div class="fluentc-support-info">
        <details>
            <summary>What information is included in the report?</summary>
            <ul>
                <li><strong>WordPress Information:</strong> Version, site URL, multisite status, memory limit, debug mode, locale, and timezone</li>
                <li><strong>Server Information:</strong> PHP version, server software, loaded extensions, database version, and PHP configuration</li>
                <li><strong>Plugin Information:</strong> List of installed plugins with their versions and activation status</li>
                <li><strong>FluentC Information:</strong> Version, API key (partially masked), language settings, and cache data</li>
                <li><strong>Permalink Information:</strong> Structure settings and configuration</li>
                <li><strong>Rewrite Rules:</strong> Active WordPress rewrite rules that may affect URL handling</li>
            </ul>
            <p><em>Note: Your API key will be partially masked for security.</em></p>
        </details>
    </div>
    
    <div class="fluentc-support-actions">
        <button id="fluentc-generate-report" class="button button-primary">Generate Support Report</button>
        <span id="fluentc-report-loading" style="display: none; margin-left: 10px;">
            <img src="<?php echo admin_url('images/spinner.gif'); ?>" alt="Loading..." />
            Generating report...
        </span>
    </div>
    
    <div id="fluentc-report-result" style="display: none; margin-top: 20px;">
        <h4>Support Report</h4>
        <div class="fluentc-report-instructions">
            <p>Please choose one of the following options to send your diagnostic report to FluentC support:</p>
            
            <div class="fluentc-report-actions">
                <div class="fluentc-report-action">
                    <h5>Option 1: Email the report</h5>
                    <p>Copy the report and email it to <a href="mailto:support@fluentc.ai">support@fluentc.ai</a></p>
                    <button id="fluentc-copy-report" class="button button-secondary">Copy Report to Clipboard</button>
                    <span id="fluentc-copy-success" style="display: none; color: green; margin-left: 10px;">Copied!</span>
                </div>
                
                <div class="fluentc-report-action">
                    <h5>Option 2: Submit directly to FluentC</h5>
                    <p>Send the report directly to FluentC support (Coming soon)</p>
                    <button id="fluentc-submit-report" class="button button-primary" disabled>Submit Report to FluentC</button>
                    <span id="fluentc-submit-note" style="color: #888; margin-left: 10px;">This feature will be available in future updates</span>
                </div>
                
                <div class="fluentc-report-action">
                    <h5>Option 3: Download as JSON file</h5>
                    <p>Download the report as a JSON file to share later</p>
                    <button id="fluentc-download-report" class="button button-secondary">Download Report</button>
                </div>
            </div>
        </div>
        
        <div class="fluentc-report-preview">
            <h5>Report Preview:</h5>
            <textarea id="fluentc-report-content" style="width: 100%; height: 300px; font-family: monospace; margin-top: 10px;" readonly></textarea>
        </div>
    </div>
    
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        var reportData = null;
        
        $('#fluentc-generate-report').on('click', function() {
            var $button = $(this);
            var $loading = $('#fluentc-report-loading');
            var $result = $('#fluentc-report-result');
            var $content = $('#fluentc-report-content');
            
            $button.prop('disabled', true);
            $loading.show();
            $result.hide();
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fluentc_generate_support_report',
                    nonce: '<?php echo wp_create_nonce('fluentc_support_report_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        reportData = response.data;
                        $content.val(JSON.stringify(reportData, null, 2));
                        $result.show();
                    } else {
                        alert('Failed to generate report: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function() {
                    alert('Failed to connect to the server. Please try again later.');
                },
                complete: function() {
                    $button.prop('disabled', false);
                    $loading.hide();
                }
            });
        });
        
        $('#fluentc-copy-report').on('click', function() {
            var $content = $('#fluentc-report-content');
            var $success = $('#fluentc-copy-success');
            
            $content.select();
            document.execCommand('copy');
            
            $success.show();
            setTimeout(function() {
                $success.fadeOut();
            }, 2000);
        });
        
        $('#fluentc-download-report').on('click', function() {
            if (!reportData) {
                alert('No report data available. Please generate a report first.');
                return;
            }
            
            // Create a JSON blob and download it
            var dataStr = JSON.stringify(reportData, null, 2);
            var dataBlob = new Blob([dataStr], {type: 'application/json'});
            
            // Create a download link and click it
            var downloadLink = document.createElement('a');
            downloadLink.setAttribute('href', URL.createObjectURL(dataBlob));
            downloadLink.setAttribute('download', 'fluentc-support-report-' + formatDate(new Date()) + '.json');
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        });
        
        // Helper function to format date for filename
        function formatDate(date) {
            var year = date.getFullYear();
            var month = ('0' + (date.getMonth() + 1)).slice(-2);
            var day = ('0' + date.getDate()).slice(-2);
            var hours = ('0' + date.getHours()).slice(-2);
            var minutes = ('0' + date.getMinutes()).slice(-2);
            return year + '-' + month + '-' + day + '-' + hours + minutes;
        }
    });
    </script>
    
    <style type="text/css">
    .fluentc-support-info {
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 20px;
        border-left: 4px solid #1E90FF;
    }
    .fluentc-support-info details {
        margin-bottom: 10px;
    }
    .fluentc-support-info summary {
        cursor: pointer;
        font-weight: bold;
        margin-bottom: 10px;
        color: #1E5D94;
    }
    .fluentc-support-info ul {
        margin-left: 20px;
        list-style-type: disc;
    }
    .fluentc-report-instructions {
        margin-bottom: 20px;
    }
    .fluentc-report-instructions p {
        margin-bottom: 15px;
    }
    .fluentc-report-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 20px;
    }
    .fluentc-report-action {
        flex: 1 1 300px;
        background-color: #fff;
        padding: 15px;
        border-radius: 5px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        border: 1px solid #e5e5e5;
    }
    .fluentc-report-action h5 {
        margin-top: 0;
        color: #1E5D94;
        font-size: 16px;
        margin-bottom: 10px;
    }
    .fluentc-report-action p {
        margin-bottom: 15px;
        color: #555;
    }
    .fluentc-report-preview {
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 5px;
        border: 1px solid #e5e5e5;
    }
    .fluentc-report-preview h5 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #1E5D94;
    }
    #fluentc-report-content {
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 3px;
    }
    #fluentc-generate-report {
        background-color: #1E90FF;
        color: white;
        border-color: #0059b3;
    }
    #fluentc-generate-report:hover {
        background-color: #0074D9;
    }
    #fluentc-report-loading {
        display: inline-flex;
        align-items: center;
    }
    </style>
    <?php
}

    /**
     * AJAX handler to get all necessary data for the dashboard.
     *
     * @since 1.2.1
     */
    public function ajax_get_dashboard_data() {
        if (!current_user_can('manage_options') || !check_ajax_referer('fluentc_dashboard_nonce', 'nonce', false)) {
            wp_send_json_error(array('message' => 'Security check failed.'), 403);
        }

        $api_key = get_option('fluentc_api_key');
        if (empty($api_key)) {
            wp_send_json_error(array('message' => 'API Key not found'), 401);
        }
        
        $languages = $this->fluentc_connect->get_display_language_list($api_key);
        $job_status = $this->get_current_job_status();
        $validation_completed_at = (int) get_option('fluentc_validation_completed_at', 0);

        wp_send_json_success(array(
            'languages' => $languages,
            'jobStatus' => $job_status,
            'validationCompletedAt' => $validation_completed_at,
            'hasCompletedValidation' => $validation_completed_at > 0,
        ));
    }

    /**
     * AJAX handler to clear cache (Sync Settings).
     *
     * @since 1.2.1
     */
    public function ajax_sync_settings() {
        if (!current_user_can('manage_options') || !check_ajax_referer('fluentc_dashboard_nonce', 'nonce', false)) {
            wp_send_json_error('Security check failed', 403);
        }

        try {
            $this->fluentc_cache->clean();
            wp_send_json_success(array('message' => 'Settings have been synchronized.'));
        } catch (\Exception $e) {
            wp_send_json_error('Error clearing cache: ' . $e->getMessage(), 500);
        }
    }

    /**
     * AJAX handler to start a new site scan.
     *
     * @since 1.2.1
     */
    public function ajax_start_site_scan() {
        if (!current_user_can('manage_options') || !check_ajax_referer('fluentc_dashboard_nonce', 'nonce', false)) {
            wp_send_json_error('Security check failed', 403);
        }

        // Prevent starting a new scan if one is already active
        $existing_job = $this->get_current_job_status();
        if (isset($existing_job['status']) && in_array($existing_job['status'], ['processing', 'queued'])) {
            wp_send_json_error(array('message' => 'A scan is already in progress.'), 409);
            return;
        }

        try {
            $jobId = $this->fluentc_processor->scan_and_send_urls_translate();
            if (!$jobId) {
                throw new \Exception("Failed to get Job ID from translation service.");
            }
            wp_send_json_success(array('message' => 'Site scan initiated.', 'jobId' => $jobId));
        } catch (\Exception $e) {
            wp_send_json_error('Error starting site scan: ' . $e->getMessage(), 500);
        }
    }
    
    /**
     * AJAX handler to get the current scan status.
     *
     * @since 1.2.1
     */
    public function ajax_get_scan_status() {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }

        $status = $this->get_current_job_status();
        wp_send_json_success($status);
    }

    /**
     * Helper to get current job status.
     *
     * @return array|null
     */
    private function get_current_job_status() {
        $job_id = $this->fluentc_cache->get('fluentc_batch_request','urls');
        if ($job_id) {
            $status = (array) $this->fluentc_connect->fetch_job_status($job_id);
            if (!empty($status)) {
                // Ensure jobId is always present in the response if a job exists
                if (!isset($status['jobId'])) {
                    $status['jobId'] = $job_id;
                }
                return $status;
            }
        }
        return ['status' => 'unknown'];
    }
}
