<?php

if (!function_exists('themeSetup')) {
    /**
     * Sets up theme defaults and registers support for various WordPress features.
     *
     * Note that this function is hooked into the after_setup_theme hook, which
     * runs before the init hook. The init hook is too late for some features, such
     * as indicating support for post thumbnails.
     */

    function themeSetup()
    {
        /*
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         * If you're building a theme based on test, use a find and replace
         * to change 'test' to the name of your theme in all the template files.
         */
        load_theme_textdomain('ftm_base', get_template_directory() . '/languages');

        // Add default posts and comments RSS feed links to head.
        //add_theme_support('automatic-feed-links');

        /*
         * Let WordPress manage the document title.
         * By adding theme support, we declare that this theme does not use a
         * hard-coded <title> tag in the document head, and expect WordPress to
         * provide it for us.
         */
        add_theme_support('title-tag');

        /*
         * Enable support for Post Thumbnails on posts and pages.
         *
         * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
         */
        add_theme_support('post-thumbnails');

        //NEED TO BE CUSTOMIZED
        /*
            add_image_size('large', 700, '', true); // Large Thumbnail
            add_image_size('medium', 250, '', true); // Medium Thumbnail
            add_image_size('small', 120, '', true); // Small Thumbnail
            add_image_size('custom-size', 700, 200, true); // Custom Thumbnail Size call using the_post_thumbnail('custom-size');
        */

        //MENUS
        register_nav_menus(
            array(
                'main-menu' => __('Main Menu', 'ftm_base'),
                'secondary-menu' => __('Secondary Menu', 'ftm_base')
            )
        );

        //SIDEBARS
        register_sidebar(
            array(
                'name' => 'Right Sidebar',
                'id'   => 'right-sidebar'
            )
        );

        /*
         * Switch default core markup for search form, comment form, and comments
         * to output valid HTML5.
         */
        add_theme_support('html5', array(
            'search-form',
            'comment-form',
            'comment-list',
            'gallery',
            'caption',
        ));

        // Set up the WordPress core custom background feature.
        add_theme_support('custom-background', apply_filters('test_custom_background_args', array(
            'default-color' => 'ffffff',
            'default-image' => '',
        )));

        // Add theme support for selective refresh for widgets.
        add_theme_support('customize-selective-refresh-widgets');

        /**
         * Add support for core custom logo.
         *
         * @link https://codex.wordpress.org/Theme_Logo
         */

        //NEED TO BE CUSTOMIZED
        add_theme_support('custom-logo', array(
            'height' => 250,
            'width' => 250,
            'flex-width' => true,
            'flex-height' => true,
        ));
    } //end of themeSetup function

} //end of if

add_action('after_setup_theme', 'themeSetup');

add_action('wp_enqueue_scripts', 'ftm_base_add_css');
add_action('wp_enqueue_scripts', 'ftm_base_add_js');

function ftm_base_add_css()
{
    wp_enqueue_style('ftm-base-variables', FTM_BASE_CSS_CUSTOMIZER_FILE_URI, array(), "1.0.0");
    wp_enqueue_style('ftm-base-css', webpack('ftm_base.css'), array(), "1.0.0");
    wp_enqueue_style('ftm-rankmath-css', webpack('ftm_rankmath.css'), array(), "1.0.0");
    wp_enqueue_style('ftm-media-logos', webpack('ftm_social.css'), array(), '', 'all');

    if (is_singular('reviews')) {
        wp_enqueue_style('ftm-swiper-css',  get_template_directory_uri() . '/assets/sass/swiper.css', array(), "1.0.0");
    }
    if (is_single()) {
        wp_enqueue_style('author-box', webpack('ftm_author_box.css'), '', '', 'all');
    }

    //Search Feature
    // Check if the customizer variable 'ftm-site-has-search' is set to true
    $site_has_search = get_theme_mod('ftm-site-has-search', false);
    if ($site_has_search) {
        wp_enqueue_style('ftm-swiper-css',  get_template_directory_uri() . '/assets/sass/search.css', array(), "1.0.0");
    }

    //Add media logos if the template being used is the Author Profile template file
    if (is_page_template('templates/author-profile.php')) {
        wp_enqueue_style('dashicons');
    }

    if (is_typesense_active()) {
        wp_enqueue_style('ftm-typesense-custom-css',  get_template_directory_uri() . '/assets/sass/typesense_custom.css', array(), "1.0.0");
    }
}

function ftm_base_add_js()
{

    if (is_singular('reviews')) {
        wp_enqueue_script('ftm-swiper-js', get_template_directory_uri() . '/assets/js/swiper.js', array(), "1.0.0", true);
    }
    wp_enqueue_script('ftm-base-js', webpack('ftm_base.js'), array(), "1.0.0", true);
    wp_localize_script(
        'ftm-base-js',
        'pw_script_vars',
        array(
            'ajaxurl' => admin_url('admin-ajax.php'),
        )
    );
}

function ftm_base_add_js_admin()
{
    wp_enqueue_script('ftm-user-js-admin', webpack('ftm_user.js'), array(), "1.0.0", true);
}
add_action('admin_enqueue_scripts', 'ftm_base_add_js_admin');

//SETUP CUSTOM POSTS TYPES
function create_reviews_post_type()
{
    //FIX SO WE CAN HAVE A PAGE /reviews DISPLAYED
    add_rewrite_rule('^reviews/?$', 'index.php?&pagename=reviews', 'top');
    flush_rewrite_rules();

    // Check if the customizer variable 'ftm-site-has-reviews' is set to true
    $site_has_reviews = get_theme_mod('ftm-site-has-reviews', false);

    if ($site_has_reviews) {
        register_post_type(
            'reviews',
            array(
                'labels' => array(
                    'name' => __('Reviews'),
                    'singular_name' => __('Review'),
                ),
                'public' => true,
                'has_archive' => true,
                'rewrite' => array('slug' => 'reviews'),
                'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'page-attributes', 'revisions', 'author'),
                'menu_icon' => 'dashicons-star-half',
                'show_in_rest' => true
            )
        );

        //Then add the necesary ACF fields group to act on the Reviews custom post type just created
        if (function_exists('acf_add_local_field_group')) :
            acf_add_local_field_group(array(
                'key' => 'group_652429296bf0d',
                'title' => 'FTM Reviews Fields',
                'fields' => array(
                    array(
                        'key' => 'field_652433d02d465',
                        'label' => 'Site Name',
                        'name' => 'site_name',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_6524299956e7d',
                        'label' => 'Site Logo',
                        'name' => 'site_logo_url',
                        'type' => 'image',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'return_format' => 'url',
                        'library' => 'all',
                        'min_width' => '',
                        'min_height' => '',
                        'min_size' => '',
                        'max_width' => '',
                        'max_height' => '',
                        'max_size' => '',
                        'mime_types' => '',
                        'preview_size' => 'thumbnail',
                    ),
                    array(
                        'key' => 'field_6579743f9f40f',
                        'label' => 'Site Affiliate Link',
                        'name' => 'site_affiliate_link',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65242a0e56e7e',
                        'label' => 'Site Welcome Bonus',
                        'name' => 'site_welcome_bonus',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_65242e1156e7f',
                        'label' => 'Site Bonus Code',
                        'name' => 'site_bonus_code',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_6524302256e80',
                        'label' => 'Site Rating',
                        'name' => 'site_rating',
                        'type' => 'number',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '3.5',
                        'min' => 0,
                        'max' => 5,
                        'placeholder' => '',
                        'step' => '',
                        'prepend' => '',
                        'append' => '',
                    ),
                    array(
                        'key' => 'field_6524292956e7c',
                        'label' => 'Review Top Content',
                        'name' => 'review_top_content',
                        'type' => 'wysiwyg',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'delay' => 0,
                        'tabs' => 'all',
                        'toolbar' => 'full',
                        'media_upload' => 1,
                    ),
                    array(
                        'key' => 'field_6524341ddd93f',
                        'label' => 'Site Key Features',
                        'name' => 'site_key_features',
                        'type' => 'repeater',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'layout' => 'row',
                        'pagination' => 0,
                        'min' => 0,
                        'max' => 0,
                        'collapsed' => '',
                        'button_label' => 'Add Row',
                        'rows_per_page' => 20,
                        'sub_fields' => array(
                            array(
                                'key' => 'field_65243436dd940',
                                'label' => 'Key Feature Name',
                                'name' => 'key_feature_name',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_6524341ddd93f',
                            ),
                            array(
                                'key' => 'field_65243451dd941',
                                'label' => 'Key Feature Value',
                                'name' => 'key_feature_value',
                                'type' => 'text',
                                'instructions' => '',
                                'required' => 0,
                                'conditional_logic' => 0,
                                'wrapper' => array(
                                    'width' => '',
                                    'class' => '',
                                    'id' => '',
                                ),
                                'default_value' => '',
                                'maxlength' => '',
                                'placeholder' => '',
                                'prepend' => '',
                                'append' => '',
                                'parent_repeater' => 'field_6524341ddd93f',
                            ),
                        ),
                    ),
                    array(
                        'key' => 'field_652cf5ff18713',
                        'label' => 'Site Gallery',
                        'name' => 'site_gallery',
                        'type' => 'gallery',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'return_format' => 'array',
                        'library' => 'all',
                        'min' => '',
                        'max' => '',
                        'min_width' => '',
                        'min_height' => '',
                        'min_size' => '',
                        'max_width' => '',
                        'max_height' => '',
                        'max_size' => '',
                        'mime_types' => '',
                        'insert' => 'append',
                        'preview_size' => 'medium',
                    ),
                    array(
                        'key' => 'field_6566613b6af93',
                        'label' => 'Site Category',
                        'name' => 'site_category',
                        'type' => 'checkbox',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'sports' => 'Sports',
                            'casino' => 'Casino',
                            'poker' => 'Poker',
                        ),
                        'default_value' => array(
                            0 => 'sports',
                        ),
                        'return_format' => 'value',
                        'allow_custom' => 0,
                        'save_custom' => 0,
                        'layout' => 'vertical',
                        'toggle' => 0,
                    ),
                ),
                'location' => array(
                    array(
                        array(
                            'param' => 'post_type',
                            'operator' => '==',
                            'value' => 'reviews',
                        ),
                    ),
                ),
                'menu_order' => 0,
                'position' => 'acf_after_title',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
                'show_in_rest' => 0,
            ));

        endif;

        //If Reviews are enabled then we need to add the reviews hub block
        // check function exists
        if (function_exists('acf_register_block')) {

            // register a the reviews-hub block
            acf_register_block_type(array(
                'name'              => 'reviews-hub',
                'title'             => __('Reviews Hub'),
                'description'       => __('The Reviews hub block.'),
                'render_callback'   => 'render_reviews_hub',
                //'render_template'   => get_theme_file_path() . '/blocks/reviews-hub/reviews-hub-render.php',
                'category'          => 'theme',
                'icon'              => 'superhero-alt',
                'keywords'          => array('reviews', 'grid'),
                'enqueue_assets'    => 'enqueue_review_hub_script',
            ));

            //register ACF fields for the block
            if (function_exists('acf_add_local_field_group')) :

                acf_add_local_field_group(array(
                    'key' => 'group_65602cec82d7b',
                    'title' => 'FTM Reviews Hub Block Fields',
                    'fields' => array(
                        array(
                            'key' => 'field_65697cff045ce',
                            'label' => 'Block Title',
                            'name' => 'block_title',
                            'type' => 'text',
                            'instructions' => '',
                            'required' => 0,
                            'conditional_logic' => 0,
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'default_value' => '',
                            'maxlength' => '',
                            'placeholder' => '',
                            'prepend' => '',
                            'append' => '',
                        ),
                        array(
                            'key' => 'field_65602cec6ba83',
                            'label' => 'Display Search',
                            'name' => 'display_search',
                            'type' => 'true_false',
                            'instructions' => '',
                            'required' => 0,
                            'conditional_logic' => 0,
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'message' => '',
                            'default_value' => 1,
                            'ui_on_text' => '',
                            'ui_off_text' => '',
                            'ui' => 0,
                        ),
                        array(
                            'key' => 'field_65683d5fabe8f',
                            'label' => 'Reviews Per Page',
                            'name' => 'reviews_per_page',
                            'type' => 'number',
                            'instructions' => '',
                            'required' => 0,
                            'conditional_logic' => 0,
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'default_value' => 4,
                            'min' => 2,
                            'max' => '',
                            'placeholder' => '',
                            'step' => '',
                            'prepend' => '',
                            'append' => '',
                        ),
                        array(
                            'key' => 'field_65682743da5cf',
                            'label' => 'Reviews Category',
                            'name' => 'reviews_category',
                            'type' => 'checkbox',
                            'instructions' => '',
                            'required' => 0,
                            'conditional_logic' => array(
                                array(
                                    array(
                                        'field' => 'field_6568317d5d0a1',
                                        'operator' => '!=',
                                        'value' => '1',
                                    ),
                                ),
                            ),
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'choices' => array(
                                'all' => 'All',
                                'sports' => 'Sports',
                                'casino' => 'Casino',
                                'poker' => 'Poker',
                            ),
                            'default_value' => array(
                                0 => 'all',
                            ),
                            'return_format' => 'value',
                            'allow_custom' => 0,
                            'layout' => 'vertical',
                            'toggle' => 0,
                            'save_custom' => 0,
                        ),
                        array(
                            'key' => 'field_6568317d5d0a1',
                            'label' => 'Specific Reviews',
                            'name' => 'specific_reviews',
                            'type' => 'true_false',
                            'instructions' => '',
                            'required' => 0,
                            'conditional_logic' => 0,
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'message' => 'If this is checked, the reviews categories setting is overridden.',
                            'default_value' => 0,
                            'ui_on_text' => '',
                            'ui_off_text' => '',
                            'ui' => 0,
                        ),
                        array(
                            'key' => 'field_656837355d0a2',
                            'label' => 'Select Reviews',
                            'name' => 'select_reviews',
                            'type' => 'post_object',
                            'instructions' => '',
                            'required' => 0,
                            'conditional_logic' => array(
                                array(
                                    array(
                                        'field' => 'field_6568317d5d0a1',
                                        'operator' => '==',
                                        'value' => '1',
                                    ),
                                ),
                            ),
                            'wrapper' => array(
                                'width' => '',
                                'class' => '',
                                'id' => '',
                            ),
                            'post_type' => array(
                                0 => 'reviews',
                            ),
                            'taxonomy' => '',
                            'return_format' => 'id',
                            'multiple' => 1,
                            'allow_null' => 0,
                            'ui' => 1,
                        ),
                    ),
                    'location' => array(
                        array(
                            array(
                                'param' => 'block',
                                'operator' => '==',
                                'value' => 'acf/reviews-hub',
                            ),
                        ),
                    ),
                    'menu_order' => 0,
                    'position' => 'normal',
                    'style' => 'default',
                    'label_placement' => 'top',
                    'instruction_placement' => 'label',
                    'hide_on_screen' => '',
                    'active' => true,
                    'description' => '',
                    'show_in_rest' => 1,
                ));

            endif;
        }

        //Add the ajax handlers 
        add_action('wp_ajax_get_reviews', 'get_reviews_list');
        add_action('wp_ajax_nopriv_get_reviews', 'get_reviews_list');

        //Enqueue the css and js scripts
        //add_action('wp_enqueue_scripts', 'enqueue_review_hub_script');
    }
}
add_action('init', 'create_reviews_post_type');

/*
 * BEGIN: CUSTOM POST TYPE BLOG
 */

//SETUP CUSTOM POSTS TYPES
function create_blog_post_type()
{
    //FIX SO WE CAN HAVE A PAGE /blog DISPLAYED
    add_rewrite_rule('^blog/?$', 'index.php?&pagename=blog', 'top');
    flush_rewrite_rules();

    register_post_type(
        'blog',
        array(
            'labels' => array(
                'name' => __('Blog'),
                'singular_name' => __('Blog'),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'blog'),
            'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'page-attributes', 'revisions', 'author', 'excerpt'),
            'show_in_rest' => true
        )
    );
}
add_action('init', 'create_blog_post_type');

function add_custom_types_to_archive($query)
{
    if ((is_category() || is_tag()) && $query->is_archive() && empty($query->query_vars['suppress_filters'])) {
        $query->set('post_type', array(
            'post',
            'blog'
        ));
    }
}
add_action('pre_get_posts', 'add_custom_types_to_archive');

add_filter('rank_math/frontend/breadcrumb/items', function ($crumbs, $class) {
    $current_url = home_url($_SERVER['REQUEST_URI']);

    $firstPart      = array_slice($crumbs, 0, 1);
    $secondPart     = array_slice($crumbs, 1);

    for ($i = 0; $i < count($secondPart); $i++) {
        for ($j = 0; $j < count($secondPart[$i]); $j++) {
            if (!empty($secondPart[$i][$j])) {
                $secondPart[$i][$j] = preg_replace('/\/category\//', '/blog/', $secondPart[$i][$j]);
            }
        }
    }

    if (preg_match('/\/blog\//', $current_url) && is_category()) {
        $blogElement[]  = ["Blog", home_url() . "/blog/", "hide_in_schema" => false];
        $crumbs = array_merge($firstPart, $blogElement, $secondPart);
    } elseif (is_single()) {
        $crumbs = array_merge($firstPart, $secondPart);
    }

    return $crumbs;
}, 10, 2);

function add_categories_to_blog_post_type()
{
    register_taxonomy_for_object_type('category', 'blog');
}
add_action('init', 'add_categories_to_blog_post_type');

/*
 * END: CUSTOM POST TYPE BLOG
 */


/*
 * BEGIN: FIX CATEGORIES URL FOR BLOG CTP
 * 
 */

add_filter('rewrite_rules_array', 'fix_rules_for_types');
function fix_rules_for_types($rules)
{
    $terms = get_terms(['taxonomy' => 'category', 'hide_empty' => false]);
    foreach ($terms as $term) {
        $rule = '^blog/' . $term->slug . '/{0,1}$';
        $rewrite = 'index.php?category_name=' . $term->slug;
        $rules = array_merge([$rule => $rewrite], $rules);
    }

    return $rules;
}

add_action('create_category', 'clear_rewrite_rules', 10, 2);
function clear_rewrite_rules($term_id, $taxonomy_term_id)
{
    $term = get_term($term_id);
    if ($term->taxonomy == 'category') {
        $rule = '^blog/' . $term->slug . '/{0,1}$';
        $rewrite = 'index.php?category_name=' . $term->slug;
        add_rewrite_rule($rule, $rewrite, 'top');
    }
    flush_rewrite_rules();
}

/*
 * END: FIX CATEGORIES URL FOR BLOG CTP
 */

/**
 * Reviews CSS and JS Files Load
 */
function enqueue_review_hub_script()
{
    wp_enqueue_script('review-hub-script', webpack('ftm_reviews_hub.js'), array(), "1.0.0");
    //wp_enqueue_script('review-hub-script', get_stylesheet_directory_uri() . '/blocks/reviews-hub/reviews-hub.js', array(), "1.0.0");
    wp_enqueue_style('ftm_reviews_hub-css', webpack('ftm_reviews_hub.css'), array(), "1.0.0");

    // Pass the nonce to the script
    wp_localize_script('review-hub-script', 'review_hub_vars', array(
        'nonce' => wp_create_nonce('review_hub_nonce'),
        'url'   => admin_url('admin-ajax.php'),
    ));
}

/**
 * Reviews Hub Render Function
 */
function render_reviews_hub($block)
{
    $slug = str_replace('acf/', '', $block['name']);

    if (file_exists(get_theme_file_path("/blocks/{$slug}/reviews-hub-render.php"))) {
        include(get_theme_file_path("/blocks/{$slug}/reviews-hub-render.php"));
    }
}

/**
 * Pulls the reviews list
 */
function get_reviews_list()
{
    check_ajax_referer('review_hub_nonce', 'nonce');

    $hub_id = isset($_POST['hub_id']) ? $_POST['hub_id'] : '';
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $posts_per_page = isset($_POST['posts_per_page']) ? intval($_POST['posts_per_page']) : -1;
    $review_types = isset($_POST['review_types']) ? $_POST['review_types'] : '';
    $search_name = isset($_POST['search_name']) ? sanitize_text_field($_POST['search_name']) : '';
    $specifc_reviews = isset($_POST['specifc_reviews']) ? $_POST['specifc_reviews'] : '-1';

    $args = array(
        'post_type'      => 'reviews',
        'posts_per_page' => $posts_per_page,
        'paged'          => $page,
        'post_status'    => 'publish',
        'meta_key'       => 'site_name',
        'orderby'        => 'meta_value',
        'order'          => 'ASC',
    );

    //See if a search was performed
    if ($search_name != '') {
        $args['meta_query'] = array(
            array(
                'key'     => 'site_name',
                'value'   => $search_name,
                'compare' => 'LIKE',
            )
        );
    }

    if ($specifc_reviews == '-1') {
        if ($review_types != '') {
            $reviews_categories = explode(',', $review_types);
        } else {
            $reviews_categories = ['all'];
        }


        if (!in_array("all", $reviews_categories)) {
            $args['meta_query']['relation'] = 'AND';

            foreach ($reviews_categories as $review_category) {
                $args['meta_query'][] = array(
                    'key'     => 'site_category',
                    'value'   => $review_category,
                    'compare' => 'LIKE',
                );
            }
        }
    } else //Specific POST IDs are provided and this condition overrides the categories filter
    {
        // Convert the string into an array
        $post_ids_array = explode(',', $specifc_reviews);
        $args['post__in'] = $post_ids_array;
    }

    $reviews = new WP_Query($args);

    $response = array();

    if ($reviews->have_posts()) {
        while ($reviews->have_posts()) {
            $reviews->the_post();
            // Get the review content
            $bookie_post_ID       = get_the_ID();
            $book_name            =  get_field('site_name', $bookie_post_ID);
            $book_logo_url        =  get_field('site_logo_url', $bookie_post_ID);
            $book_welcome_bonus   =  get_field('site_welcome_bonus', $bookie_post_ID);
            $book_bonus_code      =  get_field('site_bonus_code', $bookie_post_ID);
            $book_rating          =  get_field('site_rating', $bookie_post_ID);
            $book_key_features    =  get_field('site_key_features', $bookie_post_ID);
            $book_categories      =  get_field('site_category', $bookie_post_ID);

            $book_rating_html = '';
            $book_rating_html .= '<div class="site-rating">';
            $book_rating_html .= '<div class="just-stars">';

            $rating_percentage = 0;
            if (!empty($book_rating)) {
                $rating_floor =  floor($book_rating);
                $rating_percentage = $rating_floor * 20;

                if ($rating_floor < $book_rating) { //Decimal calculation
                    $decimnal_value = $book_rating - $rating_floor;
                    // Define the value that represents 100% on your scale
                    $valueFor100Percent = 20;

                    // Map a value from 0-1 scale to a percentage
                    $decimal_percentage = $decimnal_value * 100;

                    // Calculate the value on the original scale
                    $scaleValueOnOriginalScale = ($decimal_percentage / 100) * $valueFor100Percent;
                    $rating_percentage += $scaleValueOnOriginalScale;
                }
            }
            $book_rating_html .= '<div class="star-rating__overlay" style="width:' . $rating_percentage . '%"></div>';
            $book_rating_html .= '<div class="star-rating__underlay"></div>';
            $book_rating_html .= '</div>';
            $book_rating_html .= '</div>';

            $book_data = [
                'bookie_post_ID'     => $bookie_post_ID,
                'book_review_title'  => get_the_title(),
                'book_logo_url'      => $book_logo_url,
                'book_welcome_bonus' => $book_welcome_bonus,
                'book_bonus_code'    => $book_bonus_code,
                'book_rating'        => $book_rating,
                'book_rating_html'   => $book_rating_html,
                'book_key_features'  => $book_key_features,
                'book_categories'    => $book_categories,
                'book_review_url'    => get_permalink($bookie_post_ID)
            ];

            $response[$book_name] = $book_data;
        }

        wp_reset_postdata();
    }

    // Get pagination links
    if (isset($reviews->max_num_pages)) {
        $pagination_links = paginate_links(array(
            'total'   => $reviews->max_num_pages,
            'current' => $page,
            'type'    => 'array',
            'base'    => '#page_%#%',
            'prev_text'  => __('<', 'FTM Theme'),
            'next_text'  => __('>', 'FTM Theme'),
        ));

        $pagination_links = apply_filters('ftm_reviews_custom_pagination_links', $hub_id, $pagination_links, $page);

        // Transform the array of links into plain text
        if (is_array($pagination_links)) {
            $pagination_text = implode(' ', $pagination_links);
        } else {
            $pagination_text = str_replace(',', '', $pagination_links);
        }
    } else {
        $pagination_text = '';
    }

    echo json_encode(array('reviews' => $response, 'pagination_links' => $pagination_text, 'no_results_text' => __('-- No Results found for this search --', 'FTM Theme')));
    die();
}

//ADD FILTER FOR THE REVIEWS HUB PAGINATION
function ftm_reviews_custom_pagination_links($hub_id, $links, $page)
{
    // Add custom data attributes to each pagination link
    if (is_array($links)) {
        foreach ($links as &$link) {
            if (strpos($link, 'class="next') !== false) {
                $link = str_replace('<a ', '<a data-page-number="' . ($page + 1) . '" data-hub-id="' . $hub_id . '" ', $link);
            } elseif (strpos($link, 'class="prev') !== false) {
                $link = str_replace('<a ', '<a data-page-number="' . ($page - 1) . '" data-hub-id="' . $hub_id . '" ', $link);
            } else {
                $link = str_replace('<a ', '<a data-page-number="' . strip_tags($link) . '" data-hub-id="' . $hub_id . '" ', $link);
            }
        }
    }

    return $links;
}
add_filter('ftm_reviews_custom_pagination_links', 'ftm_reviews_custom_pagination_links', 10, 3);


//SETUP CUSTOM FIELDS AND GROUPS
//Add Default ACF groups and fields necessary for the theme from the get-go
if (function_exists('acf_add_local_field_group')) :

    acf_add_local_field_group(array(
        'key' => 'group_650121c094d8b',
        'title' => 'FTM Base Blog Posts',
        'fields' => array(
            array(
                'key' => 'field_650121c246476',
                'label' => 'Most Popular',
                'name' => 'most_popular',
                'type' => 'true_false',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'message' => 'If selected, this post might show up on the top 3 most popular posts on the blog hub template',
                'default_value' => 0,
                'ui_on_text' => '',
                'ui_off_text' => '',
                'ui' => 0,
            ),
        ),
        'location' => array(
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'post',
                ),
            ),
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'blog',
                ),
            ),
        ),
        'menu_order' => 0,
        'position' => 'normal',
        'style' => 'default',
        'label_placement' => 'top',
        'instruction_placement' => 'label',
        'hide_on_screen' => '',
        'active' => true,
        'description' => '',
        'show_in_rest' => 0,
    ));

    acf_add_local_field_group(array(
        'key' => 'group_6511de1e3c7a8',
        'title' => 'FTM Blog Hub Settings',
        'fields' => array(
            array(
                'key' => 'field_659dae10774fa',
                'label' => 'Show Most Popular Section',
                'name' => 'show_most_popular_section',
                'aria-label' => '',
                'type' => 'true_false',
                'instructions' => 'Check the box if you would like the most popular section to show up',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'message' => '',
                'default_value' => 1,
                'ui' => 0,
                'ui_on_text' => '',
                'ui_off_text' => '',
            ),
            array(
                'key' => 'field_6511de1e18e2a',
                'label' => 'Most Popular Title',
                'name' => 'most_popular_title',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => 'Most popular',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_6511de5818e2b',
                'label' => 'Latest Blogs Title',
                'name' => 'latest_blogs_title',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => 'Latest',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
        ),
        'location' => array(
            array(
                array(
                    'param' => 'page_template',
                    'operator' => '==',
                    'value' => 'templates/blog-home.php',
                ),
                array(
                    'param' => 'post_template',
                    'operator' => '==',
                    'value' => 'templates/blog-home.php',
                ),
            ),
        ),
        'menu_order' => 0,
        'position' => 'normal',
        'style' => 'default',
        'label_placement' => 'top',
        'instruction_placement' => 'label',
        'hide_on_screen' => '',
        'active' => true,
        'description' => '',
        'show_in_rest' => 0,
    ));

    acf_add_local_field_group(array(
        'key' => 'group_6580c22ecf523',
        'title' => 'FTM Custom Author Page',
        'fields' => array(
            array(
                'key' => 'field_6580c22f33e53',
                'label' => 'Author Name',
                'name' => 'author_name',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_6580c58f33e59',
                'label' => 'Wordpress User Account',
                'name' => 'wordpress_user_account',
                'type' => 'user',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'role' => '',
                'return_format' => 'id',
                'multiple' => 0,
                'allow_null' => 0,
            ),
            array(
                'key' => 'field_6580c25533e54',
                'label' => 'Author Role',
                'name' => 'author_role',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_658336399264b',
                'label' => 'Display Author Joined Date',
                'name' => 'display_author_joined_date',
                'type' => 'true_false',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'message' => '',
                'default_value' => 1,
                'ui_on_text' => '',
                'ui_off_text' => '',
                'ui' => 0,
            ),
            array(
                'key' => 'field_6580c25e33e55',
                'label' => 'Author Joined',
                'name' => 'author_joined',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'field_658336399264b',
                            'operator' => '==',
                            'value' => '1',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_658336709264c',
                'label' => 'Display Author Contact Link',
                'name' => 'display_author_contact_link',
                'type' => 'true_false',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'message' => '',
                'default_value' => 1,
                'ui_on_text' => '',
                'ui_off_text' => '',
                'ui' => 0,
            ),
            array(
                'key' => 'field_658103d817fe0',
                'label' => 'Author Contact Link',
                'name' => 'author_contact_link',
                'type' => 'text',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'field_658336709264c',
                            'operator' => '==',
                            'value' => '1',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => '',
                'maxlength' => '',
                'placeholder' => '',
                'prepend' => '',
                'append' => '',
            ),
            array(
                'key' => 'field_6580c2f233e56',
                'label' => 'Author Favorites',
                'name' => 'author_favorites',
                'type' => 'repeater',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'layout' => 'table',
                'pagination' => 0,
                'min' => 0,
                'max' => 0,
                'collapsed' => '',
                'button_label' => 'Add Row',
                'rows_per_page' => 20,
                'sub_fields' => array(
                    array(
                        'key' => 'field_6580c30533e57',
                        'label' => 'Favorite Item Name',
                        'name' => 'favorite_item_name',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                        'parent_repeater' => 'field_6580c2f233e56',
                    ),
                    array(
                        'key' => 'field_6580c55f33e58',
                        'label' => 'Favorite Item Value',
                        'name' => 'favorite_item_value',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                        'parent_repeater' => 'field_6580c2f233e56',
                    ),
                ),
            ),
            array(
                'key' => 'field_6580e55f0b33a',
                'label' => 'Author Socials',
                'name' => 'author_socials',
                'type' => 'repeater',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'layout' => 'table',
                'pagination' => 0,
                'min' => 0,
                'max' => 0,
                'collapsed' => '',
                'button_label' => 'Add Row',
                'rows_per_page' => 20,
                'sub_fields' => array(
                    array(
                        'key' => 'field_6580e5720b33b',
                        'label' => 'Social Media Site',
                        'name' => 'social_media_site',
                        'type' => 'select',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'choices' => array(
                            'facebook' => 'Facebook',
                            'instagram' => 'Instagram',
                            'linkedin' => 'LinkedIn',
                            'x' => 'X',
                        ),
                        'default_value' => false,
                        'return_format' => 'value',
                        'multiple' => 0,
                        'allow_null' => 0,
                        'ui' => 0,
                        'ajax' => 0,
                        'placeholder' => '',
                        'parent_repeater' => 'field_6580e55f0b33a',
                    ),
                    array(
                        'key' => 'field_6580e66b0b33c',
                        'label' => 'Social Media URL',
                        'name' => 'social_media_url',
                        'type' => 'text',
                        'instructions' => '',
                        'required' => 0,
                        'conditional_logic' => 0,
                        'wrapper' => array(
                            'width' => '',
                            'class' => '',
                            'id' => '',
                        ),
                        'default_value' => '',
                        'maxlength' => '',
                        'placeholder' => '',
                        'prepend' => '',
                        'append' => '',
                        'parent_repeater' => 'field_6580e55f0b33a',
                    ),
                ),
            ),
        ),
        'location' => array(
            array(
                array(
                    'param' => 'page_template',
                    'operator' => '==',
                    'value' => 'templates/author-profile.php',
                ),
            ),
        ),
        'menu_order' => 0,
        'position' => 'acf_after_title',
        'style' => 'default',
        'label_placement' => 'top',
        'instruction_placement' => 'label',
        'hide_on_screen' => '',
        'active' => true,
        'description' => '',
        'show_in_rest' => 0,
    ));

    acf_add_local_field_group(array(
        'key' => 'group_6596c22458db8',
        'title' => 'FTM Pages and Blog Post Settings',
        'fields' => array(
            array(
                'key' => 'field_6595ee0ddae',
                'label' => 'Disable Top Post Info',
                'name' => 'disable_top_post_info',
                'type' => 'true_false',
                'instructions' => 'This block of information can be displayed on the content using the shortcode [ftm_display_post_info]',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'message' => 'This setting will hide the legend at the top: By AUTHOR | date -> Social Share Buttons',
                'default_value' => 0,
                'ui' => 0,
                'ui_on_text' => '',
                'ui_off_text' => '',
            ),
        ),
        'location' => array(
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'post',
                ),
            ),
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'page',
                ),
            ),
            array(
                array(
                    'param' => 'post_type',
                    'operator' => '==',
                    'value' => 'blog',
                ),
            ),
        ),
        'menu_order' => 0,
        'position' => 'normal',
        'style' => 'default',
        'label_placement' => 'top',
        'instruction_placement' => 'label',
        'hide_on_screen' => '',
        'active' => true,
        'description' => '',
        'show_in_rest' => 0,
    ));

endif;


/**
 * REGISTER THEME SUPPORT FOR RANK MATH BREADCRUMBS
 */
add_theme_support('rank-math-breadcrumbs');

/*
 * --------------------------------------------------------------------------------------- 
 * START: ALLOW USERS TO USE A DIFFERENT PROFILE PIC RATHER THAN GRAVATAR'S ONE
 * ---------------------------------------------------------------------------------------
 */
function ftm_base_user_profile_fields($user)
{
    $image = get_user_meta($user->ID, 'ftm_custom_profile_picture', true);
?>
    <h3>Custom Profile Picture</h3>
    <table class="form-table">
        <tr>
            <th><label for="ftm_custom_profile_picture_url">Profile Picture</label></th>
            <td>
                <input type="hidden" name="ftm_custom_profile_picture_url" id="ftm_custom_profile_picture_url" value="<?php echo $image; ?>">
                <img id="ftm_custom_profile_picture_preview" style="max-width:100px; max-height:100px;" />
                <button type="button" id="ftm_custom_profile_picture_button">Upload Image</button>
                <?php
                if ($image) {
                    echo '<img src="' . $image . '" style="width:50px;height:50px;" />';
                }
                ?>
            </td>
        </tr>
    </table>
<?php
}

add_action('show_user_profile', 'ftm_base_user_profile_fields');
add_action('edit_user_profile', 'ftm_base_user_profile_fields');

function ftm_save_custom_user_profile_fields($user_id)
{
    if (!current_user_can('edit_user', $user_id)) {
        return false;
    }
    update_user_meta($user_id, 'ftm_custom_profile_picture', $_POST['ftm_custom_profile_picture_url']);
}
add_action('personal_options_update', 'ftm_save_custom_user_profile_fields');
add_action('edit_user_profile_update', 'ftm_save_custom_user_profile_fields');

/*
 * ---------------------------------------------------------------------------------------
 * END: ALLOW USERS TO USE A DIFFERENT PROFILE PIC RATHER THAN GRAVATAR'S ONE
 * ---------------------------------------------------------------------------------------
 */


/*
 * ---------------------------------------------------------------------------------------
 * BEGIN: FTM SOCIAL SHARE
 * ---------------------------------------------------------------------------------------
 */

if (function_exists('acf_add_local_field_group')) :

    acf_add_local_field_group(array(
        'key' => 'group_63bdf2002ef84',
        'title' => 'FTM Media Share Buttons',
        'fields' => array(
            array(
                'key' => 'field_63bdf20070e65',
                'label' => 'Enable Site Wide',
                'name' => 'ftm_social_share_buttons_enable_site_wide',
                'type' => 'true_false',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'message' => 'By disabling this, you disable the media buttons site wide.',
                'default_value' => 1,
                'ui' => 0,
                'ui_on_text' => '',
                'ui_off_text' => '',
            ),
            array(
                'key' => 'field_63bdf28470e66',
                'label' => 'Social Media Platforms',
                'name' => 'social_media_platforms',
                'type' => 'checkbox',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    'facebook' => 'Facebook',
                    'twitter' => 'Twitter',
                    'linkedin' => 'Linkedin',
                    'reddit' => 'Reddit',
                    'pinterest' => 'Pinterest',
                    'email' => 'Email',
                ),
                'default_value' => array(
                    0 => 'facebook',
                    1 => 'twitter',
                    2 => 'linkedin',
                    3 => 'reddit',
                    4 => 'pinterest',
                    5 => 'email',
                ),
                'return_format' => 'value',
                'allow_custom' => 0,
                'layout' => 'vertical',
                'toggle' => 0,
                'save_custom' => 0,
            ),
            array(
                'key' => 'field_63c09abb01be1',
                'label' => 'Share Buttons Position',
                'name' => 'ftm_media_share_buttons_position',
                'type' => 'select',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    'above' => 'Above content',
                    'below' => 'Below content',
                    'aftertitle' => 'After Title (Single)',
                ),
                'default_value' => 'aftertitle',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
            ),
            array(
                'key' => 'field_63cab3c79d31a',
                'label' => 'There is also a Shortcode',
                'name' => '',
                'type' => 'message',
                'instructions' => '',
                'required' => 0,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'message' => 'In order to render the social share buttons somewhere else, you can use the following shortcode:
    
    [ftm_social_media_share_buttons]
    
    If you want to center the buttons use the parameter \'align=center\' so the shotcode looks like this:
    
    [ftm_social_media_share_buttons align=center]',
                'new_lines' => 'wpautop',
                'esc_html' => 0,
            ),
        ),
        'location' => array(
            array(
                array(
                    'param' => 'options_page',
                    'operator' => '==',
                    'value' => 'ftm-theme-general-settings',
                ),
            ),
        ),
        'menu_order' => 0,
        'position' => 'normal',
        'style' => 'default',
        'label_placement' => 'top',
        'instruction_placement' => 'label',
        'hide_on_screen' => '',
        'active' => true,
        'description' => '',
        'show_in_rest' => 0,
    ));

endif;


if (function_exists('acf_add_options_page')) {

    acf_add_options_page(array(
        'page_title'    => 'Theme Social Settings',
        'menu_title'    => 'FTM Social Share Settings',
        'menu_slug'     => 'ftm-theme-general-settings',
        'capability'    => 'edit_posts',
        'redirect'      => false,
        'icon_url'      => 'dashicons-share'
    ));
}

function get_ftm_social_share_buttons_output($atts = "left")
{
    global $post;

    extract(shortcode_atts(array(
        'align' => 'left',
    ), $atts));

    $buttons_class = "ftm-social-media-share-buttons";

    if ($align == "center") {
        $buttons_class .= " center";
    }


    if (!is_null(get_field('social_media_platforms', 'option'))) {
        $social_media_platforms = get_field('social_media_platforms', 'option');
        $buttons_html_list      = "";
        $html_output            = "";
        $page_link              = htmlspecialchars(get_permalink($post));
        $page_title             = get_the_title($post);

        foreach ($social_media_platforms as $platform) {
            switch ($platform) {
                case "facebook":
                    $buttons_html_list .= '<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=' . $page_link . '" class="fb-xfbml-parse-ignore"><i class="icon-facebook-circled"></i></a>';
                    break;
                case "twitter":
                    $buttons_html_list .= '<a target="_blank" href="https://twitter.com/intent/tweet?text=' . $page_title . '&url=' . $page_link . '"><i class="icon-twitter-logo-x"></i></a>';
                    break;
                case "linkedin":
                    $buttons_html_list .= '<a target="_blank" href="http://www.linkedin.com/shareArticle?url=' . $page_link . '"><i class="icon-linkedin-squared"></i></a>';
                    break;
                case "reddit":
                    $buttons_html_list .= '<a target="_blank" href="https://reddit.com/submit?title=' . $page_title . '&url=' . $page_link . '"><i class="icon-reddit"></i></a>';
                    break;
                case "pinterest":
                    $buttons_html_list .= '<a target="_blank" href="https://pinterest.com/pin/create/pin/?url=' . $page_link . '"><i class="icon-pinterest-circled"></i></a>';
                    break;
                case "email":
                    $buttons_html_list .= '<a href="mailto:?subject=\'' . $page_title . '\'&body=\'' . $page_link . '"><i class="icon-mail"></i></a>';
                    break;
            }
        }

        if (strlen($buttons_html_list) > 0) {
            $buttons_html_list = '<label class="ftm-social-media-share-buttons-legend">Share On Your Network: </label>' . $buttons_html_list;
        }
        $html_output = '<div class="' . $buttons_class . '">' . $buttons_html_list . '</div>';

        return $html_output;
    }
}

function display_ftm_social_share_buttons_on_hook()
{

    if (!is_null(get_field('ftm_social_share_buttons_enable_site_wide', 'option'))) {
        $global_display_share_buttons = false;
        $enable_site_wide = get_field('ftm_social_share_buttons_enable_site_wide', 'option');

        if ($enable_site_wide  == "yes") {
            $ftm_media_share_buttons_dv =  acf_get_field('social_media_platforms')['default_value'];
            $ftm_media_share_buttons    =  get_field('social_media_platforms');

            if (!is_null($ftm_media_share_buttons)) {
                if ($ftm_media_share_buttons == true) {
                    $global_display_share_buttons = true;
                }
            } else {
                if (!empty($ftm_media_share_buttons_dv)) {
                    $global_display_share_buttons = true;
                }
            }
        }

        if ($global_display_share_buttons == true) {
            echo get_ftm_social_share_buttons_output();
        }
    }
}


function ftm_social_share_buttons_handle()
{

    global $post;

    if (is_front_page() || is_home()) {
        return;
    }

    $theme = wp_get_theme();
    // Set theme object to parent theme, if the current theme is a child theme
    $theme_obj  = $theme->parent();
    $parent_theme_name = ($theme_obj == false) ? $theme->get('Name') : $theme_obj->get('Name');

    $share_buttons_position = get_field('ftm_media_share_buttons_position', 'option');

    if (is_null($share_buttons_position)) {
        $share_buttons_position = "above";
    }

    if ($parent_theme_name == "Astra" && $share_buttons_position == "above") {
        if (get_post_type() === 'post') {
            add_filter("astra_blog_single_featured_image_before",  "display_ftm_social_share_buttons_on_hook");
        }
    }

    if ($parent_theme_name == "Astra" && $share_buttons_position == "below") {
        if (get_post_type() === 'post') {
            add_filter("astra_entry_bottom",  "display_ftm_social_share_buttons_on_hook");
        }
    }

    if ($parent_theme_name == "generatepress" && $share_buttons_position == "above") {
        if (get_post_type() === 'post') {
            add_filter("generate_before_content",  "display_ftm_social_share_buttons_on_hook");
        }
    }

    if ($parent_theme_name == "generatepress" && $share_buttons_position == "below") {
        if (get_post_type() === 'post') {
            add_filter("generate_after_content",  "display_ftm_social_share_buttons_on_hook");
        }
    }

    if ($parent_theme_name == "FTM Base Theme" && $share_buttons_position == "aftertitle") {
        if (get_post_type() === 'post') {
            add_action("ftm_after_single_title_hook",  "display_ftm_social_share_buttons_on_hook");
        }
    }

    if ($parent_theme_name == "FTM Base Theme" && $share_buttons_position == "below") {
        if (get_post_type() === 'post') {
            add_action("ftm_after_single_content_hook",  "display_ftm_social_share_buttons_on_hook");
        }
    }

    if ($parent_theme_name == "FTM Base Theme" && $share_buttons_position == "above") {
        if (get_post_type() === 'post') {
            add_filter("ftm_before_single_title_hook",  "display_ftm_social_share_buttons_on_hook");
        }
    }
}

add_action("template_redirect", 'ftm_social_share_buttons_handle');
add_shortcode('ftm_social_media_share_buttons', 'get_ftm_social_share_buttons_output');

/*
 * ---------------------------------------------------------------------------------------
 * END: ALLOW USERS TO USE A DIFFERENT PROFILE PIC RATHER THAN GRAVATAR'S ONE
 * ---------------------------------------------------------------------------------------
 */


/*
 * ---------------------------------------------------------------------------------------
 * BEGIN: BREADCRUMBS
 * ---------------------------------------------------------------------------------------
 */
add_action('ftm_before_content_hook', "ftm_base_breadcrumbs");

function ftm_base_breadcrumbs()
{
    echo '<div class="ftm_blog_content_wrapper site_content_wrapper">';
    if (
        function_exists('rank_math_the_breadcrumbs')
        && (!is_home() && !is_front_page())
    ) {
        rank_math_the_breadcrumbs();
    }
    echo '</div>';
}

/*
 * ---------------------------------------------------------------------------------------
 * END: BREADCRUMBS
 * ---------------------------------------------------------------------------------------
 */

/*
 * ---------------------------------------------------------------------------------------
 * BEGIN: AUTHOR BOX
 * ---------------------------------------------------------------------------------------
 */

add_action('ftm_after_single_content_hook', 'show_author_box');

function show_author_box()
{
    global $post;
    if (is_single()) {

        $post_content = get_post($post->ID)->post_content;
        $author = get_the_author();
        $author_desc = get_the_author_meta('description');
        $author_url = esc_url(get_author_posts_url(get_the_author_meta('ID')));
        $profile_picture = get_user_meta(get_the_author_meta('ID'), 'ftm_custom_profile_picture', true);
        $profile_picture_id = attachment_url_to_postid($profile_picture);
        $profile_picture_alt_text = get_post_meta($profile_picture_id, '_wp_attachment_image_alt', true); // Get the alt text

        if (empty($author_desc) || (strpos($post_content, $author_desc) !== false)) {
            //    return;
        }

        $html = '<div class="author-box">
    <a href="' . $author_url . '" class="author-box__avatar"><img alt="' . $profile_picture_alt_text . '" src="' . $profile_picture . '"/></a>
    <div class="author-box__text">
    <a href="' . $author_url . '">
    <div class="author-box__name">
    ' . $author . '</div>
    </a>
    <div class="author-box__bio">
    <p>' . $author_desc . '</p>
    </div>
    </div>
    </div>';

        echo $html;
    }
}

/*
 * ---------------------------------------------------------------------------------------
 * END: AUTHOR BOX
 * ---------------------------------------------------------------------------------------
 */

/*
 * ---------------------------------------------------------------------------------------
 * BEGIN: SHOW LATEST POSTS
 * ---------------------------------------------------------------------------------------
 */

add_action('ftm_after_single_content_hook', 'show_related_posts');
function show_related_posts()
{
    global $post;

    $post_type = (!empty(get_theme_mod('ftm_general_site_related_posts_post_type'))) ? get_theme_mod('ftm_general_site_related_posts_post_type') : 'self';

    $current_post_terms = wp_get_post_terms($post->ID, 'category');
    if ($post_type == 'self') {
        $post_type = $post->post_type;
    }

    foreach ($current_post_terms as $term) {
        $current_post_terms_arr[] = $term->term_id;
    }

    $latest_posts_title = 'Related Posts';
    $args = array(
        'post_type'      => $post_type,
        'post_status'    => 'publish',
        'posts_per_page' => 3,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'post__not_in'   => [$post->ID],
    );
    if (!empty($current_post_terms)) {
        $args['category__in'] = $current_post_terms_arr;
    }
    $query = new WP_Query($args);

    $html = '<div class="latest narrow horizontal" id="latest_post_wrapper">
    			<div class="related--posts-title">' . $latest_posts_title . '</div>';

    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post();

            $html .= '<article>';
            if (has_post_thumbnail()) :
                $html .= '<div class="post-thumbnail regular">
                                    <a href="' . get_the_permalink() . '">
                                        ' . get_the_post_thumbnail($post->ID, 'medium') . '
                                        <div class="post_meta">
                                            <span class="author">By: ' . get_the_author_meta('display_name') . '&nbsp;|&nbsp;</span>
                                            <span class="post-date">' . get_the_modified_date() . '</span>
                                        </div>
                                    </a>
                                </div>';
            endif;

            $html .= '<div class="related--post-title"><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></div>
                     </article>';
        endwhile;
        wp_reset_postdata();
    endif;
    $html .= '</div>';
    echo $html;
}

/*
 * ---------------------------------------------------------------------------------------
 * END: SHOW LATEST POSTS
 * ---------------------------------------------------------------------------------------
 */


/*
 * ---------------------------------------------------------------------------------------
 * START: CONVERT RANK MATH FAQ BLOCK INTO ACCORDION
 * ---------------------------------------------------------------------------------------
 */
function turn_rm_faq_to_accordion()
{
?>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            try {
                var faqBlock = document.querySelector("div.rank-math-block");
                if (faqBlock) {
                    var faqItems = faqBlock.querySelectorAll("div.rank-math-list-item");
                    if (faqItems.length > 0) {
                        faqItems.forEach(function(item) {
                            item.addEventListener("click", function(event) {
                                if (item.classList.contains('opened') == false) {
                                    item.classList.remove('closed');
                                    item.classList.add('opened');
                                } else {
                                    item.classList.remove('opened');
                                    item.classList.add('closed');
                                }

                                var answer = item.querySelector("div.rank-math-answer");
                                if (answer.classList.contains('opened') == false) {
                                    answer.classList.remove('closed');
                                    answer.classList.add('opened');
                                } else {
                                    answer.classList.remove('opened');
                                    answer.classList.add('closed');
                                }

                            });

                        });
                    }
                }
            } catch (error) {

            }
        });
    </script>
<?php
}
add_action('wp_footer', 'turn_rm_faq_to_accordion');

/*
 * ---------------------------------------------------------------------------------------
 * END: CONVERT RANK MATH FAQ BLOCK INTO ACCORDION
 * ---------------------------------------------------------------------------------------
 */


/*
 * ---------------------------------------------------------------------------------------
 * START: CREATE YEAR AND MONTH SHORTCODES TO REPLACE WITH CURRENT YEAR or MONTH
 * ---------------------------------------------------------------------------------------
 */

// Create Year shortcode to replace with current year.
add_shortcode('year', 'current_year');
function current_year()
{
    $year = date('Y');
    return $year;
}

add_shortcode('month', 'current_month');
function current_month()
{
    $month = date('F');
    return $month;
}

// To allow Rank Math Frontend title to parse shortcode.
add_filter(
    'rank_math/frontend/title',
    function ($title) {
        return do_shortcode($title);
    }
);

// Activate shortcode function in Post Title.
add_filter('the_title', 'do_shortcode');

/*
 * ---------------------------------------------------------------------------------------
 * END: CREATE YEAR AND MONTH SHORTCODES TO REPLACE WITH CURRENT YEAR or MONTH
 * ---------------------------------------------------------------------------------------
 */

/*
 * ---------------------------------------------------------------------------------------
 * START: CREATE AFFILIATE DISCLOSURE SHORTCODE 
 * ---------------------------------------------------------------------------------------
 */

// Create Year shortcode to replace with current year.
add_shortcode('affiliate_disclosure', 'affiliate_disclosure');
function affiliate_disclosure()
{
    $html  = '<p class="affiliate--disclosure">';
    $html .= get_theme_mod('features_affiliates', 'Our team of experts diligently research and review all of the products and services we recommend. If you buy through our links, we may receive a commission.');
    $html .= '</p>';
    return $html;
}

/*
 * ---------------------------------------------------------------------------------------
 * END: CREATE AFFILIATE DISCLOSURE SHORTCODE 
 * ---------------------------------------------------------------------------------------
 */

/*
 * ---------------------------------------------------------------------------------------
 * START: CREATE POST INFO SHORTCODE
 * ---------------------------------------------------------------------------------------
 */


function get_author_info_block_content_output($override_location = false)
{

    global $post;

    $disable_top_post_info = true;
    $disable_top_field_value = get_field('disable_top_post_info');
    if (isset($disable_top_field_value)) {
        if (get_field('disable_top_post_info')) {
            $disable_top_post_info = false;
        }
    }
    // Get the last updated date of the post
    $last_updated_date = get_the_modified_date('', $post->ID);

    $result_output = '';
    $output = '';
    $output .= '<div class="post-info-box">';
    $output .= '<div class="post-meta">';
    $output .= '<div>By: <a href="' . get_author_posts_url(get_the_author_meta('ID')) . '">' . get_the_author_link() . '</a> | Last Updated: ' .  $last_updated_date . '</div>';
    $output .= do_shortcode('[ftm_social_media_share_buttons]');
    $output .= '</div>';
    $output .= '</div>';

    if ($disable_top_post_info == false) { //The field exists on the page or post and is set to hide the top info
        $output = '';
        $result_output = '';
    }

    if ($override_location) {
        $esult_output =  $output;
    } else { //do not print on special template pages
        if (!is_page_template('templates/author-profile.php')) {
            $result_output = $output;
        }
    }

    echo $result_output;
}

function get_author_info_block_content()
{
    return get_author_info_block_content_output(true);
}
add_shortcode('ftm_display_post_info', 'get_author_info_block_content');
//Display the post info at the top of every page
add_action('ftm_after_single_title_hook', "get_author_info_block_content_output");
add_action('ftm_after_page_title_hook', "get_author_info_block_content_output");

/*
 * ---------------------------------------------------------------------------------------
 * END: CREATE POST INFO SHORTCODE
 * ---------------------------------------------------------------------------------------
 */

/*
 * ---------------------------------------------------------------------------------------
 * START: POPULATE THEME HOOKS
 * ---------------------------------------------------------------------------------------
 */

function get_gtm_head_content()
{
    $ftm_head_customizer_gtm_head_script_setting = get_theme_mod('ftm_head_customizer_gtm_head_script_setting', '');

    if ($ftm_head_customizer_gtm_head_script_setting != '') {
        echo $ftm_head_customizer_gtm_head_script_setting;
    } else {
        echo '';
    }
}

function get_gtm_body_content()
{
    $ftm_head_customizer_gtm_body_script_setting = get_theme_mod('ftm_head_customizer_gtm_body_script_setting', '');

    if ($ftm_head_customizer_gtm_body_script_setting != '') {
        echo $ftm_head_customizer_gtm_body_script_setting;
    } else {
        echo '';
    }
}

function pupulate_theme_hooks()
{

    //Google Tag Manager Hooks
    add_action('ftm_head_top_content_hook', "get_gtm_head_content");
    add_action('ftm_body_top_content_hook', "get_gtm_body_content");
}
add_action('init', 'pupulate_theme_hooks');

/*
 * ---------------------------------------------------------------------------------------
 * END: POPULATE THEME HOOKS
 * ---------------------------------------------------------------------------------------
 */

/*
 * ---------------------------------------------------------------------------------------
 * START: AUTHOR CUSTOM LINK
 * 
 * Changes the author link in case we have a custom page in the /about-us/ section of the site for the specific author
 * ---------------------------------------------------------------------------------------
 */
add_filter('author_link', 'customize_author_link', 10, 2);
function customize_author_link($link, $author_id)
{

    $author_name = strtolower(str_ireplace(" ", "-", get_the_author_meta('display_name')));

    $page_exist = get_page_by_path("/about-us/$author_name/", OBJECT, "page");

    if ($author_name && $page_exist) {
        return get_home_url() . "/about-us/" . $author_name . '/';
    }

    return $link;
}

/*
 * ---------------------------------------------------------------------------------------
 * END: AUTHOR CUSTOM LINK
 * ---------------------------------------------------------------------------------------
 */

/*
 * ---------------------------------------------------------------------------------------
 * START: EXTEND SOCIAL LINK GUTENBERG BLOCK
 * ---------------------------------------------------------------------------------------
 */

function ftm_custom_block_editor_scripts()
{
    wp_enqueue_script(
        'ftm-social-block-extend',
        get_stylesheet_directory_uri() . '/assets/js/social-link-extend.js', // Adjust the path.
        array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-hooks'),
        filemtime(get_stylesheet_directory() . '/assets/js/social-link-extend.js')
    );
}
add_action('enqueue_block_editor_assets', 'ftm_custom_block_editor_scripts', 16);

function ftm_custom_extension_social_links_target_blank($block_content, $block)
{
    if ($block['blockName'] !== 'core/social-links') {
        return $block_content;
    }

    // Check if enableTargetBlank attribute is true and modify links
    if (!empty($block['attrs']['enableTargetBlank'])) {
        // Use preg_replace or a similar method to add target="_blank" to all links
        $block_content = preg_replace('/<a /', '<a target="_blank" ', $block_content);
    }

    return $block_content;
}
add_filter('render_block', 'ftm_custom_extension_social_links_target_blank', 10, 2);

/*
 * ---------------------------------------------------------------------------------------
 * END: EXTEND SOCIAL LINK GUTENBERG BLOCK
 * ---------------------------------------------------------------------------------------
 */


/*
 * ---------------------------------------------------------------------------------------
 * START: SEARCH BY TYPESENSE
 * ---------------------------------------------------------------------------------------
 */

//Check function to determine if the search by Typesense plugin is installed
function is_typesense_active()
{
    if (is_plugin_active('search-with-typesense/codemanas-typesense.php')) {
        return true;
    } else {
        // Plugin is not active
        return false;
    }
}

function get_typesense_excluded_posts()
{
    $result = '';
    $exclusion_enabled = get_theme_mod('ftm_features_typesense_exclusion_enabled', false);

    if ($exclusion_enabled) {
        $exclusion_list = get_theme_mod('ftm_features_typesense_exclude_posts', '');
        if ($exclusion_list != '') {
            $result = $exclusion_list;
        }
    }

    return $result;
}

//Create Hidden Custom Post Type if Typesense search is active
function create_hidden_custom_post_type()
{
    $args = array(
        'label'               => 'TypeSense All',
        'public'              => false,
        'exclude_from_search' => true,
        'publicly_queryable'  => false,
        'show_ui'             => true,
        'show_in_menu'        => false,
        'capability_type'     => 'post',
        'hierarchical'        => false,
        'supports'            => array('title', 'editor', 'custom-fields'),
        'has_archive'         => false,
        'rewrite'             => false,
        'query_var'           => false,
    );
    register_post_type('tsall', $args);
}

//Add hidden post to a the custom post type
function add_hidden_post()
{

    // Check if the custom post type exists
    if (!post_type_exists('tsall')) {
        return; // Custom post type does not exist, exit the function
    }

    // Query to check if any posts of this custom post type exist
    $existing_posts = new WP_Query(array(
        'post_type'      => 'tsall',
        'post_status'    => 'publish',
        'posts_per_page' => 1,
    ));

    // If a post already exists, exit the function
    if ($existing_posts->have_posts()) {
        return;
    }

    // Prepare post data
    $post_data = array(
        'post_title'    => 'Hidden Post Title',
        'post_content'  => 'This is the content of the hidden post.',
        'post_status'   => 'publish',
        'post_type'     => 'tsall',
    );

    // Insert the post
    $post_id = wp_insert_post($post_data);

    if (is_wp_error($post_id)) {
        error_log('Error creating hidden post: ' . $post_id->get_error_message());
    }
}

if (is_typesense_active()) {
    add_action('init', 'create_hidden_custom_post_type');
    add_action('init', 'add_hidden_post');
}


function cm_typesense_add_available_post_types($available_post_types)
{
    $available_post_types['blog'] = ['label' => 'Blog', 'value' => 'blog'];
    $available_post_types['reviews'] = ['label' => 'Reviews', 'value' => 'reviews'];
    $available_post_types['tsall'] = ['label' => 'All Post Types', 'value' => 'tsall'];

    return $available_post_types;
}

if (is_typesense_active()) {
    add_filter('cm_typesense_available_index_types',  'cm_typesense_add_available_post_types');
}

//only necessary if the default post schema is not necessary
function cm_typesense_add_blog_schema($schema, $name)
{
    if ($name == 'blog') {
        $schema = [
            'name'                  => 'blog',
            'fields'                => [
                ['name' => 'post_content', 'type' => 'string'],
                ['name' => 'post_title', 'type' => 'string'],
                ['name' => 'post_type', 'type' => 'string'],
                ['name' => 'comment_count', 'type' => 'int64'],
                ['name' => 'is_sticky', 'type' => 'int32'],
                ['name' => 'post_excerpt', 'type' => 'string'],
                ['name' => 'post_date', 'type' => 'string'],
                ['name' => 'post_id', 'type' => 'string'],
                ['name' => 'post_modified', 'type' => 'string'],
                ['name' => 'id', 'type' => 'string'],
                ['name' => 'permalink', 'type' => 'string'],
                ['name' => 'post_thumbnail', 'type' => 'string'],
            ],
            'default_sorting_field' => 'comment_count'
        ];
    }

    return $schema;
}

if (is_typesense_active()) {
    if (post_type_exists('reviews')) {
        add_filter('cm_typesense_schema', 'cm_typesense_add_blog_schema', 10, 2);
    }
}

function cm_typesense_add_reviews_schema($schema, $name)
{
    if ($name == 'reviews') {
        $schema = [
            'name'                  => 'reviews',
            'fields'                => [
                ['name' => 'post_content', 'type' => 'string'],
                ['name' => 'post_title', 'type' => 'string'],
                ['name' => 'post_type', 'type' => 'string'],
                ['name' => 'comment_count', 'type' => 'int64'],
                ['name' => 'is_sticky', 'type' => 'int32'],
                ['name' => 'post_excerpt', 'type' => 'string'],
                ['name' => 'post_date', 'type' => 'string'],
                ['name' => 'post_id', 'type' => 'string'],
                ['name' => 'post_modified', 'type' => 'string'],
                ['name' => 'id', 'type' => 'string'],
                ['name' => 'permalink', 'type' => 'string'],
                ['name' => 'post_thumbnail', 'type' => 'string', 'facet' => true],
            ],
            'default_sorting_field' => 'comment_count'
        ];
    }

    return $schema;
}

if (is_typesense_active()) {
    if (post_type_exists('reviews')) {
        add_filter('cm_typesense_schema', 'cm_typesense_add_reviews_schema', 10, 2);
    }
}


function cm_typesense_add_customSearchData_schema($schema, $name)
{
    if ($name == 'reviews' || $name == 'blog') {
        $schema = [
            'name'                  => 'tsall',
            'fields'                => [
                ['name' => 'post_content', 'type' => 'string'],
                ['name' => 'post_title', 'type' => 'string'],
                ['name' => 'post_type', 'type' => 'string'],
                ['name' => 'comment_count', 'type' => 'int64'],
                ['name' => 'is_sticky', 'type' => 'int32'],
                ['name' => 'post_excerpt', 'type' => 'string'],
                ['name' => 'post_date', 'type' => 'string'],
                ['name' => 'post_id', 'type' => 'string'],
                ['name' => 'post_modified', 'type' => 'string'],
                ['name' => 'permalink', 'type' => 'string'],
                ['name' => 'post_thumbnail', 'type' => 'string', 'facet' => true],
            ],
            'default_sorting_field' => 'comment_count'
        ];
    }

    return $schema;
}

if (is_typesense_active()) {
    if (post_type_exists('all')) {
        add_filter('cm_typesense_schema', 'cm_typesense_add_customSearchData_schema', 10, 2);
    }
}


//FORTMAT THE DATA
function cm_typesense_format_customn_post_type_data($formatted_data, $raw_data, $object_id, $schema_name)
{


    if ($schema_name == 'reviews') {
        $formatted_data['post_thumbnail'] = (get_field('site_logo_url', $raw_data) ? get_field('site_logo_url', $raw_data) : '');
    }


    //$formatted_data['post_title'] = apply_filters( 'do_shortcode', $formatted_data['post_title']);
    $formatted_data['post_title'] = do_shortcode($formatted_data['post_title']);
    $formatted_data['post_content'] = strip_shortcodes($formatted_data['post_content']);

    return $formatted_data;
}

if (is_typesense_active()) {
    add_filter('cm_typesense_data_before_entry', 'cm_typesense_format_customn_post_type_data', 10, 4);
}

//Add inner different post_types to the tsall custom post type on bulk import
add_filter('cm_typesense_bulk_index_query_args', 'replace_bulk_import_for_all_cpt', 5, 1);

function replace_bulk_import_for_all_cpt($args)
{

    if ($args['post_type'] == 'tsall') {
        $args['post_type'] = ['reviews', 'blog', 'page'];
    }
    return $args;
}

//Make sure the title gets more match weight on the search request
add_filter('cm_typesense_additional_autocomplete_params', 'add_custom_typesense_autocomplete_filters', 10, 1);

function add_custom_typesense_autocomplete_filters()
{
    $new_filters = [];

    $new_filters['query_by_weights'] = '2,1';
    $new_filters['text_match_type'] = 'max_weight';

    return $new_filters;
}

add_filter('cm_typesense_additional_search_params', 'add_custom_typesense_search_filters', 10, 1);

function add_custom_typesense_search_filters()
{
    $new_filters = [];

    $new_filters['query_by_weights'] = '2,1';
    $new_filters['text_match_type'] = 'max_weight';

    return  json_encode($new_filters);
}

//Remove posts from being index on the bulk import process
add_filter('cm_typesense_bulk_import_skip_post', 'check_postID_for_typesense_exclusion', 10, 2);

function check_postID_for_typesense_exclusion($skip, $post)
{
    $theme_debug_active = get_theme_mod('feature_theme_debug', false);
    $exclusion_list_string = get_typesense_excluded_posts();
    $exclusion_list = array();
    $response = false;

    if ($exclusion_list_string != '') {
        $exclusion_list = explode(',', $exclusion_list_string);

        foreach ($exclusion_list as $excluded_post_id) {
            if ($excluded_post_id == $post->ID) {
                $response = true;

                //Debug info
                if ($theme_debug_active) {
                    error_log('Post Excluded from typesense' . $excluded_post_id);
                }
            }
        }
    }

    return $response;
}

/*
 * ---------------------------------------------------------------------------------------
 * END: SEARCH BY TYPESENSE
 * ---------------------------------------------------------------------------------------
 */

// Scheduled posts should update modified date when published
function update_modified_date_to_post_date($post)
{
    $updated_data = [
        'ID'                => $post->ID,
        'post_modified'     => $post->post_date,
        'post_modified_gmt' => $post->post_date_gmt
    ];
    wp_update_post($updated_data);
}
add_action('future_to_publish', 'update_modified_date_to_post_date', 10, 1);
