<?php

namespace FluentC\Services;

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

class Translation_Processor {

    private $fluentc_connect;
    private $fluentc_scan;
    private $widgetapikey;
    public function __construct() {
$this->fluentc_connect = new Connect();
$this->fluentc_scan = new Scan();
$this->widgetapikey  = get_option( 'fluentc_api_key' );
    }

    public function scan_and_send_urls_translate(){
        //URLS
        if(!$this->widgetapikey){
            return false;
        }
        $urls = $this->fluentc_scan->scan_all_urls();
        $urls_response = $this->fluentc_connect->send_translate_urls($this->widgetapikey, $urls);
        error_log(json_encode($urls_response));
        if($urls_response){
            return $urls_response;
        }
        return false;
    }
    public function fetchJobStatus($jobId){
        $response = $this->fluentc_connect->fetch_job_status($jobId);
        if(!$response) {
            error_log("Batch Progress not found");
            return;
        }

        return $response;
    }
   
    /**
     * Process translated URLs.
     */
    public function processTranslatedUrls() {
        $translatedUrls = get_option('fluentc_translated_urls', []);
        $processed = false;

        foreach ($translatedUrls as $originalUrl => &$data) {
            if (isset($data['translations']) && is_array($data['translations'])) {
                foreach ($data['translations'] as &$translation) {
                    if ($translation['status'] === 'pending') {
                        $response = wp_remote_get($translation['url'], [
                            'timeout' => 30,
                            'sslverify' => false
                        ]);
                        
                        if (is_wp_error($response)) {
                            error_log('FluentC Translation Error: ' . $response->get_error_message());
                            continue;
                        }

                        $responseCode = wp_remote_retrieve_response_code($response);

                        if ($responseCode === 200) {
                            $translation['status'] = 'translated';
                            $processed = true;
                        } else {
                            error_log('FluentC Translation Error: Non-200 response code (' . $responseCode . ') for URL ' . $translation['url']);
                        }

                        // Process only one URL per cron job execution
                        break 2;
                    }
                }
            }
        }

        if ($processed) {
            update_option('fluentc_translated_urls', $translatedUrls);
        }

        $this->scheduleNextRun($translatedUrls);
    }

    /**
     * Schedule the next run of the cron job if needed.
     *
     * @param array $translatedUrls The array of translated URLs.
     */
    private function scheduleNextRun($translatedUrls) {
        $pendingTranslations = $this->getPendingTranslationsCount($translatedUrls);

        if ($pendingTranslations > 0) {
            // Schedule the next run
            if (!wp_next_scheduled('fluentc_process_translated_urls')) {
                wp_schedule_single_event(time() + 3, 'fluentc_process_translated_urls');
            }
        } else {
            // All URLs processed, clear the schedule
            wp_clear_scheduled_hook('fluentc_process_translated_urls');
        }
    }

    /**
     * Get the count of pending translations.
     *
     * @param array $translatedUrls The array of translated URLs.
     * @return int The number of pending translations.
     */
    private function getPendingTranslationsCount($translatedUrls) {
        $pendingCount = 0;
        foreach ($translatedUrls as $originalUrl => $data) {
            if (isset($data['translations']) && is_array($data['translations'])) {
                foreach ($data['translations'] as $translation) {
                    if ($translation['status'] === 'pending') {
                        $pendingCount++;
                    }
                }
            }
        }
        return $pendingCount;
    }

    /**
     * Cancel the translation process.
     */
    public function cancelTranslation() {
    wp_clear_scheduled_hook('fluentc_process_translated_urls');
    
    $translatedUrls = get_option('fluentc_translated_urls', []);
    foreach ($translatedUrls as &$data) {
        if (isset($data['translations'])) {
            foreach ($data['translations'] as &$translation) {
                if ($translation['status'] === 'pending') {
                    $translation['status'] = 'not_translated';
                }
            }
        }
    }
    update_option('fluentc_translated_urls', $translatedUrls);

    // Add a flag to indicate translation has been cancelled
    update_option('fluentc_translation_cancelled', true);

    return true;
}
}