<?php

namespace SEOAIC;

use SEOAIC\DB\KeywordsPostsTable;
use SEOAIC\helpers\ImageHelpers;
use SEOAIC\loaders\PostsEditLoader;
use SEOAIC\loaders\PostsGenerationLoader;
use SEOAIC\loaders\PostsReviewLoader;
use SEOAIC\repositories\PostRevisionRepository;
use SEOAIC\rest_api\AbstractAPI;
use SEOAIC\rest_api\CustomTemplateAPI;
use SEOAIC\rest_api\EditorBlocks;
use SEOAIC\rest_api\EditorCommands;
use SEOAIC\rest_api\EditorSidebar;
use SEOAIC\rest_api\FAQAPI;
use SEOAIC\rest_api\InteractiveArticleAddonAPI;
use SEOAIC\rest_api\LeadAddonAPI;
use SEOAIC\rest_api\Options;
use SEOAIC\rest_api\Posts;
use SEOAIC\seoaic_acf\SEOAICWysiwygField;
use SEOAIC\SEOAIC_CURL;
use SEOAIC\shortcodes\InteractiveArticleBlock;
use SEOAIC\shortcodes\MultistepForm;
use SeoaicAjaxValidation;
use WP_Query;
use SEOAIC\cron\MissedScheduleCron;
use SEOAIC\cron\MissedScheduleFallback;

class SEOAIC
{
    public $curl;
    public $auth;
    public $scanner;
    public $ideas;
    public $frames;
    public $posts;
    public $keywords;
    public $explorer;
    public $improve;
    public $locations;
    public $multilang;
    public $wizard;
    public $ajax_validation;
    public $dashboard;
    public $competitors;
    public $audit_data;
    public $knowledge_base;
    public $editor_commands;
    public $editor_sidebar;
    public $editor_blocks;
    public $content_improvement;
    public $settings;
    public $prompts;
    public $internal_links;
    public $pillar_links;
    public $api_posts;
    public $options;
    public $calendar;
    public $shortcodes;
    public $leadsAddon;
    public $interactiveArticleAddon;
    public $promote;
    public $brand_visibility;
    public $sentiment_analysis;
    public $onboarding;
    public $sea;
    public $also_ask_ideas;
    public $custom_template;
    public $missed_schedule_fallback;
    public $missed_schedule_cron;


    /**
     * Init main plugin functionality, actions and filters
     */
    function __construct()
    {
        include_once ABSPATH . 'wp-admin/includes/plugin.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        global $SEOAIC_OPTIONS;

        $SEOAIC_OPTIONS = get_option('seoaic_options');
        if (empty($SEOAIC_OPTIONS['seoaic_post_type'])) {
            $SEOAIC_OPTIONS['seoaic_post_type'] = 'post';
        }

        register_activation_hook( SEOAIC_DIR . 'seoai-client.php', [$this, 'on_activation'] );
        register_deactivation_hook( SEOAIC_DIR . 'seoai-client.php', [$this, 'on_deactivation'] );

        add_action('admin_init', [$this, 'seoaic_admin_init']);
        add_action('admin_enqueue_scripts', [$this, 'seoaic_admin_enqueue_scripts']);
        add_action('wp_enqueue_scripts', [$this, 'seoaic_front_enqueue_scripts']);

        add_action('init', [$this, 'init']);

        add_action('wp_ajax_seoaic_send_upgrade_plan', [$this, 'seoaic_send_upgrade_plan']);
        add_action('wp_ajax_seoaic_settings', [$this, 'seoaic_settings']);
        add_action('wp_ajax_seoaic_pillar_links', [$this, 'seoaic_pillar_links']);
        add_action('wp_ajax_seoaic_setinfo', [$this, 'seoaic_setinfo']);
        // add_action('wp_ajax_seoaic_update_company_credits', [$this, 'seoaic_update_company_credits']);
        // add_action('wp_ajax_nopriv_seoaic_update_company_credits', [$this, 'seoaic_update_company_credits']);
        add_action('wp_ajax_seoaic_settings_get_post_type_templates', [$this, 'seoaicSettingsGetPostTypeTemplates']);
        add_action('wp_ajax_seoaic_get_public_posts', [$this, 'getPublicPostsPagedCustomLinksAjax']);
        add_action('wp_ajax_seoaic_settings_get_public_seoaic_posts', [$this, 'getSEOAICPublicPostsPagedAjax']);
        add_action('wp_ajax_seoaic_get_all_public_posts', [$this, 'getAllPublicPosts']);
        add_action('wp_ajax_seoaic_get_all_public_posts_by_title_or_slug', [$this, 'getAllPublicPostsByTitleOrSlugOrLink']);

        add_action('admin_footer', [$this, 'popups'], 10);
        add_action('admin_notices', [$this, 'seoaic_admin_notice']);
        // add_action('enqueue_block_editor_assets', [$this, 'seoaicEnqueueEditorAssets']);
        add_action('enqueue_block_assets', [$this, 'seoaicEnqueueEditorAssets']);


        require_once( SEOAIC_DIR . 'inc/classes/seoaic-curl-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-auth-class.php' );
        //require_once( SEOAIC_DIR . 'inc/classes/seoaic-ideas-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-frames-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-locations-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-improve-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-multilang-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-ajax-validation.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-audit-data-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-pillar-links-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-promote-class.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-brand-visibility.php' );
        require_once( SEOAIC_DIR . 'inc/classes/seoaic-sentiment-analysis.php' );

        $this->curl = new SEOAIC_CURL($this);
        $this->auth = new \SEOAIC_AUTH($this);
        $this->ideas = new SEOAIC_IDEAS($this);
        $this->frames = new \SEOAIC_FRAMES($this);
        $this->posts = new SEOAIC_POSTS($this);
        $this->keywords = new SEOAIC_KEYWORDS($this);
        $this->explorer = new SEOAIC_EXPLORER($this);
        $this->locations = new \SEOAIC_LOCATIONS($this);
        $this->improve = new \SEOAIC_IMPROVE($this);
        $this->multilang = new \SEOAIC_MULTILANG($this);
        $this->ajax_validation = new \SeoaicAjaxValidation();
        $this->dashboard = new SEOAIC_DASHBOARD($this);
        $this->wizard = new Wizard($this);
        $this->competitors = new SEOAIC_COMPETITORS($this);
        $this->audit_data = new \SeoaicAuditData($this);
        $this->knowledge_base = new SeoaicKnowledgeBase($this);
        $this->editor_commands = new EditorCommands($this);
        $this->editor_sidebar = new EditorSidebar($this);
        $this->editor_blocks = new EditorBlocks($this);
        $this->content_improvement = new SeoaicContentImprovement($this);
        $this->settings = new SEOAIC_SETTINGS($this);
        $this->prompts = new SEOAIC_PROMPTS();
        $this->internal_links = new SeoaicInternalLinks($this);
        $this->pillar_links = new SeoaicPillarLinks($this);
        $this->api_posts = new Posts($this);
        $this->options = new Options($this);
        $this->calendar = new SEOAIC_CALENDAR($this);
        $this->shortcodes = new SeoaicShortcodes();
        $this->promote = new SEOAIC_PROMOTE($this);
        $this->sea = new SoaicSEA($this);
        $this->brand_visibility = new SEOAIC_BRAND_VISIBILITY($this);
        $this->sentiment_analysis = new SEOAIC_SENTIMENT_ANALYSIS($this);

        $this->onboarding = new SEOAIC_ONBOARDING($this);
        $this->also_ask_ideas = new SeoaicAlsoAskIdeas($this);
        new SEOAICWysiwygField();
        new LeadAddonAPI($this);
        new InteractiveArticleAddonAPI($this);
        new FAQAPI($this);
        new CustomTemplateAPI($this);
        $this->leadsAddon = new SeoaicLeadsAddon($this);
        // $this->interactiveArticleAddon = '';
        $this->custom_template = new SeoaicTemplates();

        SEOAICSingleton::get($this);

        $this->missed_schedule_cron = new MissedScheduleCron($this);
        $this->missed_schedule_cron->init();
        $this->missed_schedule_fallback = new MissedScheduleFallback($this);
    }

    public function on_activation() {
        $seoaicBasedir = wp_upload_dir()['basedir'] . '/seoaic';

        if (!is_dir($seoaicBasedir)) {
            mkdir($seoaicBasedir);
        }

        if (!is_dir($seoaicBasedir . '/logs')) {
            mkdir($seoaicBasedir . '/logs');
        }

        if (is_multisite()) {
            KeywordsPostsTable::dropOldIfExists();
        }
        KeywordsPostsTable::createIfNotExists();

        $this->missed_schedule_cron->maybe_schedule();
    }

    public function on_deactivation()
    {
        $this->posts->unregisterCrons();
        $this->content_improvement->unregisterBackgroundCrons();
        delete_transient('seoaic_seo_audit_data');
        wp_clear_scheduled_hook(MissedScheduleCron::HOOK);
    }

    public function init()
    {
        $this->registerPostType();
    }

    private function registerPostType()
    {
        register_post_type(
            SEOAIC_POSTS::REVISION_POST_TYPE,
            [
                'label'               => 'SEOAIC Post Last Revision',
                'public'              => false,
                'publicly_queryable'  => false,
                'show_ui'             => false,
                'show_in_rest'        => false,
                'has_archive'         => false,
                'show_in_menu'        => false,
                'show_in_nav_menus'   => false,
                'delete_with_user'    => false,
                'exclude_from_search' => false,
                'capability_type'     => 'page',
                'map_meta_cap'        => true,
                'hierarchical'        => false,
                'rewrite'             => false,
                'query_var'           => false,
                'supports'            => ['editor'],
            ]
        );
    }

    public function set_option ($key, $value) {
        global $SEOAIC_OPTIONS;
        $SEOAIC_OPTIONS[$key] = $value;
        update_option('seoaic_options', $SEOAIC_OPTIONS);
    }

    public function seoaic_admin_init()
    {
        global $SEOAIC_OPTIONS;

        if ( !empty($_GET['page']) && $_GET['page'] === 'seoaic-settings' ) {
            // $data = [
            //     'step'  => 'credits',
            //     'site_url'  => get_home_url()
            // ];

            //    $result = $this->curl->init('api/ai/scanning', $data, true, false, true);

            //    if ( !empty($result['status']) && $result['status'] === 'success' ) {
            //        $this->set_api_credits($result['credits']);
            //    }

        }

        if (
            isset($_GET['page'])
            && in_array($_GET['page'], [
                'seoaic-ideas',
                'seoaic-keywords',
                'seoaic-competitors',
                'seoaic-created-posts',
                'seoaic-settings-leads-interactive-form',
            ])
        ) {
            wp_enqueue_media();
        }

        if (SEOAIC_SETTINGS::isContentImprovementDisabled()) {
            $this->content_improvement->unregisterBackgroundCrons();
        }
    }

    /**
     * Ajax action - save settings
     */
    public function seoaic_settings()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC_OPTIONS;

        foreach ($_POST as $key => $value) {
            if ('seoaic_visible_posts' == $key) {
                $old_value = !empty($SEOAIC_OPTIONS[$key]) ? $SEOAIC_OPTIONS[$key] : [];
                $this->update_seoaic_posts_visibility_meta($old_value, $value);
            }

            switch ($key) {
                case 'seoaic_company_website':
                case 'seoaic_business_name':
                case 'seoaic_industry':
                case 'seoaic_business_description':
                case 'seoaic_content_guidelines':
                case 'seoaic_translating_guidelines':
                case 'seoaic_custom_faq_prompt':
                case 'seoaic_default_leads_form_prompt':
                case 'seoaic_language':
                case 'seoaic_location':
                case 'seoaic_keywords':
                case 'seoaic_keywords_stat':
                case 'seoaic_writing_style':
                case 'seoaic_default_category':
                case 'seoaic_image_generator':
                case 'seoaic_image_style':
                case 'seoaic_image_generate_width_default':
                case 'seoaic_image_generate_height_default':
                case 'seoaic_image_colors':
                case 'seoaic_image_colors_accent':
                case 'seoaic_image_colors_additional':
                case 'seoaic_schedule_days':
                case 'seoaic_publish_delay':
                // case 'seoaic_generate_internal_links':
                // case 'seoaic_hide_posts':
                case 'seoaic_visible_posts':
                // case 'seoaic_show_related_articles':
                case 'seoaic_related_articles_count':
                case 'seoaic_phone':
                case 'seoaic_words_range_min':
                case 'seoaic_words_range_max':
                case 'seoaic_subtitles_range_min':
                case 'seoaic_subtitles_range_max':
                case 'seoaic_services':
                case 'seoaic_target_audience':
                case 'seoaic_locations':
                case 'seoaic_post_type':
                case 'seoaic_post_template':
                case 'seoaic_post_author':
                case 'seoaic-exclude-taxonomy':
                case 'language_locations':
                case 'seoaic_multilanguages':
                case 'seoaic_image_generate_style':
                case 'seoaic_branded_keywords':
                case 'seoaic_image_generate_prompt_default':
                case 'seoaic_default_scheduled_posting_time':
                case 'seoaic_onboarding_send_pages_progress':
                case 'seoaic_onboarding_clusters_generated_status':
                case 'seoaic_onboarding_current_step':
                    if (is_array($value)) {
                        $SEOAIC_OPTIONS[$key] = [];
                        foreach ($value as $item) {
                            $item = map_deep($item, 'sanitize_text_field' );

                            if ($key === 'seoaic_schedule_days') {
                                $SEOAIC_OPTIONS[$key][$item] = [
                                    'posts' => intval($_POST['seoaic_schedule_' . $item . '_posts']),
                                    'time' => sanitize_text_field($_POST['seoaic_schedule_' . $item . '_time']),
                                ];
                            } elseif (in_array($key, ['seoaic_services', 'seoaic_target_audience'])) {
                                $repeater = array_map(function($item) {
                                    return $item['name'] ? [
                                        'name' => stripslashes($item['name']),
                                        'text' => stripslashes($item['text']),
                                    ] : [];
                                }, $value);

                                $SEOAIC_OPTIONS[$key] = $repeater;

                            } elseif ('seoaic_visible_posts' == $key && count($value) > 1) {
                                if (!empty(trim($item))) {
                                    $SEOAIC_OPTIONS[$key][] = $item;
                                }

                            } else {
                                $SEOAIC_OPTIONS[$key][] = $item;
                            }
                        }
                    } else {
                        $SEOAIC_OPTIONS[$key] = stripslashes(sanitize_textarea_field($value));
                    }
                    break;
            }

            SEOAIC_SETTINGS::saveCustomPostTypeSettings($_POST);
        }

        if (isset($_REQUEST['seoaic-exclude-taxonomy'])) {
            $SEOAIC_OPTIONS['seoaic-exclude-taxonomy'] = $_REQUEST['seoaic-exclude-taxonomy'];
        } else {
            $SEOAIC_OPTIONS['seoaic-exclude-taxonomy'] = [];
        }

        if (isset($_REQUEST['seoaic_default_category'])) {
            $SEOAIC_OPTIONS['seoaic_default_category'] = $_REQUEST['seoaic_default_category'];
        } else {
            $SEOAIC_OPTIONS['seoaic_default_category'] = [];
        }

        if ( !isset($_POST['seoaic_multilanguages']) ) {
            unset($SEOAIC_OPTIONS['seoaic_multilanguages']);
        }

        if ( !isset($_POST['seoaic_schedule_days']) ) {
            // unset($SEOAIC_OPTIONS['seoaic_schedule_days']);
            $SEOAIC_OPTIONS['seoaic_schedule_days'] = [];
        }

        if (current_user_can('manage_options')) {
            if (isset($_REQUEST['seoaic_access_role'])) {
                $SEOAIC_OPTIONS['seoaic_access_role'] = $_REQUEST['seoaic_access_role'];
            } else {
                $SEOAIC_OPTIONS['seoaic_access_role'] = [];
            }
        }

        $SEOAIC_OPTIONS['seoaic_ssl_verifypeer'] = !empty($_REQUEST['seoaic_ssl_verifypeer']);
        $SEOAIC_OPTIONS['seoaic_competitors_traffic_graph'] = !empty($_REQUEST['seoaic_competitors_traffic_graph']);
        $SEOAIC_OPTIONS['seoaic_total_value_content_improvement'] = !empty($_REQUEST['seoaic_total_value_content_improvement']);
        $SEOAIC_OPTIONS['seoaic_generate_internal_links'] = !empty($_REQUEST['seoaic_generate_internal_links']);
        $SEOAIC_OPTIONS['seoaic_pillar_link_action'] = !empty($_REQUEST['seoaic_pillar_link_action']);
        $SEOAIC_OPTIONS['seoaic_show_related_articles'] = !empty($_REQUEST['seoaic_show_related_articles']);
        $SEOAIC_OPTIONS['seoaic_gutenberg_tinymce_on'] = !empty($_REQUEST['seoaic_gutenberg_tinymce_on']) ? 'on' : 'off';
        $SEOAIC_OPTIONS['seoaic_show_generated_content_in_custom_field'] = !empty($_REQUEST['seoaic_show_generated_content_in_custom_field']) ? 1 : 0;
        $SEOAIC_OPTIONS['seoaic_hide_posts'] = !empty($_REQUEST['seoaic_hide_posts']);
        $SEOAIC_OPTIONS['seoaic_activate_content_improvement'] = !empty($_REQUEST['seoaic_activate_content_improvement']) ? 'on' : 'off';
        $SEOAIC_OPTIONS['language_locations'] = !empty($_POST['language_locations']) ? $_POST['language_locations'] : '';
        $SEOAIC_OPTIONS['seoaic_gsc_url'] = !empty($_POST['seoaic_gsc_url']) ? $_POST['seoaic_gsc_url'] : '';
        $SEOAIC_OPTIONS['seoaic_hide_individual_page_graph'] = !empty($_REQUEST['seoaic_hide_individual_page_graph']) ? 1 : 0;

        unset($SEOAIC_OPTIONS['seoaic_server']);

        update_option('seoaic_options', $SEOAIC_OPTIONS);

        $this->competitors->change_our_own_url();

        if(!empty($_POST['seoaic_schedule_changed'])) {
            $this->settings::setup_auto_publish_cron();
        }

        wp_send_json([
            'status' => true,
            'post' => $SEOAIC_OPTIONS
        ]);

        wp_die();
    }

    /**
     * Ajax action - save pillar links
     */
    public function seoaic_pillar_links()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC_OPTIONS;

        foreach ($_POST as $key => $value) {
            if ('seoaic_visible_posts' == $key) {
                $old_value = !empty($SEOAIC_OPTIONS[$key]) ? $SEOAIC_OPTIONS[$key] : [];
                $this->update_seoaic_posts_visibility_meta($old_value, $value);
            }

            switch ($key) {
                case 'seoaic_pillar_links':
                case 'seoaic_multilanguages':
                    if (is_array($value)) {
                        $SEOAIC_OPTIONS[$key] = [];
                        foreach ($value as $item) {
                            $item = map_deep($item, 'sanitize_text_field' );
                            if ($key === 'seoaic_pillar_links') {
                                $c = [];

                                foreach ($value as $a) {

                                    if (!empty($a['url'] && !empty($a['text']))) {
                                        $c[] = [
                                            'lang' => sanitize_text_field($a['lang']),
                                            'name' => sanitize_text_field($a['name']),
                                            'url' => sanitize_text_field($a['url']),
                                            'text' => sanitize_text_field($a['text']),
                                        ];
                                    }
                                }

                                $SEOAIC_OPTIONS[$key] = $c;

                            } else {
                                $SEOAIC_OPTIONS[$key][] = $item;
                            }
                        }
                    } else {
                        $SEOAIC_OPTIONS[$key] = stripslashes(sanitize_textarea_field($value));
                    }
                break;
            }
        }


        $SEOAIC_OPTIONS['seoaic_pillar_link_action'] = !empty($_REQUEST['seoaic_pillar_link_action']);

        update_option('seoaic_options', $SEOAIC_OPTIONS);

        wp_send_json([
            'status' => true
        ]);
    }

    private function update_seoaic_posts_visibility_meta($old_value=[], $value=[]) {
        $meta_key = 'seoaic_visible_post';
        $filter_empty = function($item) {
            return !empty(trim($item));
        };
        $old_value = array_filter($old_value, $filter_empty);
        $value = array_values(array_filter($value, $filter_empty));

        $remove_values = array_diff($old_value, $value);
        $create_values = array_diff($value, $old_value);

        if (!empty($remove_values)) {
            foreach ($remove_values as $old_id) {
                // Updating to an empty value instead of delete
                // to reduce the DB table ID counter usage
                // in case of frequent changes.
                update_post_meta($old_id, $meta_key, '');
            }
        }

        if (!empty($create_values)) {
            foreach ($create_values as $id) {
                update_post_meta($id, $meta_key, 1);
            }
        }
    }

    public function seoaic_setinfo()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $SEOAIC_OPTIONS;

        foreach ($_POST as $key => $value) {
            switch ($key) {
                case 'seoaic_business_name':
                case 'seoaic_location':
                case 'seoaic_phone':
                    $SEOAIC_OPTIONS[$key] = sanitize_text_field($value);
                    break;
            }
        }
        $SEOAIC_OPTIONS['seoaic_language'] = seoaic_get_preferred_language($SEOAIC_OPTIONS['seoaic_location']);

        update_option('seoaic_options', $SEOAIC_OPTIONS);

        wp_send_json([
            'status'  => 'success',
        ]);
    }

    /**
     * Enqueue necessary admin styles and scripts
     */
    public function seoaic_admin_enqueue_scripts()
    {
        $current_version = get_plugin_data(SEOAIC_FILE)['Version'];

        wp_enqueue_style('seoaic_admin_global_css', SEOAIC_URL . 'assets/css/seoaic-admin-global.css', array(), $current_version);

        $pos = strpos(get_current_screen()->base, 'seoaic');
        if (!($pos || $pos === 0)) {
            return;
        }

        wp_enqueue_style('seoaic_admin_css', SEOAIC_URL . 'assets/css/seoaic-admin.css', array(), $current_version);
        wp_enqueue_style('seoaic_admin_fonts_css', SEOAIC_URL . 'assets/fonts/fonts.css');
        wp_enqueue_style('seoaic_admin_main_css', SEOAIC_URL . 'assets/css/main.min.css', array(), $current_version);

        wp_register_script('seoaic_admin_main_js', SEOAIC_URL . 'assets/js/main.min.js', array(), $current_version, true);
        wp_enqueue_script('seoaic_admin_main_js', SEOAIC_URL . 'assets/js/main.min.js');
        wp_localize_script('seoaic_admin_main_js', 'adminPage', array(
            'adminUrl' => SEOAIC::getAdminUrl('admin.php')
        ));

        wp_add_inline_style('seoaic_admin_main_css', MultistepForm::makeInlineStyles());

        $apiParams = [
            'root' => esc_url_raw(rest_url()),
            'nonce' => wp_create_nonce(AbstractAPI::SEOAIC_REST_API_ACTION),
        ];
        wp_localize_script('seoaic_admin_main_js', 'wpApiSettings', $apiParams);
    }

    public function seoaic_front_enqueue_scripts()
    {
        $current_version = get_plugin_data(SEOAIC_FILE)['Version'];

        wp_enqueue_style('seoaic_front_main_css', SEOAIC_URL . 'assets/css/front.min.css', array(), $current_version);
        wp_add_inline_style('seoaic_front_main_css', MultistepForm::makeInlineStyles());
        wp_add_inline_style('seoaic_front_main_css', InteractiveArticleBlock::makeInlineStyles());
        // wp_add_inline_style('seoaic_front_main_css', SEOAIC_SETTINGS::getCustomTemplateCSS());

        wp_register_script('seoaic_front_main_js', SEOAIC_URL . 'assets/js/front.min.js', array(), $current_version, true);
        wp_enqueue_script('seoaic_front_main_js', SEOAIC_URL . 'assets/js/front.min.js');

        $apiParams = [
            'root' => esc_url_raw(rest_url()),
            'nonce' => wp_create_nonce(AbstractAPI::SEOAIC_REST_API_ACTION),
        ];

        wp_localize_script('seoaic_front_main_js', 'wpApiSettings', $apiParams);
    }

    // public function seoaic_update_company_credits()
    // {
    //     global $SEOAIC_OPTIONS;

    //     if (!$this->auth->check_api_token($_REQUEST['email'], $_REQUEST['token'])) {
    //         echo 'error';
    //         wp_die();
    //     }

    //     if ( !empty($_REQUEST['credits']) ) {
    //         $credits = json_decode(stripslashes($_REQUEST['credits']), true);
    //         $this->set_api_credits($credits);
    //     }
    // }

    public function seoaic_send_upgrade_plan()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (empty($_REQUEST['email'])) {
            SEOAICAjaxResponse::alert('Email can`t be empty!')->wpSend();
        }

        $postsNum = intval($_REQUEST['postsNum']);
        $ideasNum = intval($_REQUEST['ideasNum']);
        $email = $_REQUEST['email'];

        $data = [
            'email' => $email,
            'posts' => $postsNum,
            'ideas' => $ideasNum,
        ];

        $result = $this->curl->init('api/companies/upgrade-credits-request', $data, true, true, true);

        if (!empty($result)) {
            SEOAICAjaxResponse::alert('Request sent')->wpSend();
        }
    }

    public function popups()
    {
        $pos = strpos(get_current_screen()->base, 'seoaic');
        if (!($pos || $pos === 0)) {
            return;
        }

        include_once(SEOAIC_DIR . 'inc/view/popups/confirm-modal.php');
        include_once(SEOAIC_DIR . 'inc/view/popups/alert-modal.php');
        include_once(SEOAIC_DIR . 'inc/view/popups/remove-modal.php');

        // include_once(SEOAIC_DIR . 'inc/view/popups/generated-post.php');
        include_once(SEOAIC_DIR . 'inc/view/popups/post-mass-creation.php');
        include_once(SEOAIC_DIR . 'inc/view/popups/generate-ideas.php');
        include_once(SEOAIC_DIR . 'inc/view/popups/generate-ideas-new-keywords.php');
        include_once(SEOAIC_DIR . 'inc/view/popups/add-keyword.php');
        // include_once(SEOAIC_DIR . 'inc/view/popups/serp-keyword.php');
        // include_once(SEOAIC_DIR . 'inc/view/popups/competitor-compare.php');
        // include_once(SEOAIC_DIR . 'inc/view/popups/search-terms-posts.php');
        // include_once(SEOAIC_DIR . 'inc/view/popups/search-terms-update-modal.php');
        include_once(SEOAIC_DIR . 'inc/view/popups/improve-modal.php');
    }

    public function set_api_credits($credits = [])
    {
        if (!empty($credits['client_version'])) {
            update_option('seoaic_client_version', sanitize_text_field($credits['client_version']));
        }
        update_option('seoaic_posts_credit', intval($credits['posts_limit']) - intval($credits['posts_used']));
        update_option('seoaic_ideas_credit', intval($credits['ideas_limit']) - intval($credits['ideas_used']));
        update_option('seoaic_frames_credit', intval($credits['frames_limit']) - intval($credits['frames_used']));
        update_option('seoaic_keywords_credit', intval($credits['keywords_limit']) - intval($credits['keywords_used']));
        update_option('seoaic_keywords_stats_credit', intval($credits['keywords_stats_limit']) - intval($credits['keywords_stats_used']));

        $imagesCredit = isset($credits['images_limit']) && isset($credits['images_used'])
            ? intval($credits['images_limit']) - intval($credits['images_used'])
            : 0;
        update_option('seoaic_images_credit', $imagesCredit);
        update_option('seoaic_images_credit_limit', $credits['images_limit']);
    }

    public function get_api_credits() {
        $credits = [
            'ideas' => 0,
            'frames' => 0,
            'posts' => 0,
            'keywords' => 0,
            'keywords_stats' => 0,
            'images' => 0,
        ];
        foreach ($credits as $key => $credit) {
            $credits[$key] = get_option('seoaic_' . $key . '_credit', true);
        }

        return $credits;
    }

    public function seoaic_admin_notice () {
        $current_version = get_plugin_data(SEOAIC_FILE)['Version'];
        $uploaded_version = get_option('seoaic_client_version', true);

        if ( version_compare($current_version, $uploaded_version) < 0 ) {
            echo '<div class="notice notice-warning">' . esc_html__('SEO AI plugin has new version', 'seoaic') . ' ' . esc_html($uploaded_version) . '! Please,
                    <button type="button"
                        class="update-plugin-button seoaic-ajax-button"
                        data-action="seoaic_update_plugin"
                        data-callback="window_reload"
                    >update</button>.
                </div>';
        }
    }

    public function get_background_process_loader($return = false)
    {
        if ($return) {
            ob_start();
        }

        $postsGenerationLoader = new PostsGenerationLoader();
        $this->makeBackgroundGenerationLoader($return, $postsGenerationLoader);

        $postsEditLoader = new PostsEditLoader();
        $this->makeBackgroundGenerationLoader($return, $postsEditLoader);

        $postsReviewLoader = new PostsReviewLoader();
        $this->makeBackgroundGenerationLoader($return, $postsReviewLoader);

        if ($return) {
            return ob_get_clean();
        }
    }

    private function makeBackgroundGenerationLoader($return, $loader)
    {
        $option = $loader::getPostsOption();

        if ($return) {
            ob_start();
        }

        if (
            !empty($option)
            && $option['total']
        ) {
            $total = array_unique($option['total']);
            $totalCount = count($total);
            $width = !empty($totalCount) ? count($option['done']) / $totalCount * 100 : 0;
            ?>
            <div id="<?php echo esc_attr($loader->getID());?>"
                class="seoaic-admin-posts-loader <?php echo $width === 100 ? 'seoaic-background-process-finished' : '';?>"
                title="<?php esc_attr_e($loader->getTitle());?>"
            >
                <div class="seoaic-background-process-box" style="background-color:<?php echo esc_attr($loader->getBackgroundColor());?>;">
                    <div class="seoaic-background-process-loader" style="width:<?php echo esc_attr($width);?>%; background-color:<?php echo esc_attr($loader->getFillColor());?>;"></div>
                    <div class="seoaic-background-process-loader seoaic-background-process-loader-bottom" style="width:<?php echo esc_attr($width);?>%; background-color:<?php echo esc_attr($loader->getFillColor());?>;"></div>
                    <div class="seoaic-background-process-content">
                        <div class="seoaic-background-process-content-overflow">
                            <p><b><?php esc_html_e($loader->getTitle());?>:</b></p>
                            <?php foreach ($total as $id) {
                                ?>
                                <p class="seoaic-background-process-p-<?php echo esc_attr($id) . (in_array($id, $option['done']) ? ' seoaic-background-process-generated' : '');?>"><b><?php echo esc_html($id);?></b> - <?php echo esc_html(get_the_title($id));?></p>
                                <?php
                            }
                            ?>
                        </div>
                        <div class="seoaic-background-process-control">
                            <button type="button" class="seoaic-background-process-closer"><?php esc_html_e('Minimize panel', 'seoaic');?></button>
                            <?php
                            if ($width === 100) {
                                ?>
                                <button type="button"
                                        class="seoaic-background-process-close modal-button confirm-modal-button"
                                        data-modal="#seoaic-confirm-modal"
                                        data-action="<?php echo esc_attr($loader->getCloseAction());?>"
                                        data-form-callback="window_reload"
                                        data-content="<?php esc_html_e('Do you want to close panel?', 'seoaic');?>"
                                ><?php esc_html_e('Close panel', 'seoaic');?></button>
                                <?php
                            } else {
                                if ($loader->isCheckManuallyButtonDisplayed) {
                                    ?>
                                    <button type="button"
                                            class="seoaic-check-manually modal-button confirm-modal-button"
                                            data-modal="#seoaic-confirm-modal"
                                            data-action="<?php echo esc_attr($loader->getCheckManualyAction());?>"
                                            data-form-callback="window_reload"
                                            data-content="<?php esc_html_e('Do you want to pull results manually?', 'seoaic');?>"
                                    ><?php esc_html_e('Check results manually', 'seoaic');?></button>
                                    <?php
                                }
                                if ($loader->isStopButtonDisplayed) {
                                    ?>
                                    <button type="button"
                                            class="seoaic-background-process-stop modal-button confirm-modal-button"
                                            data-modal="#seoaic-confirm-modal"
                                            data-action="<?php echo esc_attr($loader->getStopAction());?>"
                                            data-form-callback="window_reload"
                                            data-content="<?php esc_html_e('Do you want to stop background process?', 'seoaic');?>"
                                    ><?php esc_html_e('Stop process', 'seoaic');?></button>
                                    <?php
                                }
                            }
                            ?>
                        </div>
                    </div>
                    <button type="button" class="seoaic-background-process-opener"></button>
                </div>
            </div>
            <?php
        }

        if ($return) {
            $result = ob_get_contents();
            ob_end_clean();
            return $result;
        }
    }

    // String to slug
    public static function seoaicSlugify($text){
        // replace non letter or digits by -
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        // trim
        $text = trim($text, '-');

        // remove duplicated - symbols
        $text = preg_replace('~-+~', '-', $text);

        // lowercase
        $text = strtolower($text);

        if (empty($text)) {
            return 'n-a';
        }

        return $text;
    }

    // Upload extermal images to media
    public static function seoaicUploadFile( $url, $img_tile ) {
        include_once( ABSPATH . 'wp-admin/includes/image.php' );
        $image_url = $url;
        $loop = explode('/', getimagesize($image_url)['mime']);
        $imagetype = end($loop);

        if (
            !ImageHelpers::isAllowedExtension($imagetype)
            || !ImageHelpers::isAllowedContentType($url)
        ) {
            return false;
        }

        $uniq_name = $img_tile ? self::seoaicSlugify($img_tile) . '_' . (int)microtime(true) : date('dmY').''. (int)microtime(true);
        $filename = $uniq_name.'.'.$imagetype;

        $uploaddir = wp_upload_dir();
        $uploadfile = $uploaddir['path'] . '/' . $filename;
        $contents = file_get_contents($image_url);
        $savefile = fopen($uploadfile, 'w');
        fwrite($savefile, $contents);
        fclose($savefile);

        $wp_filetype = wp_check_filetype(basename($filename), null);
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => $img_tile,
            'post_content' => '',
            'post_status' => 'inherit'
        );

        $attach_id = wp_insert_attachment( $attachment, $uploadfile );
        $imagenew = get_post( $attach_id );
        $fullsizepath = get_attached_file( $imagenew->ID );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
        wp_update_attachment_metadata( $attach_id, $attach_data );

        return $attach_id;

    }

    public static function getSEOAICData()
    {
        global $SEOAIC_OPTIONS;

        $seoaicData = [
            'name' => !empty($SEOAIC_OPTIONS['seoaic_business_name']) ? $SEOAIC_OPTIONS['seoaic_business_name'] : get_option('blogname', true),
            'industry' => !empty($SEOAIC_OPTIONS['seoaic_industry']) ? " on the industry of " . $SEOAIC_OPTIONS['seoaic_industry'] : '',
            'desc' => !empty($SEOAIC_OPTIONS['seoaic_business_description']) ? $SEOAIC_OPTIONS['seoaic_business_description'] : get_option('blogdescription', true),
            'writing_style' => !empty($SEOAIC_OPTIONS['seoaic_writing_style']) ? $SEOAIC_OPTIONS['seoaic_writing_style'] : '',
            'content_guidelines' => !empty($SEOAIC_OPTIONS['seoaic_content_guidelines']) ? $SEOAIC_OPTIONS['seoaic_content_guidelines'] : '',
        ];

        return $seoaicData;
    }

    public function getDefaultLanguageName()
    {
        if ($this->multilang->is_multilang()) {
            $lang = $this->multilang->get_default_language('name');

            if (!empty($lang)) {
                return $lang;
            }
        }

        return SEOAIC_SETTINGS::getLanguage();
    }

    public static function seoaicSettingsGetPostTypeTemplates()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        if (!empty($_REQUEST['post_type'])) {
            $postTemplates = get_page_templates(null, $_REQUEST['post_type']);
            SEOAICAjaxResponse::success()->addFields([
                'options' => self::makePostTemplatesOptions($postTemplates)
            ])->wpSend();
        }
    }

    public static function makePostTemplatesOptions($templates=[], $selectedPostTemplate='')
    {
        global $SEOAIC_OPTIONS;

        if (empty($selectedPostTemplate)) {
            $selectedPostTemplate = !empty($SEOAIC_OPTIONS['seoaic_post_template']) ? $SEOAIC_OPTIONS['seoaic_post_template'] : '';
        }

        ob_start();

        if (is_array($templates)) {
            $templates = array_reverse($templates, true);
            $templates['Default template'] = '';
            $templates = array_reverse($templates, true);

            foreach ($templates as $tmpltTitle => $tmpltName) {
                $selected = $selectedPostTemplate === $tmpltName ? ' selected' : '';
                ?>
                <option value="<?php echo esc_attr($tmpltName);?>"<?php echo esc_html($selected);?>><?php echo esc_html($tmpltTitle);?></option>
                <?php
            }
        }

        return trim(ob_get_clean());
    }

    public static function makePostTypesOptions($types=[], $selectedPostType=''): void
    {
        $postTypesObjects = get_post_types(['public' => true], 'objects');

        if (is_array($types)) {
            foreach ($postTypesObjects as $postTypeObject) {
                if (!in_array($postTypeObject->name, $types)) {
                    continue;
                }

                $selected = $selectedPostType === $postTypeObject->name ? ' selected' : '';
                ?>
                <option value="<?php echo esc_attr($postTypeObject->name);?>"<?php echo esc_html($selected);?>><?php echo esc_html($postTypeObject->label) . " (" . esc_html($postTypeObject->name) . ")";?></option>
                <?php
            }
        }
    }

    public static function getAdminUrl($path='')
    {
        return admin_url($path);
    }

    // public function registerGutenbergBlocks()
    // {
    //     if (function_exists('register_block_type')) {
    //         register_block_type(dirname(SEOAIC_FILE) . '/gutenberg/content-editor/build/');
    //     }
    // }

    public function seoaicEnqueueEditorAssets() {
        if (is_admin()) {
            wp_localize_script('wp-api', 'wpApiSettings', [
                'root' => esc_url_raw(rest_url()),
                'nonce' => wp_create_nonce('wp_rest'),
                'sidebar_slots_available' => version_compare(get_bloginfo('version'), '6.6.2', '>='),
            ]);
            wp_enqueue_script('wp-api');

            wp_enqueue_style('dashicons');

            wp_enqueue_style(
                'seoaic-editor-styles',
                // plugins_url('gutenberg/content-editor/build/style-index.css', SEOAIC_FILE)
                plugins_url('gutenberg/content-editor/build/content-editor/index.css', SEOAIC_FILE)
            );
            wp_enqueue_style(
                'seoaic-editor-styles',
                plugins_url('gutenberg/content-editor/build/blocks/faq/index.css', SEOAIC_FILE)
            );
        }
    }

    public function getPublicPostsPagedCustomLinksAjax()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        global $wpdb, $SEOAIC_OPTIONS;

        $__POST = wp_unslash($_POST);
        $items = [];
        $page = !empty($__POST['page']) ? $__POST['page'] : 1;

        if (1 == $page) {
            $customLinks = $wpdb->get_col(
                $wpdb->prepare("
                    SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm
                    WHERE pm.meta_key = %s
                    AND pm.meta_value NOT REGEXP '^[0-9]+$'
                ", ['page_link'])
            );

            if (!empty($customLinks)) {
                foreach ($customLinks as $customLink) {
                    if ( // filter custom links
                        !empty($__POST['q'])
                        && $customLink
                        && false === strpos($customLink, $__POST['q'])
                    ) {
                        continue;
                    }

                    $items[] = [
                        'id' => esc_attr($customLink),
                        'text' => esc_html($customLink),
                        // 'permalink' => esc_attr($customLink),
                        'flag' => '',
                    ];
                }
            }
        }

        $args = [
            'post_type' => seoaic_get_post_types(),
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'lang' => '',
            'meta_query' => [ // all posts, without hiding feature
                'relation' => 'OR',
                [
                    'key' => 'seoaic_posted',
                    'compare' => 'EXISTS'
                ],
                [
                    'key' => 'seoaic_posted',
                    'compare' => 'NOT EXISTS'
                ],
            ]
        ];

        if (!empty($__POST['lang'])) {
            $args['lang'] = $__POST['lang'];
        }

        if (!empty($__POST['q'])) {
            $args['post_title_like'] = $__POST['q'];
        }

        $query_total = new WP_Query($args);
        $total_count = $query_total->post_count;

        $args['posts_per_page'] = 10;
        $args['paged'] = $page;
        $query = new WP_Query($args);
        $pages = $query->posts;

        // find post by URL
        if (
            !empty($__POST['q'])
            && false !== strpos($__POST['q'], '/')
        ) {
            $postID = url_to_postid($__POST['q']);

            if ($postID) {
                $postByURL = get_post($postID);
                array_unshift($pages, $postByURL);
            }
        }

        if (!empty($pages) && is_array($pages)) {
            foreach ($pages as $page) {
                $post_id = isset($page->ID) ? (int)$page->ID : 0;
                $post_title = isset($page->post_title) ? $page->post_title : '';

                if (!$post_id) {
                    continue;
                }


                $post_permalink = rtrim(get_permalink($post_id), '/');

                if (!$post_permalink) {
                    continue;
                }

                $excluded_urls      = !empty($_POST['excluded_urls']) && is_array($_POST['excluded_urls']) ? $_POST['excluded_urls'] : [];
                $exclude_redirected = !empty($_POST['exclude_redirected_posts']);

                $redirects_301      = $SEOAIC_OPTIONS['redirect']['301'] ?? [];
                $redirects_410      = $SEOAIC_OPTIONS['redirect']['410'] ?? [];

                if (in_array($post_permalink, $excluded_urls, true)) {
                    continue;
                }

                if (
                    $exclude_redirected &&
                    (
                        in_array($post_permalink, array_keys($redirects_301), true) ||
                        in_array($post_permalink, array_keys($redirects_410), true)
                    )
                ) {
                    continue;
                }

                list('language' => $language, 'flag' => $flag) = $this->multilang->getPostLanguageAndFlag($post_id);
                $items[] = [
                    'id' => esc_attr($post_id),
                    'text' => esc_html($post_title),
                    'permalink' => esc_url($post_permalink),
                    'flag' => $flag,
                ];
            }
        }

        SEOAICAjaxResponse::success()->addFields([
            'items' => $items,
            'total_count' => $total_count,
        ])->wpSend();
    }

    public function getSEOAICPublicPostsPagedAjax()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $items = [];
        $args = [
            'post_type'         => seoaic_get_post_types(),
            'post_status'       => ['publish', 'future'],
            'posts_per_page'    => -1,
            'meta_key'          => 'seoaic_posted',
            'meta_value'        => '1',
            'lang' => '',
        ];

        if (!empty($_POST['q'])) {
            $args['post_title_like'] = $_POST['q'];
        }

        $query_total = new WP_Query($args);
        $total_count = $query_total->post_count;

        $args['posts_per_page'] = 10;
        $args['paged'] = !empty($_POST['page']) ? $_POST['page'] : 1;
        $query = new WP_Query($args);
        $pages = $query->posts;

        if (!empty($pages)) {
            foreach ($pages as $page) {
                $items[] = [
                    'id' => esc_attr($page->ID),
                    'text' => $page->post_title,
                ];
            }
        }

        SEOAICAjaxResponse::success()->addFields([
            'items' => $items,
            'total_count' => $total_count,
        ])->wpSend();
    }

    public function getAllPublicPosts()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $args = [
            'post_type' => seoaic_get_post_types(),
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'lang' => '',
            'meta_query' => [
            'relation' => 'OR',
            [
                'key' => 'seoaic_posted',
                'compare' => 'EXISTS'
            ],
            [
                'key' => 'seoaic_posted',
                'compare' => 'NOT EXISTS'
            ],
        ]
        ];

        if (!empty($_POST['q'])) {
            $args['post_title_like'] = $_POST['q'];
        }

        $query_total = new WP_Query($args);
        $total_count = $query_total->found_posts;

        $args['posts_per_page'] = 10;
        $args['paged'] = !empty($_POST['page']) ? $_POST['page'] : 1;
        $query = new WP_Query($args);
        $pages = $query->posts;

        if (!empty($pages)) {
            foreach ($pages as $page) {
                $items[] = [
                    'id' => esc_url(get_permalink($page->ID)),
                    'text' => esc_html($page->post_title),
                    'permalink' => esc_url(get_permalink($page->ID)),
                ];
            }
        }

        SEOAICAjaxResponse::success()->addFields([
            'items' => $items,
            'total_count' => $total_count,
        ])->wpSend();
    }

    public function getAllPublicPostsByTitleOrSlugOrLink()
    {
        check_ajax_referer(SeoaicAjaxValidation::ACTION_STRING);

        $search = !empty($_POST['q']) ? trim($_POST['q']) : '';
        $paged = !empty($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
        $per_page = 10;

        $is_url_search = filter_var($search, FILTER_VALIDATE_URL) || str_contains($search, '/');
        $where_filter = function ($where, $wp_query) use ($search, $is_url_search) {
            global $wpdb;

            if (empty($search)) return $where;

            $like = '%' . $wpdb->esc_like($search) . '%';

            if ($is_url_search) {
                $where .= $wpdb->prepare(" AND {$wpdb->posts}.guid LIKE %s", $like);
            } else {
                $where .= $wpdb->prepare(" OR {$wpdb->posts}.post_name LIKE %s", $like);
            }

            return $where;
        };

        add_filter('posts_where', $where_filter, 10, 2);

        $args = [
            'post_type' => seoaic_get_post_types(),
            'post_status' => 'publish',
            's' => $search,
            'posts_per_page' => $per_page,
            'paged' => $paged,
            'lang' => '',
            'meta_query' => [
                'relation' => 'OR',
                [
                    'key' => 'seoaic_posted',
                    'compare' => 'EXISTS'
                ],
                [
                    'key' => 'seoaic_posted',
                    'compare' => 'NOT EXISTS'
                ],
            ]
        ];

        $query = new WP_Query($args);
        remove_filter('posts_where', $where_filter, 10);
        $items = [];

        foreach ($query->posts as $post) {
            $items[] = [
                'id' => esc_url(get_permalink($post->ID)),
                'text' => esc_html($post->post_title),
                'permalink' => esc_url(get_permalink($post->ID)),
            ];
        }

        SEOAICAjaxResponse::success()->addFields([
            'items' => $items,
            'total_count' => $query->found_posts,
        ])->wpSend();
    }
    public static function makeAuthorTemplateOptions($selectedAuthor='')
    {
        ob_start();

        $authors = get_users_can_edit_posts();

        if (is_array($authors)) {
            foreach ($authors as $author) {
                $selected = (int)$selectedAuthor === $author->ID ? ' selected' : '';
                ?>
                <option value="<?php echo esc_attr($author->ID);?>"<?php echo esc_html($selected);?>><?php echo esc_html($author->display_name);?></option>
                <?php
            }
        }

        return trim(ob_get_clean());
    }
}
