<?php
/**
 * FluentC WordPress Translation Status Page
 *
 * This file contains the adjustments for the Translation Status functionality
 *
 * @package FluentCPlugin
 * @author  FluentC <wp@fluentc.io>
 */

namespace FluentC\Actions;

use FluentC\Models\Hooks;
use FluentC\Services\Scan;
use FluentC\Services\Connect;
use FluentC\Services\Translation_Processor;
use FluentC\Utils\Language;

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

class Translationstatus implements Hooks {

    /**
     * FluentC scan class
     *
     * @var Scan
     */
    protected $fluentc_scan;

    /**
     * FluentC connect class
     *
     * @var Connect
     */
    protected $fluentc_connect;

    /**
     * FluentC language class
     *
     * @var Language
     */
    protected $fluentc_language;

    /**
     * FluentC translation processor class
     *
     * @var Translation_Processor
     */
    protected $fluentc_processor;

    /**
     * Constructor
     */
    public function __construct() {
        $this->fluentc_scan = new Scan();
        $this->fluentc_language = new Language();
        $this->fluentc_connect = new Connect();
        $this->fluentc_processor = new Translation_Processor();
    }

    /**
     * Register WordPress hooks
     */
    public function hooks() {
        //add_action('admin_menu', [$this, 'addTranslationStatusSubMenu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueAssets']);
        add_action('wp_ajax_fluentc_scan_site', [$this, 'ajaxScanSite']);
        add_action('wp_ajax_fluentc_toggle_url_status', [$this, 'ajaxToggleUrlStatus']);
        add_action('wp_ajax_fluentc_get_last_scan_time', [$this, 'ajaxGetLastScanTime']);
        add_action('wp_ajax_fluentc_get_translation_table', [$this, 'ajaxGetTranslationTable']);
        add_action('wp_ajax_fluentc_translate_site', [$this, 'ajaxTranslateSite']);
        add_action('wp_ajax_fluentc_get_saved_urls', [$this, 'ajaxGetSavedUrls']);
        add_action('wp_ajax_fluentc_cancel_translation', [$this, 'ajaxCancelTranslation']);
        add_action('wp_ajax_fluentc_get_translation_status', [$this, 'ajaxGetTranslationStatus']);
        add_action('fluentc_process_translated_urls', [$this->fluentc_processor, 'processTranslatedUrls']);
    }

    /**
     * Add Translation Status submenu
     */
    public function addTranslationStatusSubMenu() {
        add_submenu_page(
            'fluentc-settings',
            __('Translation Status', 'fluentc-translation'),
            __('Translation Status', 'fluentc-translation'),
            'manage_options',
            'fluentc-translation-status',
            [$this, 'renderTranslationStatusPage']
        );
    }

    /**
     * Render Translation Status page
     */
    public function renderTranslationStatusPage() {
        include plugin_dir_path(__FILE__) . '../templates/translation-status.php';
    }

    /**
     * Enqueue assets for Translation Status page
     *
     * @param string $hook The current admin page.
     */
    public function enqueueAssets($hook) {
        if ($hook !== 'toplevel_page_fluentc-settings') {
            return;
        }

        wp_enqueue_script(
            'fluentc-settings',
            FLUENTC_TRANSLATION_PLUGIN_URL . 'src/includes/js/translation-status.js',
            ['jquery', 'underscore', 'wp-util'],  // Add 'underscore' as a dependency.
            FLUENTC_TRANSLATION_VERSION,
            true
        );

        wp_localize_script('fluentc-settings', 'fluentcTranslation', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('fluentc_translation_nonce'),
        ]);
    }

    /**
     * AJAX handler for scanning the site
     */
    public function ajaxScanSite() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }

        $this->fluentc_processor->scan_and_send_urls_translate();

       
       wp_send_json_success(__('Site scan started successfully.', 'fluentc-translation'));
        
    }

    /**
     * AJAX handler for toggling URL status
     */
    public function ajaxToggleUrlStatus() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');
    
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }
    
        $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
        $result = $this->fluentc_scan->toggleUrlStatus($url);
    
        if ($result) {
            $translatedUrls = get_option('fluentc_translated_urls', []);
            if (isset($translatedUrls[$url])) {
                $translatedUrls[$url]['status'] = $result;
                update_option('fluentc_translated_urls', $translatedUrls);
            }
            wp_send_json_success(__('URL status updated successfully.', 'fluentc-translation'));
        } else {
            wp_send_json_error(__('An error occurred while updating the URL status.', 'fluentc-translation'));
        }
    }

    /**
     * AJAX handler for getting last scan time
     */
    public function ajaxGetLastScanTime() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }

        $lastScanTime = get_transient('fluentc_last_scan_time');
        $canTranslate = false;
        $message = '';

        if ($lastScanTime) {
            $timeSinceScan = current_time('timestamp') - $lastScanTime;
            $daysSinceScan = floor($timeSinceScan / DAY_IN_SECONDS);

            if ($daysSinceScan < 7) {
                $canTranslate = true;
                $message = sprintf(
                    __('Last scan: %s ago', 'fluentc-translation'),
                    human_time_diff($lastScanTime, current_time('timestamp'))
                );
            } else {
                $message = __('Last Scan older than 7 days, scan again', 'fluentc-translation');
            }
        } else {
            $message = __('No scan has been performed yet', 'fluentc-translation');
        }

        wp_send_json_success([
            'message' => $message,
            'canTranslate' => $canTranslate,
        ]);
    }

    /**
     * AJAX handler for translating the site
     */
    public function ajaxTranslateSite() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }

        // Step 1: Fetch languages
        $languages = $this->fluentc_connect->get_fluentc_languages_list();
        $defaultLanguage = $this->fluentc_language->fluentc_site_language();

        // Step 2: Generate translated URLs
        $urls = $this->fluentc_scan->getUrls();
        $translatedUrls = [];

        foreach ($urls as $url => $data) {
            if ($data['status'] === 'active') {
                $translatedUrls[$url] = [
                    'translations' => []
                ];
                foreach ($languages as $language) {
                    if ($language !== $defaultLanguage) {
                        $translatedUrl = $this->generateTranslatedUrl($url, $language);
                        $translatedUrls[$url]['translations'][] = [
                            'url' => $translatedUrl,
                            'language' => $language,
                            'status' => 'pending'
                        ];
                    }
                }
            }
        }

        // Save translated URLs
        update_option('fluentc_translated_urls', $translatedUrls);

        // Step 4: Schedule wp-cron job
        if (!wp_next_scheduled('fluentc_process_translated_urls')) {
            wp_schedule_single_event(time(), 'fluentc_process_translated_urls');
        }

        wp_send_json_success([
            'message' => __('Translation process started.', 'fluentc-translation'),
            'total_urls' => count($translatedUrls),
            'urls' => $translatedUrls
        ]);
    }

    /**
     * Handler for translating the site urls
     */
    public function translate_site_urls() {
       
        // Step 1: Fetch languages
        $languages = $this->fluentc_connect->get_fluentc_languages_list();
        $defaultLanguage = $this->fluentc_language->fluentc_site_language();

        // Step 2: Generate translated URLs
        $urls = $this->fluentc_scan->getUrls();
        $translatedUrls = [];
        $allurls = [];
        foreach ($urls as $url => $data) {
            if ($data['status'] === 'active') {
                $translatedUrls[$url] = [
                    'translations' => []
                ];
                foreach ($languages as $language) {
                    if ($language !== $defaultLanguage) {
                        $translatedUrl = $this->generateTranslatedUrl($url, $language);
                        $translatedUrls[$url]['translations'][] = [
                            'url' => $translatedUrl
                           
                        ];
                        $allurls[] = $translatedUrl; 
                    }
                }
            }
        }

        // Save translated URLs
        update_option('fluentc_translated_urls', $translatedUrls);
        error_log(json_encode($urls));
    }

    /**
     * AJAX handler for cancelling translation
     */
    public function ajaxCancelTranslation() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }

        $result = $this->fluentc_processor->cancelTranslation();

        if ($result) {
            wp_send_json_success(['message' => __('Translation cancelled', 'fluentc-translation')]);
        } else {
            wp_send_json_error(__('An error occurred while cancelling the translation.', 'fluentc-translation'));
        }
    }

    /**
     * Render translation table
     *
     * @param array $translatedUrls Array of translated URLs.
     */
    private function renderTranslationTable($translatedUrls) {
        ?>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th><?php _e('Original URL', 'fluentc-translation'); ?></th>
                    <th><?php _e('Translations', 'fluentc-translation'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($translatedUrls as $originalUrl => $data): ?>
                    <tr>
                        <td><?php echo esc_url($originalUrl); ?></td>
                        <td>
                            <table class="nested-translations">
                                <thead>
                                    <tr>
                                        <th><?php _e('Translated URL', 'fluentc-translation'); ?></th>
                                        <th><?php _e('Language', 'fluentc-translation'); ?></th>
                                        <th><?php _e('Status', 'fluentc-translation'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (isset($data['translations']) && is_array($data['translations'])): ?>
                                        <?php foreach ($data['translations'] as $translation): ?>
                                            <tr>
                                                <td>
                                                    <a href="<?php echo esc_url($translation['url']); ?>" target="_blank">
                                                        <?php echo esc_url($translation['url']); ?>
                                                        <span class="dashicons dashicons-external"></span>
                                                    </a>
                                                </td>
                                                <td><?php echo esc_html($translation['language']); ?></td>
                                                <td>
                                                    <?php
                                                    $status_class = $translation['status'] === 'translated' ? 'translated' : 'pending';
                                                    $status_text = $translation['status'] === 'translated' ? __('Translated', 'fluentc-translation') : __('Pending', 'fluentc-translation');
                                                    ?>
                                                    <span class="translation-status <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="3"><?php _e('No translations available', 'fluentc-translation'); ?></td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php
    }

    public function ajaxGetTranslationTable() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');
    
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }
    
        $scannedUrls = $this->fluentc_scan->getUrls();
        $translatedUrls = get_option('fluentc_translated_urls', []);
    
        $mergedUrls = [];
        foreach ($scannedUrls as $url => $data) {
            if (!isset($mergedUrls[$url])) {
                $mergedUrls[$url] = [
                    'status' => $data['status'],
                    'translations' => isset($translatedUrls[$url]['translations']) ? $translatedUrls[$url]['translations'] : []
                ];
            }
        }
    
        wp_send_json_success(['urls' => $mergedUrls]);
    }


    /**
     * Generate translated URL
     *
     * @param string $url Original URL.
     * @param string $languageCode Language code.
     * @return string Translated URL.
     */
    private function generateTranslatedUrl($url, $languageCode) {
        $parsedUrl = parse_url($url);
        $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
        return $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/' . $languageCode . $path;
    }

    /**
     * AJAX handler for getting translation status
     */
    public function ajaxGetTranslationStatus() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');
    
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }
    
        // Check if translation has been cancelled
        if (get_option('fluentc_translation_cancelled', false)) {
            delete_option('fluentc_translation_cancelled');
            wp_send_json_success([
                'status' => 'cancelled',
                'message' => __('Translation Cancelled', 'fluentc-translation'),
                'completed' => 0,
                'total' => 0
            ]);
            return;
        }
    
        $translatedUrls = get_option('fluentc_translated_urls', []);
        $totalTranslations = 0;
        $completedTranslations = 0;
        $notTranslated = 0;
    
        foreach ($translatedUrls as $originalUrl => $data) {
            if (isset($data['translations']) && is_array($data['translations'])) {
                foreach ($data['translations'] as $translation) {
                    $totalTranslations++;
                    if ($translation['status'] === 'translated') {
                        $completedTranslations++;
                    }
                    if ($translation['status'] === 'not_translated') {
                        $notTranslated++;
                    }
                }
            }
        }
    
        $status = 'in_progress';
        $message = __('Translation In Progress', 'fluentc-translation');
    
        if ($completedTranslations === $totalTranslations && $totalTranslations > 0) {
            $status = 'completed';
            $message = __('Translation Completed', 'fluentc-translation');
        } elseif ($totalTranslations === 0) {
            $status = 'not_started';
            $message = __('Translation Not Started', 'fluentc-translation');
        } elseif ( 0 <  $notTranslated) {
            $status = 'completed';
            $message = __('Last Translation Canceled', 'fluentc-translation');
        }
    
        wp_send_json_success([
            'status' => $status,
            'message' => $message,
            'completed' => $completedTranslations,
            'total' => $totalTranslations
        ]);
    }

    /**
     * AJAX handler for getting saved URLs
     */
    public function ajaxGetSavedUrls() {
        check_ajax_referer('fluentc_translation_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to perform this action.', 'fluentc-translation'));
        }

        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $per_page = 50;

        $translatedUrls = get_option('fluentc_translated_urls', []);
        $total_urls = count($translatedUrls);

        $urls = array_slice($translatedUrls, ($page - 1) * $per_page, $per_page, true);

        wp_send_json_success([
            'urls' => $urls,
            'total_pages' => ceil($total_urls / $per_page),
            'current_page' => $page
        ]);
    }
}