<?php

class ATFPP_Register_Backend_Assets
{

    /**
     * Singleton instance of ATFPP_Register_Backend_Assets.
     *
     * @var ATFPP_Register_Backend_Assets
     */
    private static $instance;

    /**
     * Get the singleton instance of ATFPP_Register_Backend_Assets.
     *
     * @return ATFPP_Register_Backend_Assets
     */
    public static function get_instance()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor for ATFPP_Register_Backend_Assets.
     */
    public function __construct()
    {
        add_action('admin_enqueue_scripts', array($this, 'enqueue_gutenberg_translate_assets'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_supported_block_scripts'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_classic_translate_assets'));
        add_action('enqueue_block_assets', array($this, 'block_inline_translation_assets'));
        add_action('admin_enqueue_scripts', array($this, 'classic_inline_translation_assets'));
        add_action('elementor/editor/before_enqueue_scripts', array($this, 'enqueue_elementor_translate_assets'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_bulk_translate_assets'));
        add_action('admin_enqueue_scripts', array($this, 'atfpp_enqueue_admin_assets'));
    }

    public function atfpp_enqueue_admin_assets(){
        if(!is_admin()){
            return;
        }

        global $polylang;
        
		if(!$polylang || !property_exists($polylang, 'model') || !function_exists('get_current_screen')){
            return;
		}
        
		$current_screen = get_current_screen();
        
        if(class_exists('ATFPP_Helper') && ATFPP_Helper::bulk_translation_render($current_screen)){
            wp_enqueue_script('atfp-views-link-admin', ATFPP_URL . 'assets/js/atfp-admin-views-link.js', array('jquery'), ATFPP_V, true);
        }
    }

    public function enqueue_supported_block_scripts(){
        if(function_exists('get_current_screen') && property_exists(get_current_screen(), 'post_type') && 'atfp_add_blocks' === get_current_screen()->post_type){
            wp_enqueue_style('atfp-update-custom-blocks', ATFPP_URL . 'assets/css/atfp-update-custom-blocks.min.css', array(), ATFPP_V);
            wp_enqueue_script('atfp-update-custom-blocks', ATFPP_URL . 'assets/js/atfp-update-custom-blocks.min.js', array('jquery'), ATFPP_V, true);
        
            wp_localize_script(
                'atfp-update-custom-blocks',
                'atfp_block_update_object',
                array(
                    'ajax_url'       => admin_url('admin-ajax.php'),
                    'ajax_nonce'     => wp_create_nonce('atfp_block_update_nonce'),
                    'atfp_url'       => esc_url(ATFPP_URL),
                    'action_get_content' => 'atfp_get_custom_blocks_content',
                    'action_update_content' => 'atfp_update_custom_blocks_content',
                )
            );
        }
    }

    /**
     * Register block translator assets.
     */
    public function block_inline_translation_assets()
    {

        if (defined('POLYLANG_VERSION')) {
            $this->enqueue_inline_translation_assets('block');
        }
    }

    /**
     * Register backend assets.
     */
    public function enqueue_gutenberg_translate_assets()
    {
        $current_screen = get_current_screen();
        if (
            isset($_GET['from_post'], $_GET['new_lang'], $_GET['_wpnonce']) &&
            wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'new-post-translation')
        ) {
            if (method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor()) {
                $from_post_id = isset($_GET['from_post']) ? absint($_GET['from_post']) : 0;
                
                global $post;
                
                if (null === $post || 0 === $from_post_id) {
                    return;
                }
                
                $lang           = isset($_GET['new_lang']) ? sanitize_key($_GET['new_lang']) : '';

                $editor = '';
                if ('builder' === get_post_meta($from_post_id, '_elementor_edit_mode', true) && defined('ELEMENTOR_VERSION')) {
                    $source_lang_name = pll_get_post_language($from_post_id, 'slug');
                    $this->enqueue_elementor_confirm_box_assets($from_post_id, $lang, $source_lang_name, 'gutenberg');
                    $editor = 'Elementor';
                }
                if ('on' === get_post_meta($from_post_id, '_et_pb_use_builder', true) && defined('ET_CORE')) {
                    $editor = 'Divi';
                }

                if (in_array($editor, array('Elementor', 'Divi'), true)) {
                    return;
                }

                $languages = PLL()->model->get_languages_list();

                $lang_object = array();
                foreach ($languages as $lang_obj) {
                    $lang_object[$lang_obj->slug] = $lang_obj->name;
                }

                $post_translate = PLL()->model->is_translated_post_type($post->post_type);
                
                $post_type      = isset($_GET['post_type']) ? sanitize_key($_GET['post_type']) : '';

                if ($post_translate && $lang && $post_type) {
                    $data = array(
                        'action_fetch'       => 'atfp_fetch_post_content',
                        'action_block_rules' => 'atfp_block_parsing_rules',
                        'parent_post_id'     => $from_post_id,
                    );

                    $this->enqueue_automatic_translate_assets(pll_get_post_language($from_post_id, 'slug'), $lang, 'gutenberg', $data);
                }
            }
        }
    }

    public function enqueue_classic_translate_assets()
    {
        global $post;
        $current_screen = get_current_screen();
        $post_translate_status = isset($post) ? get_post_meta($post->ID, '_atfpp_translate_status', true) : '';
        $post_parent_post_id = isset($post) ? get_post_meta($post->ID, '_atfpp_parent_post_id', true) : '';

        if(isset($current_screen) && isset($current_screen->id) && $current_screen->id === 'edit-page'){
            return;
        }

        if (
            isset($_GET['from_post'], $_GET['new_lang'], $_GET['_wpnonce']) &&
            wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'new-post-translation')) {
            $current_screen = get_current_screen();

            if (method_exists($current_screen, 'is_block_editor') && !$current_screen->is_block_editor()) {
                $from_post_id = isset($_GET['from_post']) ? absint($_GET['from_post']) : 0;
                $from_post_id = !empty($post_parent_post_id) ? $post_parent_post_id : $from_post_id;

                if (null === $post || 0 === $from_post_id) {
                    return;
                }

                $lang           = isset($_GET['new_lang']) ? sanitize_key($_GET['new_lang']) : '';

                if(!empty($post_translate_status) && $post_translate_status === 'pending') {
                    $lang = pll_get_post_language($post->ID, 'slug');
                }

                $editor = '';
                if ('builder' === get_post_meta($from_post_id, '_elementor_edit_mode', true) && defined('ELEMENTOR_VERSION')) {
                    $source_lang_name = pll_get_post_language($from_post_id, 'slug');
                    $this->enqueue_elementor_confirm_box_assets($from_post_id, $lang, $source_lang_name, 'classic');
                    $editor = 'Elementor';
                }
                if ('on' === get_post_meta($from_post_id, '_et_pb_use_builder', true) && defined('ET_CORE')) {
                    $editor = 'Divi';
                }

                if (in_array($editor, array('Elementor', 'Divi'), true)) {
                    return;
                }

                $languages = PLL()->model->get_languages_list();

                $lang_object = array();
                foreach ($languages as $lang_obj) {
                    $lang_object[$lang_obj->slug] = $lang_obj->name;
                }

                $post_translate = PLL()->model->is_translated_post_type($post->post_type);
               

                if ($post_translate && $lang && !empty($lang)) {

                    $data = array(
                        'action_fetch'       => 'atfp_fetch_post_content',
                        'parent_post_id'     => $from_post_id,
                        'action_update_status' => 'atfp_update_classic_translate_status',
                        'classic_status_key' => wp_create_nonce('atfp_classic_translate_nonce'),
                    );

                    $parent_page_content = get_the_content(null, false, $from_post_id);
                    $block_comment_tag = preg_match('/<!--[\s\S]*?-->/s', $parent_page_content) && strpos($parent_page_content, '<!--') < strpos($parent_page_content, '-->');
                    
                    if($block_comment_tag){
                        $data['blockCommentTag']="true";       
                    }

                    $this->enqueue_automatic_translate_assets(pll_get_post_language($from_post_id, 'slug'), $lang, 'classic', $data);
                }
            }
        }
    }

    public function classic_inline_translation_assets()
    {
        $current_screen = get_current_screen();

        if (method_exists($current_screen, 'is_block_editor') && !$current_screen->is_block_editor()) {
            $this->enqueue_inline_translation_assets('classic');
        }
    }

    public function enqueue_elementor_translate_assets()
    {

        $this->elementor_inline_translation_assets();

        $page_translated = get_post_meta(get_the_ID(), '_atfp_elementor_translated', true);
        $parent_post_language_slug = get_post_meta(get_the_ID(), '_atfp_parent_post_language_slug', true);

        if ((!empty($page_translated) && $page_translated === 'true') || empty($parent_post_language_slug)) {
            return;
        }

        $post_language_slug = pll_get_post_language(get_the_ID(), 'slug');
        $current_post_id = get_the_ID(); // Get the current post ID

        if(!class_exists('\Elementor\Plugin') || !property_exists('\Elementor\Plugin', 'instance') ){
            return;
        }

        $elementor_data = \Elementor\Plugin::$instance->documents->get( $current_post_id )->get_elements_data();


        if ($parent_post_language_slug === $post_language_slug) {
            return;
        }

        $parent_post_id=PLL()->model->post->get_translation($current_post_id, $parent_post_language_slug);

        $data = array(
            'update_elementor_data' => 'atfp_update_elementor_data',
            'elementorData' => $elementor_data,
            'parent_post_id' => $parent_post_id,
            'parent_post_title' => get_the_title($parent_post_id),
        );

        wp_enqueue_style('atfp-elementor-translate', ATFPP_URL . 'assets/css/atfp-elementor-translate.css', array(), ATFPP_V);
        $this->enqueue_automatic_translate_assets($parent_post_language_slug, $post_language_slug, 'elementor', $data);
    }

    public function enqueue_automatic_translate_assets($source_lang, $target_lang, $editor_type, $extra_data = array())
    {
        wp_register_style('atfp-automatic-translate-custom', ATFPP_URL . 'assets/css/atfp-custom.min.css', array(), ATFPP_V);
        wp_register_script( 'atfp-google-api', 'https://translate.google.com/translate_a/element.js', '', ATFPP_V, true );

        $editor_script_asset = include ATFPP_DIR_PATH . 'assets/automatic-translate/index.asset.php';
        wp_register_script('atfp-automatic-translate', ATFPP_URL . 'assets/automatic-translate/index.js', array_merge($editor_script_asset['dependencies'], ['atfp-google-api']), $editor_script_asset['version'], true);

        $post_type = get_post_type();

        $languages = PLL()->model->get_languages_list();
        $lang_object = array();
        foreach ($languages as $lang) {
            $lang_object[$lang->slug] = array('name' => $lang->name, 'flag' => $lang->flag_url, 'locale' => $lang->locale);
        }
        
        wp_enqueue_style('atfp-automatic-translate-custom');
        
        wp_enqueue_script('atfp-automatic-translate');
        wp_set_script_translations('atfp-automatic-translate', 'autopoly-ai-translation-for-polylang-pro', ATFPP_DIR_PATH . 'languages');


        $post_id = get_the_ID();
        
        $services=atfpp_ai_services()->get_registered_service_slugs();
        $available_ai_services=array();

        foreach($services as $service){
            $service_status=atfpp_ai_services()->is_service_available($service);
            if($service_status){
                array_push($available_ai_services, $service);
            }
        }

        $slug_translation_option = get_option('atfp_slug_translation_option','title_translate');

        if(isset($extra_data['parent_post_id'])){
            $parent_post_id = $extra_data['parent_post_id'];
            $parent_post_slug = get_post_field('post_name', $parent_post_id);

            $extra_data['slug_name'] = $parent_post_slug;
        }

        if (!isset(PLL()->options['sync']) || (isset(PLL()->options['sync']) && !in_array('post_meta', PLL()->options['sync']))) {
            $extra_data['postMetaSync'] = 'false';

            if(in_array($editor_type, array('classic', 'gutenberg'))){
                $extra_data['update_post_meta_fields'] = 'atfp_update_post_meta_fields';
                $extra_data['post_meta_fields_key'] = wp_create_nonce('atfp_update_post_meta_fields');
            }
            
        } else {
            $extra_data['postMetaSync'] = 'true';
        }

        $ai_max_tokens=get_option('atfp_ai_request_token_per_request', 500);
        $ai_batch_size=get_option('atfp_ai_request_batch_size', 5);

        $data = array_merge(array(
            'ajax_url'           => admin_url('admin-ajax.php'),
            'ajax_nonce'         => wp_create_nonce('atfp_translate_nonce'),
            'atfp_url'           => esc_url(ATFPP_URL),
            'admin_url'          => admin_url(),
            'update_translate_data' => 'atfp_update_translate_data',
            'source_lang'        => $source_lang,
            'target_lang'        => $target_lang,
            'languageObject'     => $lang_object,
            'post_type'          => $post_type,
            'editor_type'        => $editor_type,
            'current_post_id'    => $post_id,
            'ai_translate_route_url' => get_rest_url(null, 'atfpp-translate'),
            'ai_translate_route_nonce' => wp_create_nonce('wp_rest'),
            'ai_translate_nonce' => wp_create_nonce('atfp_ai_translate_nonce'),
            'get_meta_fields' => 'atfp_fetch_post_meta_fields',
            'meta_fields_key'=>wp_create_nonce('atfp_fetch_post_meta_fields'),
            'atfpp_glossary_nonce' => wp_create_nonce('atfpp_glossary_nonce'),
            'slug_translation_option' => $slug_translation_option,
            'AIServices' => $available_ai_services,
            'AIRequestMaxTokens' => $ai_max_tokens,
            'AIRequestBatchSize' => $ai_batch_size,
        ), $extra_data);

        wp_localize_script(
            'atfp-automatic-translate',
            'atfp_global_object',
            $data
        );
    }

    /**
     * Enqueue the elementor widget translator script.
     */
    public function elementor_inline_translation_assets()
    {
        if (defined('POLYLANG_VERSION')) {
            $this->enqueue_inline_translation_assets(
                'elementor', 
                array(
                    'backbone-marionette',
                    'elementor-common',
                    'elementor-web-cli',
                    'elementor-editor-modules',
                )
            );
        }
    }

    public function enqueue_bulk_translate_assets()
    {
        global $polylang;
        
        if(!$polylang || !property_exists($polylang, 'model')){
            return;
        }

        $current_screen = function_exists('get_current_screen') ? get_current_screen() : false;

        if(!$current_screen){
            return;
        }
        
        if(!class_exists('ATFPP_Helper') || !ATFPP_Helper::bulk_translation_render($current_screen)){
            return;
        }

        $post_status=isset($_GET['post_status']) ? sanitize_text_field(wp_unslash($_GET['post_status'])) : '';

        if('trash' === $post_status){
            return;
        }

        $post_label=__("Pages", "autopoly-ai-translation-for-polylang-pro");
        $taxonomy_page=false;

        if(isset($current_screen->post_type)){
            $post_type = $current_screen->post_type;

            if(isset(get_post_type_object($post_type)->label) && !empty(get_post_type_object($post_type)->label)){
                $post_label = get_post_type_object($post_type)->label;
            }

            if(isset($current_screen->taxonomy) && !empty($current_screen->taxonomy)){
                $taxonomy_page=$current_screen->taxonomy;    
                $taxonomy_object = get_taxonomy($current_screen->taxonomy);

                if(isset($taxonomy_object->label) && !empty($taxonomy_object->label)){
                    $post_label = $taxonomy_object->label;

                    if(isset($taxonomy_object->labels->singular_name) && !empty($taxonomy_object->labels->singular_name)){
                        $post_label = $taxonomy_object->labels->singular_name;
                    }
                }
            }
        }
        
        $slug_translation_option = get_option('atfp_slug_translation_option','title_translate');

        $editor_script_asset = include ATFPP_DIR_PATH . 'assets/bulk-translate/index.asset.php';
        
        $rtl=function_exists('is_rtl') ? is_rtl() : false;
        $css_file=$rtl ? 'index-rtl.css' : 'index.css';
      
        wp_enqueue_script( 'atfpp-google-api', 'https://translate.google.com/translate_a/element.js', '', ATFPP_V, true );
        wp_enqueue_script('atfpp-bulk-translate', ATFPP_URL . 'assets/bulk-translate/index.js', array_merge($editor_script_asset['dependencies'], ['atfpp-google-api']), $editor_script_asset['version'], true);
       
        wp_enqueue_style('atfpp-bulk-translate', ATFPP_URL . 'assets/bulk-translate/'.$css_file, array(), $editor_script_asset['version']);

        $languages = PLL()->model->get_languages_list();

        $lang_object = array();
        foreach ($languages as $lang) {
            $lang_object[$lang->slug] = array('name' => $lang->name, 'flag' => $lang->flag_url, 'locale' => $lang->locale);
        }

        $services=atfpp_ai_services()->get_registered_service_slugs();
        $available_ai_services=array();

        foreach($services as $service){
            $service_status=atfpp_ai_services()->is_service_available($service);
            if($service_status){
                array_push($available_ai_services, $service);
            }
        }

        $extra_data = array();

        if(!$taxonomy_page || empty($taxonomy_page)){
            if (!isset(PLL()->options['sync']) || (isset(PLL()->options['sync']) && !in_array('post_meta', PLL()->options['sync']))) {
                $extra_data['postMetaSync'] = 'false';
            } else {
                $extra_data['postMetaSync'] = 'true';
            }
        }

        $ai_max_tokens=get_option('atfp_ai_request_token_per_request', 500);
        $ai_batch_size=get_option('atfp_ai_request_batch_size', 5);

        wp_localize_script(
            'atfpp-bulk-translate',
            'atfpp_bulk_translate_object',
            array_merge(array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'languageObject' => $lang_object,
                'nonce' => wp_create_nonce('wp_rest'),
                'bulkTranslateRouteUrl' => get_rest_url(null, 'atfpp-translate'),
                'bulkTranslatePrivateKey' => wp_create_nonce('atfpp_bulk_translate_entries_nonce'),
                'atfpp_url'           => esc_url(ATFPP_URL),
                'AIServices' => $available_ai_services,
                'admin_url' => admin_url(),
                'ai_translate_route_url' => get_rest_url(null, 'atfpp-translate'),
                'ai_translate_route_nonce' => wp_create_nonce('wp_rest'),
                'ai_translate_nonce' => wp_create_nonce('atfp_ai_translate_nonce'),
                'post_label' => $post_label,
                'update_translate_data' => 'atfp_update_translate_data',
                'slug_translation_option' => $slug_translation_option,
                'taxonomy_page' => $taxonomy_page,
                'AIRequestMaxTokens' => $ai_max_tokens,
                'AIRequestBatchSize' => $ai_batch_size,
                'atfpp_glossary_nonce' => wp_create_nonce('atfpp_glossary_nonce'),
            ), $extra_data)
        );
    }

    public function enqueue_elementor_confirm_box_assets($parent_post_id, $target_lang_name, $source_lang_name, $editor_type='gutenberg')
    {
        $post_id = get_the_ID();

        $source_lang_name=PLL()->model->get_language($source_lang_name);
        $target_lang_name=PLL()->model->get_language($target_lang_name);

        wp_enqueue_script('atfp-elementor-confirm-box', ATFPP_URL . 'assets/js/atfp-elementor-translate-confirm-box.js', array('jquery', 'wp-i18n'), ATFPP_V, true);

        wp_localize_script('atfp-elementor-confirm-box', 'atfpElementorConfirmBoxData',
            array('postId' => $post_id, 'parentPostId' => $parent_post_id, 'sourceLangSlug' => $source_lang_name->slug, 'targetLangSlug' => $target_lang_name->slug, 'sourceLangName' => $source_lang_name->name, 'targetLangName' => $target_lang_name->name, 'editorType' => $editor_type)
        );

        wp_enqueue_style('atfp-elementor-confirm-box', ATFPP_URL . 'assets/css/atfp-elementor-translate-confirm-box.css', array(), ATFPP_V);
    }

    private function enqueue_inline_translation_assets( $type = 'block', $extra_dependencies = array() ) {

		global $post;

		if(!isset($post) || !isset($post->ID)){
			return;
		}

		if (defined('POLYLANG_VERSION')) {
            if (function_exists('pll_current_language')) {
                $current_language = pll_current_language();
                $current_language_name = pll_current_language('name');
            } else {
                $current_language = '';
                $current_language_name = '';
            }

            $editor_script_asset = require_once ATFPP_DIR_PATH . 'assets/'.sanitize_file_name( $type ).'-inline-translation/index.asset.php';
            $core_modal_script_asset = include ATFPP_DIR_PATH . 'assets/inline-translate-modal/index.asset.php';

            if(!is_array($editor_script_asset)) {
                $editor_script_asset = array(
                    'dependencies' => array(),
                    'version' => ATFPP_V,
                );
            }

            if(!is_array($core_modal_script_asset)) {
                $core_modal_script_asset = array(
                    'dependencies' => array(),
                    'version' => ATFPP_V,
                );
            }

            wp_register_script( 'atfp-inline-translate-modal', ATFPP_URL . 'assets/inline-translate-modal/index.js' , array_merge( $core_modal_script_asset['dependencies'] ), $core_modal_script_asset['version'], true );
    
            $extra_dependencies[] = 'atfp-inline-translate-modal';

            wp_register_script(
                'atfp-'.sanitize_file_name( $type ).'-inline-translation',
                ATFPP_URL . 'assets/'.sanitize_file_name( $type ).'-inline-translation/index.js',
                array_merge(
                    $editor_script_asset['dependencies'], $extra_dependencies
                ),
                $editor_script_asset['version'],
                true
            );

            wp_enqueue_script( 'atfp-inline-translate-modal' );

            wp_enqueue_script('atfp-' . sanitize_file_name( $type ) . '-inline-translation');

            if ($current_language && $current_language !== '') {
                wp_localize_script(
                    'atfp-inline-translate-modal',
                    'atfpInlineTranslation',
                    array(
                        'pageLanguage' => $current_language,
                        'pageLanguageName' => $current_language_name,
                    )
                );
            }
        }
	}
}
