<?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");
    if (is_singular('reviews')) {
        wp_enqueue_style('ftm-swiper-css',  get_stylesheet_directory_uri() . '/assets/sass/swiper.css', array(), "1.0.0");
    }
    if (is_single()) {
        wp_enqueue_style('author-box', webpack('ftm_author_box.css'), '', '', 'all');
        wp_enqueue_style('ftm-media-logos', webpack('ftm_social.css'), array(), '', 'all');
    }
}

function ftm_base_add_js()
{

    if (is_singular('reviews')) {
        wp_enqueue_script('ftm-swiper-js', get_stylesheet_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()
{
    // 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' => false,
                'rewrite' => array('slug' => 'review'),
                'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'page-attributes', 'revisions'),
                '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_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',
                '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' => 0,
                ));
                
                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');

/**
 * 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_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
    );

    //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',
                ),
            ),
        ),
        '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_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,
    ));

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)
{
?>
    <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="">
                <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
                $image = get_user_meta($user->ID, 'ftm_custom_profile_picture', true);
                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')) 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_latest_posts');
function show_latest_posts()
{
    global $post;

    $current_post_terms = wp_get_post_terms($post->ID, 'category');

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

    $latest_posts_title = 'Related Posts';
    $args = array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'category__in'   => $current_post_terms_arr,
        'posts_per_page' => 3,
        'orderby'        => 'date',
        'order'          => 'DESC',
    );
    $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('nicename') . '&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 SHORTCODE TO REPLACE WITH CURRENT YEAR
 * ---------------------------------------------------------------------------------------
 */

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

// 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 SHORTCODE TO REPLACE WITH CURRENT YEAR
 * ---------------------------------------------------------------------------------------
 */