<?php
/**
 * Inbio functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package histudy
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

/**
 * Define Constants
 */
define('RAINBOW_THEME_URI', get_template_directory_uri());
define('RAINBOW_THEME_DIR', get_template_directory());
define('RAINBOW_CSS_URL', get_template_directory_uri() . '/assets/css/');
define('RAINBOW_RTL_CSS_URL', get_template_directory_uri() . '/assets/css/rtl/');
define('RAINBOW_CSS_FICON_URL', get_template_directory_uri() . '/assets/flaticon/');
define('RAINBOW_JS_URL', get_template_directory_uri() . '/assets/js/');
define('RAINBOW_RTL_JS_URL', get_template_directory_uri() . '/assets/js/rtl/');
define('RAINBOW_ADMIN_CSS_URL', get_template_directory_uri() . '/assets/admin/css/');
define('RAINBOW_ADMIN_JS_URL', get_template_directory_uri() . '/assets/admin/js/');
define('RAINBOW_DIRECTORY', RAINBOW_THEME_DIR . '/inc/');
define('RAINBOW_DIRECTORY_VIEW', RAINBOW_THEME_DIR . '/inc/views/');
define('RAINBOW_HELPER', RAINBOW_THEME_DIR . '/inc/helper/');
define('RAINBOW_OPTIONS', RAINBOW_THEME_DIR . '/inc/options/');
define('RAINBOW_CUSTOMIZER', RAINBOW_THEME_DIR . '/inc/customizer/');
define('RAINBOW_THEME_FIX', 'histudy');
define('RAINBOW_THEME_PT_PREFIX', 'rainbow');
define('RAINBOW_LAB', RAINBOW_THEME_DIR . '/inc/lab/');
define('RAINBOW_WOOCMMERCE', RAINBOW_THEME_DIR . '/woocommerce/custom/');
define('RAINBOW_LEARNPRESS', RAINBOW_THEME_DIR . '/learnpress/custom/');
define('RAINBOW_TP', RAINBOW_THEME_DIR . '/template-parts/');
define('RAINBOW_IMG_URL', RAINBOW_THEME_URI . '/assets/images/');
do_action('rainbow_theme_init');
$rainbow_theme_data = wp_get_theme();

define('RAINBOW_VERSION', (WP_DEBUG) ? time() : $rainbow_theme_data->get('Version'));

/* user info */
defined('WOOC_CORE_USER_LOGGED') or define('WOOC_CORE_USER_LOGGED', is_user_logged_in());

/* Check if WooCommerce active */
defined('WOOC_WOO_ACTIVED') or define('WOOC_WOO_ACTIVED', (bool) function_exists('WC'));

/* Check if tutor active */
defined('TUTOR_ACTIVED') or define('TUTOR_ACTIVED', (bool) function_exists('tutor'));

add_action('init', function() {
    load_theme_textdomain('histudy', get_template_directory() . '/languages');
});

if (!function_exists('rainbow_setup')):
    /**
     * 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 rainbow_setup() {
        /*
         * Make theme available for translation.
         * Translations can be filed in the /languages/ directory.
         * If you're building a theme based on histudy, use a find and replace
         * to change 'histudy' to the name of your theme in all the template files.
         */
        
        // Add default posts and comments RSS feed links to head.
        add_theme_support('automatic-feed-links');
        
        function mytheme_add_woocommerce_support() {
            if(class_exists('WooCommerce')) {
                add_theme_support('woocommerce');
            }
        }
        add_action('after_setup_theme', 'mytheme_add_woocommerce_support');
        /*
         * 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');

        // This theme uses wp_nav_menu() in one location.
        register_nav_menus(array(
            'primary' => __('Primary', 'histudy'),
            'sidenav' => __('Offcanvas Menu', 'histudy'),
            'footerbottom' => __('Footer Bottom Menu (No depth supported)', 'histudy'),
            'headertop' => __('Header Top Menu (No depth supported)', 'histudy'),
            'categorymenu' => __('Category Menu', 'histudy'),
            'mobilemenu' => __('Mobile Menu', 'histudy'),
        ));
        
        /*
         * 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',
        ));

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

        /*
         * Post Format
         */
        add_theme_support('post-formats', array('gallery', 'link', 'quote', 'video', 'audio'));
        remove_theme_support('widgets-block-editor');

        add_editor_style(array('style-editor.css', rainbow_fonts_url()));
        add_theme_support('responsive-embeds');
        add_theme_support('wp-block-styles');
        add_theme_support('editor-styles');
        add_editor_style('style-editor.css');

        /*
         * Color Support
         */
        add_theme_support('align-wide');
        add_theme_support('editor-color-palette', array(
            array(
                'name' => esc_html__('Primary', 'histudy'),
                'slug' => 'histudy-primary',
                'color' => '#ff014f',
            ),
            array(
                'name' => esc_html__('Secondary', 'histudy'),
                'slug' => 'histudy-secondary',
                'color' => '#FFDC60',
            ),
            array(
                'name' => esc_html__('Tertiary', 'histudy'),
                'slug' => 'histudy-tertiary',
                'color' => '#FAB8C4',
            ),
            array(
                'name' => esc_html__('White', 'histudy'),
                'slug' => 'histudy-white',
                'color' => '#ffffff',
            ),
            array(
                'name' => esc_html__('Dark', 'histudy'),
                'slug' => 'histudy-dark',
                'color' => '#27272E',
            ),
        ));
        /*
         * Font Size
         */
        add_theme_support('editor-font-sizes', array(
            array(
                'name' => esc_html__('Small', 'histudy'),
                'size' => 12,
                'slug' => 'small',
            ),
            array(
                'name' => esc_html__('Normal', 'histudy'),
                'size' => 16,
                'slug' => 'normal',
            ),
            array(
                'name' => esc_html__('Large', 'histudy'),
                'size' => 36,
                'slug' => 'large',
            ),
            array(
                'name' => esc_html__('Huge', 'histudy'),
                'size' => 50,
                'slug' => 'huge',
            ),
        ));

        /*
         * Add Custom Image Size
         */
        add_image_size('rainbow-thumbnail-sm', 340, 250, true);
        add_image_size('rainbow-thumbnail-md', 400, 400, true);
        add_image_size('rainbow-thumbnail-lg', 800, 600, true);
        add_image_size('rainbow-thumbnail-archive', 800, 450, true);
        add_image_size('rainbow-thumbnail-single', 1220, 686, true);
        add_image_size('rainbow-course-card-list', 231, 324, true);

    }
endif;
add_action('after_setup_theme', 'rainbow_setup');

add_filter('image_size_names_choose', 'rainbow_new_image_sizes');
if (!function_exists('rainbow_new_image_sizes')) {
    /**
     * Image Size Name Choose
     *
     * @param $sizes
     * @return array
     */
    function rainbow_new_image_sizes($sizes) {
        return array_merge($sizes, array(
            'rainbow-thumbnail-sm' => __('Thumbnail Small - (335x250)', 'histudy'),
            'rainbow-thumbnail-md' => __('Thumbnail Medium - (400x400)', 'histudy'),
            'rainbow-thumbnail-lg' => __('Thumbnail large - (800x600)', 'histudy'),
            'rainbow-thumbnail-archive' => __('Thumbnail Archive - (800x450)', 'histudy'),
            'rainbow-thumbnail-single' => __('Thumbnail Single - (1220x686)', 'histudy'),
        ));
    }
}

if (!function_exists('rainbow_content_width')) {
    /**
     * Set the content width in pixels, based on the theme's design and stylesheet.
     *
     * Priority 0 to make it available to lower priority callbacks.
     *
     * @global int $content_width
     */
    function rainbow_content_width() {
        // This variable is intended to be overruled from themes.
        // Open WPCS issue: {@link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/1043}.
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
        $GLOBALS['content_width'] = apply_filters('rainbow_content_width', 640);
    }
}

add_action('after_setup_theme', 'rainbow_content_width', 0);

/**
 * Enqueue scripts and styles.
 */
require_once RAINBOW_DIRECTORY . "scripts.php";
/**
 * Global Functions
 */
require_once RAINBOW_DIRECTORY . "global-functions.php";

/**
 * Register Custom Widget Area
 */
require_once RAINBOW_DIRECTORY . "widget-area-register.php";

/**
 * Register Custom Fonts
 */
require_once RAINBOW_DIRECTORY . "register-custom-fonts.php";

/**
 * TGM Register
 */
require_once RAINBOW_DIRECTORY . "tgm-config.php";

/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/underscore/custom-header.php';

/**
 * Custom Footer For Mobile
 */
add_action( 'init', function() {
    require get_template_directory() . '/inc/custom-mobile-footer.php';
} );


/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/underscore/template-tags.php';

/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/inc/underscore/template-functions.php';

/**
 * Load Jetpack compatibility file.
 */
if (defined('JETPACK__VERSION')) {
    require get_template_directory() . '/inc/underscore/jetpack.php';
}
/**
 * Functions for histudy envato purchase check.
 */
require_once get_template_directory() . '/inc/class-hi-study-base.php';
require_once get_template_directory() . '/inc/class-hi-study-activation.php';

/**
 * Helper Template
 */
require_once RAINBOW_HELPER . "menu-area-trait.php";
require_once RAINBOW_HELPER . "layout-trait.php";
require_once RAINBOW_HELPER . "option-trait.php";
require_once RAINBOW_HELPER . "meta-trait.php";
require_once RAINBOW_HELPER . "banner-trait.php";
require_once RAINBOW_HELPER . "course-cart-trait.php";
require_once RAINBOW_HELPER . "course-details-trait.php";
require_once RAINBOW_HELPER . "tutor/card-trait.php";
require_once RAINBOW_HELPER . "social-trait.php";
require_once RAINBOW_HELPER . "page-title-trait.php";
require_once RAINBOW_HELPER . "pagination-trai.php";
require_once RAINBOW_HELPER . "shop-details-banner-trait.php";
require_once RAINBOW_HELPER . "become-instructor-trait.php";
require_once RAINBOW_HELPER . "become-student-trait.php";

/**
 * Helper
 */
require_once RAINBOW_HELPER . "helper.php";
add_filter( 'wp_head', 'histudy_insert_css' );
function histudy_insert_css() {
    if( !class_exists( 'RAINBOW_ELEMENTS' ) ) {
        ob_start();
        ?>
        <style>
            .course-archive-page, .tutor-course-details-page.tutor-container {
                padding-top: 120px;
                padding-bottom: 120px;
            }
            .course-archive-page .rbt-card .rbt-tutor-card-body .tutor-ratings {
                display: none;
            }
            .tutor-card.tutor-sidebar-card .tutor-card-body {
                padding: 30px;
                border-radius: 6px;
                margin-bottom: 30px;
            }
            .course-archive-page .dropdown.bootstrap-select.tutor-form-select {
                display: none;
            }
        </style>
        <?php
        echo ob_get_clean();
    }
}
/**
 * Options
 */
/**
 * Options (Check License for option menu)
 */
require_once RAINBOW_OPTIONS . "theme/option-framework.php";
add_action('init', function() {
    $licence_activated = HiStudyEducationThemes::$licence_activated;
    require_once RAINBOW_OPTIONS . "theme/generic-theme-options.php";
    if($licence_activated) {
        require_once RAINBOW_OPTIONS . "theme/option-framework.php";
    } else {
        global $histudy_options;
        $file_path = RAINBOW_OPTIONS . 'predefined-data.json';


        global $wp_filesystem;

        // Initialize the WordPress filesystem
        if (empty($wp_filesystem)) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
        }

        // Check if the file exists using WP_Filesystem
        if ($wp_filesystem->exists($file_path)) {
            // Get the file content using WP_Filesystem
            $predefined_data = $wp_filesystem->get_contents($file_path);

            $rainbow_optionss = json_decode($predefined_data, true);

            if (json_last_error() === JSON_ERROR_NONE) {
                global $options;
                $rainbow_optionss = isset($GLOBALS['rainbow_options']) ? wp_parse_args($GLOBALS['rainbow_options'], $options) : $rainbow_optionss;

                return $rainbow_optionss;
            } 
        } 
        $histudy_options = $rainbow_optionss;
        require_once( RAINBOW_OPTIONS . 'theme/inactive-theme-options.php');
        remove_action('admin_menu', 'histudy_options');
    }
});

add_action('admin_menu', 'remove_histudy_options_page');
require_once RAINBOW_OPTIONS . "page-options.php";
require_once RAINBOW_OPTIONS . "portfolio-options.php";
require_once RAINBOW_OPTIONS . "post-format-options.php";
require_once RAINBOW_OPTIONS . "user-extra-meta.php";
require_once RAINBOW_OPTIONS . "menu-options.php";
require_once RAINBOW_OPTIONS . "team-extra-meta.php";
require_once RAINBOW_OPTIONS . "woo-options.php";
function remove_histudy_options_page() {
    $licence_activated = HiStudyEducationThemes::$licence_activated;
    if( !$licence_activated ) {
        if (function_exists('remove_submenu_page') && !empty(get_admin_page_parent('themes.php'))) {
            remove_submenu_page('themes.php', 'histudy_options');
        }
    }
}

/**
 * Customizer
 */
require_once RAINBOW_CUSTOMIZER . "color.php";

/**
 * Lab
 */
require_once RAINBOW_LAB . "class-tgm-plugin-activation.php";
require_once RAINBOW_DIRECTORY . "demo-import-config.php";

/**
 * Nav Walker
 */
require_once RAINBOW_LAB . "nav-menu-walker.php";
require_once RAINBOW_LAB . "mobile-menu-walker.php";
require_once RAINBOW_LAB . "nav-menu-walker-category.php";
require_once RAINBOW_TP . "breadcrumb.php";
require_once RAINBOW_LAB . "post-views.php";

/**
 * WooCommerce
 */

if ( class_exists('WooCommerce') ) {
    require_once RAINBOW_WOOCMMERCE . "wooc-functions.php";
    require_once RAINBOW_WOOCMMERCE . "wooc-hooks.php";
}

if( class_exists( 'LearnPress' ) ) { 
    require_once RAINBOW_LEARNPRESS . "lp-hooks.php";
    require_once RAINBOW_LEARNPRESS . "lp-functions.php";
}


/**
 * User login
*/
function rbt_ajax_user_login() {
    $rainbow_options                       = Rainbow_Helper::rainbow_get_options();
    $redirect_type                         = $rainbow_options['rainbow_login_redirect_type'];
    $rainbow_login_page                    = $rainbow_options['rainbow_login_page'];
    $rainbow_login_custom_url              = $rainbow_options['rainbow_login_custom_url'];
    $rainbow_username_pass_not_found_error = $rainbow_options['rainbow_username_pass_not_found_error'];
    $rainbow_username_pass_not_valid_error = $rainbow_options['rainbow_username_pass_not_valid_error'];
    $rainbow_login_successfull_message     = $rainbow_options['rainbow_login_successfull_message'];
    if( 'page' == $redirect_type ) {
        $page_id = $rainbow_login_page;
        $login_redirect_url = get_the_permalink( $page_id );
    } else {
        $login_redirect_url = esc_url($rainbow_login_custom_url);
    }

    if (!isset($_POST['nonce'])) {
        return wp_send_json_error(array('success' => false, 'messages' => 'Nonce does not exist'));
    }

    if (wp_verify_nonce(wp_unslash($_POST['nonce']), 'histudy_form_account')) {
        $user_login = sanitize_text_field($_POST['user_login']);
        $password   = sanitize_text_field($_POST['password']);
        $remember   = isset($_POST['rememberme']) && 'forever' === sanitize_text_field($_POST['rememberme']) ? true : false;

        if (empty($user_login) || empty($password)) {
            return wp_send_json_error(array('success' => false, 'messages' => esc_html($rainbow_username_pass_not_found_error)));
        }

        if (filter_var($user_login, FILTER_VALIDATE_EMAIL)) {
            $user = get_user_by('email', $user_login);
        } else {
            $user = get_user_by('login', $user_login);
        }

        if (!$user instanceof WP_User || !wp_check_password($password, $user->data->user_pass, $user->ID)) {
            return wp_send_json_error(array( 'success' => false, 'messages' => esc_html( $rainbow_username_pass_not_valid_error )));
        }

        $credentials = [
            'user_login'    => $user->data->user_login,
            'user_password' => $password,
            'remember'      => $remember,
        ];
        $user = wp_signon($credentials);
        if (is_wp_error($user)) {
            return wp_send_json_error(array('success' => false, 'messages' => $user->get_error_message()));
        }

        $redirect_url = '';

        // Define your redirect logic here
        switch ($redirect_type) {
            case 'home':
                $redirect_url = home_url();
                break;
            case 'dashboard':
                if (function_exists('tutor') && function_exists('tutor_utils')) {
                    $redirect_url = tutor_utils()->get_tutor_dashboard_page_permalink();
                }
                break;
            case 'custom':
                $redirect_url = esc_url($rainbow_login_custom_url);
                break;
            default:
                $redirect_url = $login_redirect_url;
        }
        return wp_send_json_success(array('success' => true, 'redirect' => $redirect_url, 'messages' => esc_html( $rainbow_login_successfull_message )));
    }

    return wp_send_json_error(array('success' => false, 'messages' => 'User not valid!'));
}

add_action( 'wp_ajax_rbt_ajax_user_login','rbt_ajax_user_login' );
add_action( 'wp_ajax_nopriv_rbt_ajax_user_login','rbt_ajax_user_login' );

/**
 * User registration
 */
add_action( 'wp_ajax_rbt_ajax_user_registration','rbt_ajax_user_registration' );
add_action( 'wp_ajax_nopriv_rbt_ajax_user_registration','rbt_ajax_user_registration' );
function rbt_ajax_user_registration() {
    if( !isset($_POST['nonce']) ) {
        return wp_send_json_error( array( 'messages' => __( 'Nonce does not exist', 'histudy' ) ) );
    }

    if( wp_verify_nonce( wp_unslash( $_POST['nonce'] ), 'histudy_form_account' ) ) {
        if( !get_option('users_can_register') ) {
            return wp_send_json_error( 
                array(
                    'success' => false,
                    'messages' => __( 'Sorry! User Ragistration Disabled.', 'histudy' )
                )
            );
        }
        $rainbow_options                           = Rainbow_Helper::rainbow_get_options();
        $rainbow_registration_redirect_type        = $rainbow_options['rainbow_registration_redirect_type'];
        $rainbow_registration_page                 = $rainbow_options['rainbow_registration_page'];
        $rainbow_registration_custom_url           = $rainbow_options['rainbow_registration_custom_url'];
        $rainbow_user_registration_success_message = $rainbow_options['rainbow_user_registration_success_message'];
        $rainbow_registration_valid_email_error    = $rainbow_options['rainbow_registration_valid_email_error'];
        $rainbow_already_registared_by_email       = $rainbow_options['rainbow_already_registared_by_email'];
        $rainbow_insert_all_required_fields       = $rainbow_options['rainbow_insert_all_required_fields'];
        $rainbow_valid_username_error              = $rainbow_options['rainbow_valid_username_error'];
        $rainbow_username_exists_error             = $rainbow_options['rainbow_username_exists_error'];
        $rainbow_privacy_policty_check_error       = $rainbow_options['rainbow_privacy_policty_check_error'];
        
    
        if ( empty( $_POST['firstname'] ) || empty( $_POST['lastname'] ) || empty( $_POST['email'] ) || empty( $_POST['password'] ) || empty( $_POST['username'] ) ) {
            wp_send_json_error( ['success' => false, 'messages' => esc_html( $rainbow_insert_all_required_fields ) ] );
        }
    
        $email      = sanitize_email( $_POST['email'] );
        $user_login = sanitize_user( $_POST['username'] );
        $password   = sanitize_text_field( $_POST['password'] );
        $check_password   = sanitize_text_field( $_POST['check_password'] );
        $firstname  = sanitize_text_field( $_POST['firstname'] );
        $lastname   = sanitize_text_field( $_POST['lastname'] );
        if($password !== $check_password) {
            return wp_send_json_error( ['success' => false, 'messages' => __( 'Password are not matched', 'histudy' ) ] );
        }
        if ( ! is_email( $email ) ) {
            return wp_send_json_error( ['success' => false, 'messages' => esc_html( $rainbow_registration_valid_email_error ) ] );
        }
    
        if ( email_exists( $email ) ) {
            return wp_send_json_error( ['success' => false, 'messages' => esc_html( $rainbow_already_registared_by_email ) ] );
        }
    
        if ( ! validate_username( $user_login ) ) {
            return wp_send_json_error( [ 'success' => false, 'messages' => esc_html( $rainbow_valid_username_error ) ] );
        }
    
        if ( username_exists( $user_login ) ) {
            return wp_send_json_error( [ 'success' => false, 'messages' => esc_html( $rainbow_username_exists_error ) ] );
        }
    
        if ( ! isset( $_POST['accept_account'] ) && '1' !== $_POST['accept_account'] ) {
            return wp_send_json_error( [ 'success' => false, 'messages' => esc_html( $rainbow_privacy_policty_check_error ) ] );
        }
        $userdata = [
            'first_name' => $firstname,
            'last_name'  => $lastname,
            'user_login' => $user_login,
            'user_email' => $email,
            'user_pass'  => $password,
        ];
    
        $user_id = wp_insert_user( $userdata );
    
        if ( ! is_wp_error( $user_id ) ) {
            $creds                  = array();
            $creds['user_login']    = $user_login;
            $creds['user_email']    = $email;
            $creds['user_password'] = $password;
            $creds['remember']      = true;
            $user                   = wp_signon( $creds, false );
            $redirect_url = home_url();
            return wp_send_json_success( array( 'success' => true ,'messages' => esc_html( $rainbow_user_registration_success_message ), 'redirect' => esc_url($redirect_url) ) );
        } else {
            return wp_send_json_error( [ 'success' => false,'messages' => __( 'some error', 'histudy' ) ] );
        }
    }
    die;
}



/**
 * Ajax actions
 */
add_action('wp_ajax_rainbow_loadmore_projects', 'rainbow_loadmore_projects');
add_action('wp_ajax_nopriv_rainbow_loadmore_projects', 'rainbow_loadmore_projects');
 if (!function_exists('awescapeing')) {
    function awescapeing($html)
    {
        return $html;
    }
}

/**
 * Ajax functions are here
 */

function rtb_wc_refresh_mini_cart_count($fragments)
{
    ob_start();
?>
    <div class="rbt-cart-count">
        <?php echo WC()->cart->get_cart_contents_count(); ?>
    </div>
<?php
    $fragments['#rbt-cart-count'] = ob_get_clean();
    return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'rtb_wc_refresh_mini_cart_count');
function rtb_wc_refresh_get_subtotal($fragments)
{
    ob_start();
?>
    <div class="woocommerce-Price-amount">
        <?php echo WC()->cart->get_cart_subtotal(); ?>
    </div>
<?php
    $fragments['.rbt-cart-subttotal .woocommerce-Price-amount'] = ob_get_clean();
    return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'rtb_wc_refresh_get_subtotal');


// Update Cart Count & Mini Cart

function rbt_cart_add_fragment($fragments)
{
    ob_start();
    global $product;
    $items_to_show = apply_filters('histudy_mini_cart_items_to_show', 10);
    if (!empty(WC()->cart->get_cart_contents_count())) { ?>
        <?php echo get_template_part('template-parts/components/woocommerce/minicart'); ?>
        <?php
        $fragments['.rbt-minicart-wrapper'] = ob_get_clean();
    } else {
        echo '<p class="woocommerce-mini-cart__empty-message">'.__( 'No products in the cart.', 'histudy' ).'</p>';
    }
    return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'rbt_cart_add_fragment', 10, 1);
function rbt_cart_add_subtotal( $fragments ) {
    if (!empty(WC()->cart->get_cart_contents_count())) {
        ob_start();
        if (function_exists('WC') && version_compare(WC()->version, '3.7.0', '<')) : ?>
            <hr class="mb--0">
                <div class="rbt-cart-subttotal">
                    <p class="subtotal"><strong><?php echo esc_html__("Subtotal:", "histudy") ?></strong></p>
                    <p class="price"><?php echo WC()->cart->get_cart_subtotal(); ?></p>
                </div>
            <?php else : ?>
                <div class="rbt-cart-subttotal">
                    <div class="subtotal">
                        <?php
                        /**
                         * Woocommerce_widget_shopping_cart_total hook.
                         *
                         * @hooked woocommerce_widget_shopping_cart_subtotal - 10
                         */
                        do_action('woocommerce_widget_shopping_cart_total');
                        ?>
                    </div>
                </div>
            <?php endif; ?>
        <hr class="mb--0">
        <div class="rbt-minicart-bottom mt--20">
            <?php do_action('woocommerce_widget_shopping_cart_before_buttons'); ?>
            <div class="woocommerce-mini-cart__buttons">
                <?php do_action('woocommerce_widget_shopping_cart_buttons'); ?>
            </div>
            <?php do_action('woocommerce_widget_shopping_cart_after_buttons'); ?>
        </div>
        <?php
        $fragments['.rbt-side-cart-subtotal-box'] = ob_get_clean();
        return $fragments;
    } ?>
    <?php
}
add_filter('woocommerce_add_to_cart_fragments', 'rbt_cart_add_subtotal', 10, 1);

/**
 * Ajax for product remove from cart
 */
add_action('wp_ajax_rbt_remove_prdouct_from_cart', 'rbt_remove_prdouct_from_cart');
add_action('wp_ajax_nopriv_rbt_remove_prdouct_from_cart', 'rbt_remove_prdouct_from_cart');
 if (!function_exists('rbt_remove_prdouct_from_cart')) {
    function rbt_remove_prdouct_from_cart()
    {
        $cart_item_key = isset($_REQUEST['cart_item_key']) ? wc_clean(wp_unslash($_REQUEST['cart_item_key'])) : '';
        WC()->cart->remove_cart_item($cart_item_key);
        echo __('card removed', 'histudy');
        wp_die();
    }
}
/**
 * Search results on ajax
 */
function rbt_ajax_search_tutor_courses() {
    $courseName = isset($_REQUEST['courseName']) ? sanitize_text_field( $_REQUEST['courseName'] ) : '';
    $postType = isset($_REQUEST['postType']) ? sanitize_text_field( $_REQUEST['postType'] ) : '';
    $args = array(
        'post_type'      => $postType,
        's'              => $courseName,
        'posts_per_page' => -1
    );

    $query = new WP_Query($args);

    ob_start(); // Start output buffering to capture HTML
    
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            echo '<div class="col-lg-3 col-md-4 col-sm-6 col-6">';
            
            get_template_part('template-parts/components/card/layout', 2);
            
            
            echo '</div>';
        }
    } else {
        echo '<div class="no-result-found">'.esc_html__("No results found.","histudy").'</div>';
    }
    
    wp_reset_postdata();
    
    $response = ob_get_clean(); // Get the captured HTML

    wp_send_json($response); // Return the HTML as AJAX response

    wp_die(); // Always call wp_die() after handling AJAX requests
}

// Hook the AJAX actions
add_action('wp_ajax_rbt_ajax_search_tutor_courses', 'rbt_ajax_search_tutor_courses');
add_action('wp_ajax_nopriv_rbt_ajax_search_tutor_courses', 'rbt_ajax_search_tutor_courses');


function event_query_vars_filter( $vars ){
    $vars[] = "event_layout";
    $vars[] = "sidebar_position";
    $vars[] = "course_layout";
    return $vars;
}

add_filter( 'query_vars', 'event_query_vars_filter' );

/**
 * Ajax for like functionality on blog post
 */

add_action( 'wp_ajax_update_single_post_like_meta', 'histudy_update_single_post_like_meta' );
add_action( 'wp_ajax_nopriv_update_single_post_like_meta', 'histudy_update_single_post_like_meta' );

/**
 * Create a ajax for update like
 * 
 * @since 1.0.0
 * 
 * @return void
*/
function histudy_update_single_post_like_meta() {
    // veriry nonce
    $nonce = isset($_POST['nonce']) ? sanitize_text_field($_POST['nonce']): '';
    if( !wp_verify_nonce( $nonce, 'histudy_like_post' ) ) {
        return wp_send_json_error(
            array(
                'message' => __( 'Sorry! nonce validation failed' , 'histudy' )
            )
        );
        exit;
    }
    $post_id = isset( $_POST['post_id'] ) ? absint($_POST['post_id']): '';
    if( !empty($post_id) ) {
        $meta_value = array_map( 'sanitize_text_field', get_post_meta( $post_id, 'histudy_post_like' ) );
        $meta_value = isset($meta_value[0]) ? absint($meta_value[0]): 0;
        $post_count_to_update = $meta_value + 1;
        update_post_meta( $post_id, 'histudy_post_like', $post_count_to_update );
        // successfully works
        return wp_send_json_success(
            array(
                'message' => __( 'Post updated successfully', 'histudy' ),
                'value' => $post_count_to_update
            )
        );
    }
    exit;
}



/**
 * Function to retrieve the current template name programmatically
 *
 * @return string The name of the current template (if available)
 *                 or an empty string if not found
 */
function get_current_template_name() {
    global $template;

    $custom_template = get_post_meta( get_queried_object_id(), '_wp_page_template', true );

    if ( $custom_template ) {
        $template_name = basename( $custom_template ); 
    } else {
      
        $template_name = basename( $template );
    }

    $template_name = str_replace( '.php', '', $template_name );

    return $template_name;
}




function is_product_in_cart($product_id) {
    if( !class_exists('WooCommerce') ) {
        return;
    }
    global $woocommerce;
    
    // Get cart contents
    $cart = $woocommerce->cart->get_cart();

    // Loop through cart items to check if the product ID exists
    foreach ($cart as $cart_item_key => $cart_item) {
        if ($cart_item['product_id'] == $product_id) {
            return true; // Product is in the cart
        }
    }

    return false; // Product is not in the cart
}


add_filter( 'get_the_archive_title_prefix', '__return_empty_string' );


function is_lp_course_wishlisted($course_id) {
    if( !class_exists( 'LearnPress' ) ) {
        return;
    }
   
    if (is_user_logged_in()) {
       
        $user_id = get_current_user_id();

        $wishlist = get_user_meta($user_id, '_lp_wishlist', true);

        if (is_array($wishlist) && in_array($course_id, $wishlist)) {
            return true; 
        }
    }

    return false; 
}

function is_course_in_wishlist($course_id) {
   
    if (!is_user_logged_in() && !class_exists('LearnPress') && !class_exists('LP_Addon_Wishlist_Preload')) {
        return false;
    }

    $user_id = get_current_user_id();

    $wishlist = get_user_meta($user_id, '_lp_wishlist', true);

    if (is_array($wishlist) && in_array($course_id, $wishlist)) {
        return true; 
    }

    return false; 
}



function custom_wc_login_redirect( $redirect, $user ) {
    $custom_redirect_url = 'https://example.com/custom-redirect-url';
    if ( ! empty( $custom_redirect_url ) ) {
        return $custom_redirect_url;
    }
    return $redirect;
}

add_filter( 'woocommerce_login_redirect', 'custom_wc_login_redirect', 10, 2 );


add_filter('woocommerce_return_to_shop_redirect', 'custom_return_to_courses_page');

function custom_return_to_courses_page($url) {
    $courses_page_url = get_permalink(get_page_by_path('courses'));

    if ($courses_page_url) {
        return $courses_page_url;
    }

    return $url;
}

add_action( 'woocommerce_thankyou', 'custom_empty_cart_after_checkout' );
function custom_empty_cart_after_checkout() {
    WC()->cart->empty_cart();
}

if(function_exists('academy_start' )) {
    require get_template_directory() . '/academy/custom/academy-hooks.php';
}


// Disable Yoast SEO output on the student registration page
add_action('template_redirect', function () {
    if ( is_singular() ) {
        global $post;
        if ( isset( $post->post_content ) && has_shortcode( $post->post_content, 'tutor_student_registration_form' ) ) {
            remove_all_actions('wpseo_head');
        }
    }
});
