<?php

use SEOAIC\posts_mass_actions\ThumbnailsGenerate;
use SEOAIC\SEOAIC;
use SEOAIC\SEOAIC_POSTS;
use SEOAIC\SEOAIC_SETTINGS;
use SEOAIC\SeoaicContentImprovement;

/**
 * Get backend server url
 *
 * @param string $uri
 * @return string
 */
function seoai_get_backend_url( $uri = '' ) {
    $url = defined( 'SEOAIC_BACK_URL' ) && SEOAIC_BACK_URL ? untrailingslashit( SEOAIC_BACK_URL ) : '';

    if ( $uri ) {
        $uri = ltrim( untrailingslashit( $uri ), '/' );
        $url .= '/' . $uri;
    }

    return trim($url);
}

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

    return $current_version;
}

function seoaic_get_post_types() {
    $post_types = get_post_types(['public' => true]);

    unset($post_types['attachment']);
    unset($post_types['elementor_library']);
    unset($post_types['bgh_wg']);
    unset($post_types['e-landing-page']);
    unset($post_types['eeco-vd']);
    unset($post_types['eeco_pg']);
    unset($post_types['gwp_campaign']);
    sort($post_types);

    return $post_types;
}

function seoai_get_logo( $image ) {
    $image = '<img src="' . SEOAIC_URL . 'assets/img/' . $image . '" width="165" height="44" fetchpriority="high">';

    return $image;
}

function seoaic_get_languages () {
    $languages = [
        'Arabic',
        'Bulgarian',
        'Croatian',
        'Czech',
        'Danish',
        'Dutch',
        'English',
        'Estonian',
        'Finnish',
        'French',
        'German',
        'Greek',
        'Hungarian',
        'Irish',
        'Italian',
        'Japanese',
        'Latvian',
        'Lithuanian',
        'Norwegian (Bokmål)',
        'Polish',
        'Portuguese',
        'Romanian',
        'Russian',
        'Spanish',
        'Swedish',
        'Thai',
        'Turkish',
        'Ukrainian'
    ];
    sort($languages);
    return $languages;
}

function seoaic_get_writing_styles () {
    $styles = [
        'Default',
        'Friendly',
        'Professional',
        'Educational',
        'Formal',
        'Easily approachable',
    ];
    return $styles;
}

function seoaic_get_locations () {
    $locations = [
        "Afghanistan",
        "Albania",
        "Algeria",
        "Andorra",
        "Angola",
        "Antigua and Barbuda",
        "Argentina",
        "Armenia",
        "Australia",
        "Austria",
        "Azerbaijan",
        "Bahrain",
        "Bangladesh",
        "Barbados",
        "Belarus",
        "Belgium",
        "Belize",
        "Benin",
        "Bhutan",
        "Bolivia",
        "Bosnia and Herzegovina",
        "Botswana",
        "Brazil",
        "Brunei",
        "Bulgaria",
        "Burkina Faso",
        "Burundi",
        "Cabo Verde",
        "Cambodia",
        "Cameroon",
        "Canada",
        "Central African Republic",
        "Chad",
        "Channel Islands",
        "Chile",
        "China",
        "Colombia",
        "Comoros",
        "Congo",
        "Costa Rica",
        "Cote d'Ivoire",
        "Croatia",
        "Cuba",
        "Cyprus",
        "Czechia",
        "Denmark",
        "Djibouti",
        "Dominica",
        "Dominican Republic",
        "DR Congo",
        "Ecuador",
        "Egypt",
        "El Salvador",
        "Equatorial Guinea",
        "Eritrea",
        "Estonia",
        "Eswatini",
        "Ethiopia",
        "Faeroe Islands",
        "Finland",
        "France",
        "French Guiana",
        "Gabon",
        "Gambia",
        "Georgia",
        "Germany",
        "Ghana",
        "Gibraltar",
        "Greece",
        "Grenada",
        "Guatemala",
        "Guinea",
        "Guinea-Bissau",
        "Guyana",
        "Haiti",
        "Holy See",
        "Honduras",
        "Hong Kong",
        "Hungary",
        "Iceland",
        "India",
        "Indonesia",
        "Iran",
        "Iraq",
        "Ireland",
        "Isle of Man",
        "Israel",
        "Italy",
        "Jamaica",
        "Japan",
        "Jordan",
        "Kazakhstan",
        "Kenya",
        "Kuwait",
        "Kyrgyzstan",
        "Laos",
        "Latvia",
        "Lebanon",
        "Lesotho",
        "Liberia",
        "Libya",
        "Liechtenstein",
        "Lithuania",
        "Luxembourg",
        "Macao",
        "Madagascar",
        "Malawi",
        "Malaysia",
        "Maldives",
        "Mali",
        "Malta",
        "Mauritania",
        "Mauritius",
        "Mayotte",
        "Mexico",
        "Moldova",
        "Monaco",
        "Mongolia",
        "Montenegro",
        "Morocco",
        "Mozambique",
        "Myanmar (Burma)",
        "Namibia",
        "Nepal",
        "Netherlands",
        "New Zealand",
        "Nicaragua",
        "Niger",
        "Nigeria",
        "North Korea",
        "North Macedonia",
        "Norway",
        "Oman",
        "Pakistan",
        "Panama",
        "Paraguay",
        "Peru",
        "Philippines",
        "Poland",
        "Portugal",
        "Qatar",
        "Réunion",
        "Romania",
        "Russia",
        "Rwanda",
        "Saint Helena",
        "Saint Kitts and Nevis",
        "Saint Lucia",
        "Saint Vincent and the Grenadines",
        "San Marino",
        "Sao Tome & Principe",
        "Saudi Arabia",
        "Senegal",
        "Serbia",
        "Seychelles",
        "Sierra Leone",
        "Singapore",
        "Slovakia",
        "Slovenia",
        "Somalia",
        "South Africa",
        "South Korea",
        "South Sudan",
        "Spain",
        "Sri Lanka",
        "State of Palestine",
        "Sudan",
        "Suriname",
        "Sweden",
        "Switzerland",
        "Syria",
        "Taiwan",
        "Tajikistan",
        "Tanzania",
        "Thailand",
        "The Bahamas",
        "Timor-Leste",
        "Togo",
        "Trinidad and Tobago",
        "Tunisia",
        "Turkiye",
        "Turkmenistan",
        "Uganda",
        "Ukraine",
        "United Arab Emirates",
        "United Kingdom",
        "United States",
        "Uruguay",
        "Uzbekistan",
        "Venezuela",
        "Vietnam",
        "Western Sahara",
        "Yemen",
        "Zambia",
        "Zimbabwe"
    ];
    return $locations;
}

// Available countries Google ads
function seoaic_google_ads_available_locations() {
    $locations = [
        "Algeria",
        "Angola",
        "Azerbaijan",
        "Argentina",
        "Australia",
        "Austria",
        "Bahrain",
        "Bangladesh",
        "Armenia",
        "Belgium",
        "Bolivia",
        "Brazil",
        "Bulgaria",
        "Myanmar (Burma)",
        "Cambodia",
        "Cameroon",
        "Canada",
        "Sri Lanka",
        "Chile",
        "Taiwan",
        "Colombia",
        "Costa Rica",
        "Croatia",
        "Cyprus",
        "Czechia",
        "Denmark",
        "Ecuador",
        "El Salvador",
        "Estonia",
        "Finland",
        "France",
        "Germany",
        "Ghana",
        "Greece",
        "Guatemala",
        "Hong Kong",
        "Hungary",
        "India",
        "Indonesia",
        "Ireland",
        "Israel",
        "Italy",
        "Cote d'Ivoire",
        "Japan",
        "Kazakhstan",
        "Jordan",
        "Kenya",
        "South Korea",
        "Latvia",
        "Lithuania",
        "Malaysia",
        "Malta",
        "Mexico",
        "Morocco",
        "Netherlands",
        "New Zealand",
        "Nicaragua",
        "Nigeria",
        "Norway",
        "Pakistan",
        "Panama",
        "Paraguay",
        "Peru",
        "Philippines",
        "Poland",
        "Portugal",
        "Romania",
        "Saudi Arabia",
        "Senegal",
        "Serbia",
        "Singapore",
        "Slovakia",
        "Vietnam",
        "Slovenia",
        "South Africa",
        "Spain",
        "Sweden",
        "Switzerland",
        "Thailand",
        "United Arab Emirates",
        "Tunisia",
        "Turkiye",
        "Ukraine",
        "North Macedonia",
        "Egypt",
        "United Kingdom",
        "United States",
        "Burkina Faso",
        "Uruguay",
        "Venezuela",
    ];
    return $locations;
}

function seoaic_get_preferred_language($location)
{
    switch ($location) {
        case "Bulgaria":
            $preferred_language = "Bulgarian";
            break;
        case "Croatia":
            $preferred_language = "Croatian";
            break;
        case "Czech Republic":
            $preferred_language = "Czech";
            break;
        case "Denmark":
            $preferred_language = "Danish";
            break;
        case "Netherlands":
            $preferred_language = "Dutch";
            break;
        case "Norway":
            $preferred_language = "Norwegian (Bokmål)";
            break;
        case "Estonia":
            $preferred_language = "Estonian";
            break;
        case "Finland":
            $preferred_language = "Finnish";
            break;
        case "France":
            $preferred_language = "French";
            break;
        case "Germany":
            $preferred_language = "German";
            break;
        case "Greece":
            $preferred_language = "Greek";
            break;
        case "Hungary":
            $preferred_language = "Hungarian";
            break;
        case "Ireland":
            $preferred_language = "Irish";
            break;
        case "Italy":
            $preferred_language = "Italian";
            break;
        case "Japan":
            $preferred_language = "Japanese";
            break;
        case "Latvia":
            $preferred_language = "Latvian";
            break;
        case "Lithuania":
            $preferred_language = "Lithuanian";
            break;
        case "Poland":
            $preferred_language = "Polish";
            break;
        case "Portugal":
            $preferred_language = "Portuguese";
            break;
        case "Romania":
            $preferred_language = "Romanian";
            break;
        case "Russia":
            $preferred_language = "Russian";
            break;
        case "Spain":
            $preferred_language = "Spanish";
            break;
        case "Sweden":
            $preferred_language = "Swedish";
            break;
        case "Thailand":
            $preferred_language = "Thai";
            break;
        case "Turkiye":
            $preferred_language = "Turkish";
            break;
        case "Ukraine":
            $preferred_language = "Ukrainian";
            break;
        default:
            $preferred_language = "English";
    }

    return $preferred_language;
}

function seoaic_get_image_generators () {
    return [
        'gpt' => 'GPT',
        'clipdrop' => 'Clipdrop',
        'no_image' => 'No image',
    ];
}

function seoaic_get_default_image_generator () {
    global $SEOAIC_OPTIONS;
    if ( !empty($SEOAIC_OPTIONS['seoaic_image_generator']) ) {
        return $SEOAIC_OPTIONS['seoaic_image_generator'];
    }

    return 'no_image';
}

function seoaic_get_categories( $post_type = 'post', $id = 0, $select_view = null ) {
    global $SEOAIC, $SEOAIC_OPTIONS;

    $terms = $SEOAIC->multilang->get_terms( $post_type );
    $termsArray = [];
    foreach ( $terms as $term ) {
        if ( !empty($SEOAIC_OPTIONS['seoaic-exclude-taxonomy']) && in_array($term->taxonomy, $SEOAIC_OPTIONS['seoaic-exclude-taxonomy']) )
            continue;
        $termsArray[] = $term;
    }

    $checkboxes = '<div class="toggle-choose-role">
                       <div class="checkbox-list">';

    if ( !empty($id) ) {
        $idea_content = get_post_meta($id, 'seoaic_idea_content', true);
        if ( empty($idea_content) ) {
            $choosen_categories = $SEOAIC_OPTIONS['seoaic_default_category'] ?? [];
        } else {
            $idea_content = json_decode($idea_content, true);
            $choosen_categories = $idea_content['idea_category'] ?? [];
        }
    } else {
        $choosen_categories = $SEOAIC_OPTIONS['seoaic_default_category'] ?? [];
    }

    usort($termsArray, 'seoaic_compare_terms_taxanomy');

    if ( $select_view ) {
        $select = '<div class="d-flex seoaic-flex-column">';
        $select .= '<label>' . esc_html__('Select category', 'seoaic') . '</label>';
        $select .= '<select multiple name="seoaic_default_category" class="seoaic-form-item seoaic-ajax-field">';

        foreach ( $termsArray as $term ) {
            if ( $term->slug === 'uncategorized' ) continue;
            $selected = in_array($term->term_id, $choosen_categories) ? ' selected' : '';
            $taxonomy = get_taxonomy($term->taxonomy);
            $label = $taxonomy ? $taxonomy->label . ': ' : '';

            $select .= '<option value="' . esc_attr($term->term_id) . '"' . $selected . '>' . esc_html($label . $term->name) . '</option>';
        }

        $select .= '</select></div>';

        return $select;
    }

    $last_taxonomy = '';
    foreach ( $termsArray as $term ) {
        if ( $term->slug === 'uncategorized' ) continue;

        if ( $last_taxonomy !== $term->taxonomy ) {

            $taxonomy = get_taxonomy( $term->taxonomy );
            if (!is_object($taxonomy) || !isset($taxonomy->name)) {
                continue;
            }

            $last_taxonomy = $taxonomy->name;

            $checkboxes .= '<div class="checkbox-wrapper-mc-group">' . esc_html($taxonomy->label) . '</div>';
        }

        $id = $term->term_id . '-' . rand(1000, 5000);
        $checkboxes .= '
        <div class="checkbox-wrapper-mc">
            <input id="seoaic-default-category-' . esc_attr($id) . '" class="seoaic-form-item"
                    name="seoaic_default_category[]"
                    type="checkbox"
                    value="' . esc_attr($term->term_id) . '"';


        if ( !empty($choosen_categories) && is_array($choosen_categories) && in_array($term->term_id, $choosen_categories ) ) {
            $checkboxes .= ' checked ';
        }

        $checkboxes .= '/>
            <label for="seoaic-default-category-' . esc_attr($id) . '" class="check">
                <svg width="18px" height="18px" viewBox="0 0 18 18">
                    <path d="M1,9 L1,3.5 C1,2 2,1 3.5,1 L14.5,1 C16,1 17,2 17,3.5 L17,14.5 C17,16 16,17 14.5,17 L3.5,17 C2,17 1,16 1,14.5 L1,9 Z"></path>
                    <polyline points="1 9 7 14 15 4"></polyline>
                </svg>
                <span>' . esc_html($term->name) . '</span>
            </label>
        </div>';

    }

    if ( $last_taxonomy === '' ) {
        $checkboxes .= esc_html__('No terms for this post type', 'seoaic');
    }

    $checkboxes .= '</div></div>';

    return $checkboxes;
}

function seoaic_get_categories_ids($post_type = 'post', $id = 0) {
    global $SEOAIC, $SEOAIC_OPTIONS;

    $ids = [];
    $terms = $SEOAIC->multilang->get_terms( $post_type );
    $termsArray = [];

    foreach ($terms as $term) {
        if (
            !empty($SEOAIC_OPTIONS['seoaic-exclude-taxonomy'])
            && in_array($term->taxonomy, $SEOAIC_OPTIONS['seoaic-exclude-taxonomy'])
        ) {
            continue;
        }

        $termsArray[] = $term;
    }

    if ( !empty($id) ) {
        $idea_content = get_post_meta($id, 'seoaic_idea_content', true);
        if ( empty($idea_content) ) {
            $choosen_categories = $SEOAIC_OPTIONS['seoaic_default_category'] ?? [];

        } else {
            $idea_content = json_decode($idea_content, true);
            $choosen_categories = $idea_content['idea_category'] ?? [];
        }

    } else {
        $choosen_categories = $SEOAIC_OPTIONS['seoaic_default_category'] ?? [];
    }

    foreach ( $termsArray as $term ) {
        if ( $term->slug === 'uncategorized' ) continue;

        if (in_array($term->term_id, $choosen_categories)) {
            $ids[] = $term->term_id;
        }
    }

    return $ids;
}

function seoaic_get_prompt_template_types()
{
    return [
        'default'       => 'Default',
        'location'      => 'Location based content',
        'educational'   => 'Educational content',
        'how_to'        => 'How-to content',
        'service'       => 'Service introduction content',
        'also_asked'    => 'Also asked content',
        'news'          => 'Listicle content',
        'microkeywords' => 'Landing page content',
    ];
}

add_action('pre_get_posts', 'seoaic_exclude_posts', 99999999, 1);
function seoaic_exclude_posts(WP_Query $query)
{
    global $SEOAIC_OPTIONS;
    $q_post_type = $query->get('post_type');

    if (seoaic_is_post_type_invalid($q_post_type)) {
        return;
    }

    if (
        (!is_admin() || (is_admin() && wp_doing_ajax()))
        && !((strpos($_SERVER['REQUEST_URI'], 'sitemap') !== false)
        && (strpos($_SERVER['REQUEST_URI'], '.xml') !== false))
        && (SEOAIC_SETTINGS::isHidePostsEnabled())
        && !$query->is_feed()
        && !wp_doing_cron()
    ) {
        if (
            !empty($_REQUEST['action']) // do not alter query for next ajax calls
            && in_array($_REQUEST['action'], [
                'seoaic_settings_get_public_seoaic_posts',
                'seoaic_posts_mass_create',
                'seoaic_posts_mass_generate_check_status',
                'seoaic_posts_mass_translate_check_status',
            ])
        ) {
            return;
        }

        if ( // strictly allow all posts
            isset($query->query['skip_hiding'])
            && $query->query['skip_hiding']
        ) {
            return;
        }

        //Hide from ajax responses
        if (is_admin() && wp_doing_ajax() && (strpos($_REQUEST['action'], 'seoaic') !== 0)) {
            seoaic_modify_hiding_query($query);
            return;
        }

        if (is_singular() && $query->is_main_query()) {
            return;
        }

        seoaic_modify_hiding_query($query);
    }
}

function seoaic_is_post_type_invalid($post_type)
{
    $invalid_post_types = [
        'attachment', 'nav_menu_item', 'x-portfolio', 'gwp_campaign', 'product', 'product_variation',
        'cs_header', 'cs_footer', 'cs_layout_archive',
        'cs_layout_single', 'cs_layout_archive_wc', 'cs_layout_single_wc',
        'eeco-volume-discount', 'eeco-volume-discount-campaign', 'eeco-volume-discount-rule',
        'eeco-volume-discount-rule-group', 'eeco-volume-discount-rule-product', 'eeco-vd',
        'cfw_pickup_location','cfw_acr_emails','cfw_order_bumps',
        'acf-field-group','portfolio', 'cookielawinfo',
        'listings', 'shop_order', 'shop_order_refund'
    ];

    if (is_array($post_type)) {
        $theme = wp_get_theme();

        // fix for Enfold theme
        if (
            (
                "Enfold" == $theme->get("Name") // for Enfold theme itself
                || "enfold" == $theme->get("Template") // and its child theme
            )
            && in_array("post", $post_type)
            && in_array("page", $post_type)
            && in_array(SEOAIC_SETTINGS::getSEOAICPostType(), $post_type)
        ) {
            return false;
        }

        return array_intersect($post_type, $invalid_post_types);
    }

    return in_array($post_type, $invalid_post_types);
}

function seoaic_modify_hiding_query(WP_Query $query)
{
    $meta_query = $query->get('meta_query');

    if (seoaic_is_skip_hiding($meta_query)) {
        return;
    }

    $updated_query = [
        'relation' => 'OR',
        [
            'key' => 'seoaic_posted',
            'compare' => 'NOT EXISTS'
        ],
        [
            'key' => 'seoaic_visible_post',
            'compare' => '=',
            'value' => 1
        ]
    ];

    if (!$meta_query) {
        $query->set('meta_query', $updated_query);
    } else {
        $query->set('meta_query', [
            'relation' => 'AND',
            $updated_query,
            $meta_query
        ]);
    }
}

function seoaic_is_skip_hiding($meta_query)
{
    $isSkip = false;
    if ($meta_query) {
        array_map(function($item) use (&$isSkip) {
            if (is_array($item) && array_key_exists('key', $item) && $item['key'] === 'seoaic_posted') {
                $isSkip = true;
            }
        }, $meta_query);
    }

    return $isSkip;
}

function seoaic_additional_related_posts($content) {
    global $SEOAIC_OPTIONS;

    if (
        !is_admin()
        && SEOAIC_SETTINGS::isShowRelatedArticlesEnabled()
    ) {
        $post_id = get_the_ID();
        $meta_value = get_post_meta( $post_id, 'seoaic_posted', true );

        if (!$meta_value) {
            return $content;
        }

        $query = new WP_Query([
            'posts_per_page'        => $SEOAIC_OPTIONS['seoaic_related_articles_count'],
            'ignore_sticky_posts'   => true,
            'post__not_in'          => array( $post_id ),
            'post_type'             => 'any',
            'orderby'               => 'rand',
            'meta_query'            => [
                [
                    'key'       => 'seoaic_posted',
                    'value'     => 1,
                    'compare'   => '='
                ],
            ],
        ]);

        if ($query->have_posts()) {
            $content .= '<h2>' . esc_html__('Related Articles', 'seoaic') . '</h2>';
            $content .= '<ul>';
            while ( $query->have_posts() ) {
                $query->the_post();
                $content .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            wp_reset_postdata();
            $content .= '</ul>';
        }
    }

    return $content;
}
add_filter('the_content', 'seoaic_additional_related_posts', 100, 1);


function seoaic_ssl_verifypeer () {
    global $SEOAIC_OPTIONS;

    $ssl_verifypeer = false;

    if ( !empty($SEOAIC_OPTIONS['seoaic_ssl_verifypeer']) ) {
        $ssl_verifypeer = true;
    }

    return $ssl_verifypeer;
}

function seoaic_compare_terms_taxanomy ($a, $b) {
    return strnatcmp($a->taxonomy, $b->taxonomy);
}


/**
 * Get all registered taxonomies.
 * @return array
 */
function seoaic_get_taxonomies_checkboxes () {
    global $SEOAIC_OPTIONS;

    $post_types = get_post_types(['public' => true], 'objects');

    $checkboxes = '<div class="toggle-choose-role">
                       <div class="checkbox-list">';
    foreach ( $post_types as $key => $post_type ) {
        $taxonomies = get_object_taxonomies(['post_type' => $key]);
        $taxonomiesArray = [];
        foreach ( $taxonomies as $taxonomy) {

            if ( $taxonomy === 'language' ) continue;
            if ( $taxonomy === 'post_translations' ) continue;

            $taxonomiesArray[] = $taxonomy;
        }

        if ( count($taxonomiesArray) === 0 ) continue;

        $checkboxes .= '<div class="checkbox-wrapper-mc-group">' . $post_type->label . '</div>';

        foreach ( $taxonomiesArray as $taxonomy ) {

            $taxonomy = get_taxonomy( $taxonomy );

            $checkboxes .= '
            <div class="checkbox-wrapper-mc">
                <input id="seoaic-exclude-taxonomy-' . $taxonomy->name . '" class="seoaic-form-item"
                        name="seoaic-exclude-taxonomy[]"
                        type="checkbox"
                        value="' . $taxonomy->name . '"';

            if ( !empty($SEOAIC_OPTIONS['seoaic-exclude-taxonomy']) && in_array($taxonomy->name, $SEOAIC_OPTIONS['seoaic-exclude-taxonomy'] ) ) {
                $checkboxes .= ' checked ';
            }

            $checkboxes .= '/>
                <label for="seoaic-exclude-taxonomy-' . $taxonomy->name . '" class="check">
                    <svg width="18px" height="18px" viewBox="0 0 18 18">
                        <path d="M1,9 L1,3.5 C1,2 2,1 3.5,1 L14.5,1 C16,1 17,2 17,3.5 L17,14.5 C17,16 16,17 14.5,17 L3.5,17 C2,17 1,16 1,14.5 L1,9 Z"></path>
                        <polyline points="1 9 7 14 15 4"></polyline>
                    </svg>
                    <span>' . $taxonomy->label . '</span>
                </label>
            </div>';

        }
    }

    $checkboxes .= '</div></div>';
    return $checkboxes;
}

add_action('init', 'seoaic_load_textdomain');

function seoaic_load_textdomain()
{
    load_plugin_textdomain(
        'seoaic',
        false,
        dirname( plugin_basename( SEOAIC_FILE ) ) . '/languages'
    );
}

function SEOAICregisterGutenbergBlocks()
{
    $isGutenbergTinyMCEDisabled = SEOAIC_SETTINGS::isGutenbergTinyMCEDisabled();

    if (
        seoaicIsUserLoggedIn()
        && !$isGutenbergTinyMCEDisabled
    ) {
        if (function_exists('register_block_type')) {
            register_block_type(dirname(SEOAIC_FILE) . '/gutenberg/content-editor/build/content-editor');
            register_block_type(dirname(SEOAIC_FILE) . '/gutenberg/content-editor/build/blocks/faq');
            register_block_type(dirname(SEOAIC_FILE) . '/gutenberg/content-editor/build/blocks/generate-image');
            register_block_type(dirname(SEOAIC_FILE) . '/gutenberg/content-editor/build/blocks/multistep-lead-form');
            register_block_type(dirname(SEOAIC_FILE) . '/gutenberg/content-editor/build/blocks/interactive-article', [
                'api_version' => 3,
                'render_callback' => 'seoaicInteractiveArticleCallback'
            ]);
        }
    }
}
add_action('init', 'SEOAICregisterGutenbergBlocks');

function seoaicInteractiveArticleCallback($blockAttributes, $content)
{
    $paramsJSON = htmlentities(json_encode($blockAttributes, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ENT_NOQUOTES | ENT_SUBSTITUTE);

    return "[seoaic_interactive_block]" . $paramsJSON . "[/seoaic_interactive_block]";
}

function seoaic_custom_tinymce_plugin($plugins) {
    $isGutenbergTinyMCEDisabled = SEOAIC_SETTINGS::isGutenbergTinyMCEDisabled();

    if (
        seoaicIsUserLoggedIn()
        && !$isGutenbergTinyMCEDisabled
    ) {
        $ver = seoaic_get_plugin_version() ? "?ver=" . seoaic_get_plugin_version() : '';
        $plugins['seoaic_button'] = SEOAIC_URL . "tiny-mce/assets/js/tinymce-plugin.js$ver";
    }
    return $plugins;
}
add_filter('mce_external_plugins', 'seoaic_custom_tinymce_plugin', 20);

function seoaic_register_custom_button($buttons) {
    array_push($buttons, 'seoaic_button');
    return $buttons;
}
add_filter('mce_buttons', 'seoaic_register_custom_button', 20);

function add_custom_post_selector_button() {
    $isGutenbergTinyMCEDisabled = SEOAIC_SETTINGS::isGutenbergTinyMCEDisabled();

    if (
        seoaicIsUserLoggedIn()
        && !$isGutenbergTinyMCEDisabled
    ) {
        echo '<button type="button" class="button seoaic-tiny-mce-generate-image">Generate Image by SEOAI</button>';
    }
}
add_action('media_buttons', 'add_custom_post_selector_button', 20);

function seoaic_tiny_mce_enqueue_scripts($hook_suffix) {
    if ('post.php' == $hook_suffix) {
        $currentScreen = get_current_screen();

        if (method_exists($currentScreen, 'is_block_editor')) {
            if (!$currentScreen->is_block_editor()) {
                wp_enqueue_style('custom-tinymce-style', SEOAIC_URL . 'tiny-mce/assets/css/seoaic-tinymce.css');
            }
        } else {
            wp_enqueue_style('custom-tinymce-style', SEOAIC_URL . 'tiny-mce/assets/css/seoaic-tinymce.css'); // just a fallback
        }
    }
}
add_action('admin_enqueue_scripts', 'seoaic_tiny_mce_enqueue_scripts');


function seoaic_check_wp_cron_running($event_name = '') {
    $cron = _get_cron_array();

    $event_found = true;

    if (!wp_next_scheduled($event_name)) {
        $event_found = false;
    }

    return $event_found;
}

function seoaicIsUserLoggedIn() {
    global $SEOAIC_OPTIONS;

    return !empty($SEOAIC_OPTIONS['seoaic_api_email'])
        && !empty($SEOAIC_OPTIONS['seoaic_api_token']);
}

add_action('add_meta_boxes', 'seoaic_add_thumbnail_meta_box');

function seoaic_add_thumbnail_meta_box() {
    $screen = get_current_screen();
    $post_type = $screen ? $screen->post_type : null;

    $exclusions = [
        'acf-field-group',
        'smart-custom-fields',
        'acf-taxonomy',
        'acf-ui-options-page',
        'acf-post-type'
    ];

    if ( $post_type &&
         post_type_supports($post_type, 'thumbnail') &&
         !is_gutenberg_active_for_post_type() &&
         !($screen && in_array($screen->id, $exclusions))
    ) {
        add_meta_box(
            'seoaic_thumbnail_block',
            esc_html__('SEOAI Featured Image', 'seoaic'),
            'seoaic_render_thumbnail_meta_box',
            null,
            'side',
            'low'
        );
    }
}

/**
 * Check if Gutenberg is active for the current post type.
 */
function is_gutenberg_active_for_post_type() {
    $post_type = get_current_screen() ? get_current_screen()->post_type : null;

    if (function_exists('use_block_editor_for_post_type')) {
        return use_block_editor_for_post_type($post_type);
    }

    return false;
}

/**
 * Render the custom meta box for the post thumbnail.
 *
 * @param WP_Post $post Current post object.
 */
function seoaic_render_thumbnail_meta_box($post) {
    ?>
    <div id="seoaic-thumbnail-container" class="seoaic-thumbnail-actions">
        <div class="thumbnail-prompt">
            <label for="seoaic-thumbnail-prompt"><?php esc_html_e('Prompt', 'seoaic') ?></label>
            <textarea name="seoaic-thumbnail-prompt" id="seoaic-thumbnail-prompt" rows="4"></textarea>
            <p><?php esc_html_e('Optional field. Use prompt to specify more precise results of image generation.', 'seoaic') ?></p>
        </div>

        <label for="style_value">Style:</label>
        <select name="style_value" id="style_value">
            <?php
            $defaultStyle = SEOAIC_SETTINGS::getImageGenerateStyle();
            $styles = SEOAIC_SETTINGS::getImageGenerateStylesAvailable();

            foreach ($styles as $value => $label) {
                $isSelected = ($value == $defaultStyle) ? 'selected="selected"' : '';
                echo '<option value="' . esc_attr($value) . '" ' . $isSelected . '>' . esc_html($label) . '</option>';
            }
            ?>
        </select>
        <br>
        <label for="width_value">Width:</label>
        <input type="range" id="width_value" name="width" value="<?php echo esc_html( SEOAIC_SETTINGS::getImageGenerateWidthDefault() ); ?>" min="256" max="1440" step="32" />
        <span id="width_value_output"><?php echo esc_html( SEOAIC_SETTINGS::getImageGenerateWidthDefault() ); ?></span>px
        <br>
        <label for="height_value">Height:</label>
        <input type="range" id="height_value" name="height" value="<?php echo esc_html(SEOAIC_SETTINGS::getImageGenerateHeightDefault() ); ?>" min="256" max="1440" step="32" />
        <span id="height_value_output"><?php echo esc_html( SEOAIC_SETTINGS::getImageGenerateHeightDefault() ); ?></span>px
        <p class="hide-if-no-js">
            <a href="#" id="seoaic-generate-thumbnail-button" class="seoaic-gradient-btn components-button"><span><?php esc_html_e('Generate featured image', 'seoaic'); ?></span></a>
        </p>
    </div>
    <?php
}

/**
 * Save the selected thumbnail ID.
 *
 * @param int $post_id The ID of the current post.
 */
add_action('save_post', 'seoaic_save_thumbnail_meta');
function seoaic_save_thumbnail_meta($post_id) {
    if (isset($_POST['seoaic_thumbnail'])) {
        $thumbnail_id = sanitize_text_field($_POST['seoaic_thumbnail']);
        if (!empty($thumbnail_id)) {
            update_post_meta($post_id, '_thumbnail_id', $thumbnail_id);
        } else {
            delete_post_meta($post_id, '_thumbnail_id');
        }
    }
}

function seoaicPageRender($file, $className = '', $attributesString = '')
{
    $contentHTML = '';

    ob_start();
    include_once(SEOAIC_DIR . 'inc/view/seoaic-page-template-view.php');
    $pageHTML = ob_get_clean();

    if (file_exists($file)) {
        ob_start();
        include_once($file);
        $contentHTML = ob_get_clean();
    }

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    echo str_replace(
        ['%SEOAIC_PAGE_CONTENT%', '%SEOAIC_PAGE_CLASS_NAME%', '%SEOAIC_PAGE_ATTRS_STR%'],
        [$contentHTML, esc_attr($className), $attributesString],
        $pageHTML
    );
}

function seoaic_get_branded_keywords() {
    global $SEOAIC_OPTIONS;

    $brandedKeywords = [
        $SEOAIC_OPTIONS['seoaic_business_name']
    ];

    if (!empty($SEOAIC_OPTIONS['seoaic_branded_keywords'])) {
        $additionalKeywords = explode("\n", $SEOAIC_OPTIONS['seoaic_branded_keywords']);
        $brandedKeywords = array_merge($brandedKeywords, $additionalKeywords);
    }

    return $brandedKeywords;
}

function seoaic_is_scf_active() {
    return function_exists('get_field');
}

/**
 * Checks whether width & height fit or not
 *
 * @param int $width
 * @param int $height
 * @return bool
 */
function checkSizeOfImage(int $width, int $height)
{
    return ($width >= ThumbnailsGenerate::MIN_THUMBNAIL_WIDTH
            && $width <= ThumbnailsGenerate::MAX_THUMBNAIL_WIDTH)
        && ($height >= ThumbnailsGenerate::MIN_THUMBNAIL_HEIGHT
            && $height <= ThumbnailsGenerate::MAX_THUMBNAIL_HEIGHT);
}

function getTotalPublishedPostsCount(): int {
    static $total = null;

    if ($total !== null) {
        return $total;
    }

    $total = 0;
    $post_types = get_post_types(['public' => true], 'names');

    foreach ($post_types as $post_type) {
        $counts = wp_count_posts($post_type);
        if (!empty($counts->publish)) {
            $total += (int) $counts->publish;
        }
    }

    return $total;
}

function get_users_can_edit_posts() {
    $args = [
        'role__in' => ['administrator', 'editor', 'author'],
        'orderby' => 'display_name',
        'order' => 'ASC',
    ];

    return get_users($args);
}

function isSEOAIPost($post) {
    if (is_numeric($post)) {
        $postId = intval($post);

    } else if (is_a($post, 'WP_Post')) {
        $postId = $post->ID;

    } else {
        return false;
    }

    $seoaicPosted = get_post_meta($postId, 'seoaic_posted', true);

    return 1 == $seoaicPosted;
}

/**
 * Get plugin slug in <folder>/<file> format.
 * @param bool $trimExtension Trim file extension or not
 */
function seoaiGetPluginSlug($trimExtension = false) {
    $arr = explode('/', SEOAIC_FILE);
    $slugEls = array_slice($arr, -2, 2);

    if ($trimExtension) {
        return rtrim(implode('/', $slugEls), '.php');
    }

    return implode('/', $slugEls);
}

function seoaicGetOtherStatuses() {
    $otherStatuses = [];
    $allStatuses = get_post_stati([], 'objects');
    $allStatuses = array_map(function ($item) { // make needed format
        return $item->label;
    }, $allStatuses);
    $allStatuses = array_filter( // skip some statuses
        $allStatuses,
        function ($item) {
            return !in_array($item, ['trash', 'auto-draft']);
        },
        ARRAY_FILTER_USE_KEY
    );
    $otherStatusesKeys = array_diff(array_keys($allStatuses), SEOAIC_POSTS::ANY_STATUS);

    foreach ($allStatuses as $key => $value) {
        if (in_array($key, $otherStatusesKeys)) {
            $otherStatuses[$key] = $value;
        }
    }

    return $otherStatuses;
}

function seoaic_get_last_month_options($count = 3) {
    $opts = [];
    $now  = current_time('timestamp');

    for ($i = 0; $i < $count; $i++) {
        $ts = strtotime(date('Y-m-01 00:00:00', $now) . " -$i month");
        $value = wp_date('Y-m-d', $ts);
        $label = wp_date('F Y', $ts);
        $opts[$value] = $label;
    }
    return $opts;
}
