<?php
/**
 * FluentC Translation Management File.
 *
 * This file contains the functions for managing translations
 *
 * @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;

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

  
    private $items_per_page = 20;

    public function display_translations_page() {
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $offset = ($current_page - 1) * $this->items_per_page;

        $translations = $this->get_paginated_translations($offset, $this->items_per_page);
        $total_items = $this->get_total_translations_count();

        include plugin_dir_path(__FILE__) . '../templates/manage-translations-page.php';
    }

    private function get_paginated_translations($offset, $limit) {
        global $wpdb;
        $translations = [];
        $count = 0;
    
        $sql = "SELECT option_name, option_value 
                FROM {$wpdb->options} 
                WHERE option_name LIKE '_transient_fluentc%'
                LIMIT %d OFFSET %d";
    
        $results = $wpdb->get_results($wpdb->prepare($sql, $limit, $offset), ARRAY_A);
    
        foreach ($results as $result) {
            $transient_name = str_replace('_transient_', '', $result['option_name']);
            $transient_data = $result['option_value'];
    
            if (is_string($transient_data)) {
                $data = json_decode($transient_data, true);
                if (json_last_error() === JSON_ERROR_NONE && isset($data['data']['translateSite']['body'])) {
                    $body = $data['data']['translateSite']['body'];
                    
                    // Check if body is a single translation or an array of translations
                    if (isset($body['originalText'])) {
                    
                        $originalText = html_entity_decode($body['originalText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                        $translatedText = html_entity_decode($body['translatedText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                        
                        if ($originalText !== $translatedText) {
                            $translations[] = [
                                'id' => $transient_name,
                                'sourceLanguage' => $body['sourceLanguage'],
                                'targetLanguage' => $body['targetLanguage'],
                                'originalText' => $originalText,
                                'translatedText' => $translatedText
                            ];
                            $count++;
                        }
                    }
                    elseif(isset($body[0]['originalText'])){
					
                        $originalText = html_entity_decode($body[0]['originalText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                        $translatedText = html_entity_decode($body[0]['translatedText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                        
                        if ($originalText !== $translatedText) {
                            $translations[] = [
                                'id' => $transient_name,
                                'sourceLanguage' => $body[0]['sourceLanguage'],
                                'targetLanguage' => $body[0]['targetLanguage'],
                                'originalText' => $originalText,
                                'translatedText' => $translatedText
                            ];
                            $count++;
                        }
                   }
                   else {
                        do_action('qm/info', 'get_total_translations_count No Origianl');
                   }
                }
            }
        }
    
        return $translations;
    }
    
    private function get_total_translations_count() {
        global $wpdb;
        $count = 0;
    
        $sql = "SELECT option_value 
                FROM {$wpdb->options} 
                WHERE option_name LIKE '_transient_fluentc%'";
    
        $results = $wpdb->get_col($sql);
    
        foreach ($results as $transient_data) {
            $data = json_decode($transient_data, true);
            if (json_last_error() === JSON_ERROR_NONE && isset($data['data']['translateSite']['body'])) {
                $body = $data['data']['translateSite']['body'];
                if (isset($body['originalText'])) {
                  
                    $originalText = html_entity_decode($body['originalText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                    $translatedText = html_entity_decode($body['translatedText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                        
                        if ($originalText !== $translatedText) {
                            $count++;
                        }
                    }
                    elseif(isset($body[0]['originalText'])){
					
                       $originalText = html_entity_decode($body[0]['originalText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                       $translatedText = html_entity_decode($body[0]['translatedText'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
                           
                        if ($originalText !== $translatedText) {
                             $count++;
                         }
                   }
                   else {
                        do_action('qm/info', 'get_total_translations_count No Origianl');
                   }
            }
        }
    
        return $count;
    }

    public function handle_inline_edit() {
        if (!isset($_POST['action']) || $_POST['action'] !== 'fluentc_inline_edit') {
            return;
        }
        do_action( 'qm/notice', 'Handle Inline Edit' );
        // Verify nonce
        check_admin_referer('fluentc_inline_edit', 'fluentc_nonce');

        $translation_id = isset($_POST['translation_id']) ? sanitize_text_field($_POST['translation_id']) : '';
       $new_translation = isset($_POST['new_translation']) ? $_POST['new_translation'] : '';

        if (empty($translation_id) || empty($new_translation)) {
            wp_send_json_error('Invalid data');
        }

        // Update the translation in the transient
        $fluentc_cache = new Cache();
        $updated = $fluentc_cache->update_translation($translation_id, $new_translation);

        if ($updated) {
            do_action( 'qm/notice', 'Translation updated successfully' );
            wp_send_json_success('Translation updated successfully');
        } else {
            do_action( 'qm/notice', 'Failed to update translation' );
            wp_send_json_error('Failed to update translation');
        }
    }

    public function handle_search_translations() {
        if (!isset($_POST['action']) || $_POST['action'] !== 'fluentc_search_translations') {
            wp_send_json_error('Invalid action');
        }

        // Verify nonce
        check_admin_referer('fluentc_inline_edit', 'fluentc_nonce');

        $search_term = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;

        if (empty($search_term)) {
            wp_send_json_error('Empty search term');
        }

        $fluentc_cache = new \FluentC\Services\Cache();
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $results = $fluentc_cache->search_fluentc_transients($search_term, $offset, $limit);
        $total_results = $fluentc_cache->count_search_results($search_term);

        wp_send_json_success([
            'translations' => $results,
            'total' => $total_results,
            'page' => $page,
            'totalPages' => ceil($total_results / $limit)
        ]);
    }


    public function handle_delete_translation() {
        if (!isset($_POST['action']) || $_POST['action'] !== 'fluentc_delete_translation') {
            wp_send_json_error('Invalid action');
        }
    
        // Verify nonce
        check_admin_referer('fluentc_inline_edit', 'fluentc_nonce');
    
        $translation_id = isset($_POST['translation_id']) ? sanitize_text_field($_POST['translation_id']) : '';
    
        if (empty($translation_id)) {
            wp_send_json_error('Invalid translation ID');
        }
    
        $fluentc_cache = new \FluentC\Services\Cache();
        $result = $fluentc_cache->update_clean($translation_id);
    
        if ($result) {
            wp_send_json_success('Translation deleted successfully');
        } else {
            wp_send_json_error('Failed to delete translation');
        }
    }

    public function enqueue_scripts() {
        wp_enqueue_script('fluentc-translations', plugin_dir_url(__FILE__) . '../includes/js/translations.js', array('jquery'), '1.0', true);
        wp_localize_script('fluentc-translations', 'fluentcTranslations', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('fluentc_inline_edit')
        ));
    }

    public function handle_get_translations() {
        if (!isset($_POST['action']) || $_POST['action'] !== 'fluentc_get_translations') {
            wp_send_json_error('Invalid action');
        }
    
        // Verify nonce
        check_admin_referer('fluentc_inline_edit', 'fluentc_nonce');
    
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    
        $limit = 20;
        $offset = ($page - 1) * $limit;
    
        $translations = $this->get_paginated_translations($offset, $limit);
        $total_translations = $this->get_total_translations_count();
    
        wp_send_json_success([
            'translations' => $translations,
            'total' => $total_translations,
            'page' => $page,
            'totalPages' => ceil($total_translations / $limit)
        ]);
    }
}

