<?php

/**
 * @author  Rainbow-Themes
 * @since   1.0
 * @version 1.0
 * @package histudy
 */

// No direct access, please.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Rainbow_Helper
{
    use rainbowMenuAreaTrait;
    use rainbowLayoutTrait;
    use rainbowPostMeta;
    use rainbowBannerTrait;
    use rainbowCourseCartTrait;
    use rainbowCourseDetailsTrait;
    use becomeInstructorTrait;
    use becomeStudent;
    use rainbowTutorCardTrait;
    use SingleProductAttributes;
    use rainbowOptionsTrait;
    use rainbowsocialTrait;
    use rainbowPageTitleTrait;
    use rainbowPaginationTrait;
    public function popup_login() {
        if ( ! is_user_logged_in() ) {
            rainbow_load_template( 'popup/popup-user' );
        }
    }
    public static function get_total_product_count() {
        if (class_exists('WooCommerce')) {
            $args = array(
                'limit' => -1,
                'return' => 'ids',
            );
    
            $products = wc_get_products($args);
    
            return count($products);
        } else {
            return 0;
        }
    }
    
    public static function rb_get_product_prices($product_id) {
        // Get the product object
        if( !class_exists('WooCommerce') ) {
            return;
        }
        $product = ( class_exists( 'WooCommerce' ) ) ? wc_get_product( $product_id ) : '';
    
        if ($product) {
            // Get the current price
            $current_price = $product->get_price();
            $regular_price = $product->get_regular_price();
            return array(
                'current_price' => $current_price,
                'regular_price' => $regular_price,
            );
        }
    
        // Return default values or handle the case where no product is found
        return array(
            'current_price' => '',
            'regular_price' => '',
        );
    }
    public static function rb_get_product_offer_percentage($product_id) {

        $course_id = get_the_ID();
        if( function_exists('tutor')) {
            if( !tutor_utils()->is_course_purchasable($course_id)) : 
                return 0;
            endif;
        }
        
        if( function_exists('tutor')) {
            $tutor_options = get_option('tutor_option');
            $monetize_by = isset($tutor_options['monetize_by']) ? $tutor_options['monetize_by'] : '';
            if( $monetize_by  == 'wc' &&  function_exists( 'tutor_pro' ) || $monetize_by  == 'tutor' && function_exists( 'tutor_pro' ) ) {
                $regular_price = get_post_meta( $product_id, 'tutor_course_price', true );
                $sale_price = get_post_meta( $product_id, 'tutor_course_sale_price', true );
            } else {
                $regular_price = get_post_meta($product_id, '_regular_price', true);
                $sale_price = get_post_meta($product_id, '_sale_price', true);
            }
        }elseif (  function_exists( 'academy_start' ) ) {

            $is_paid     = \Academy\Helper::is_course_purchasable( $product_id );
            // Check if WooCommerce is active and the course is purchasable
            if ( \Academy\Helper::is_active_woocommerce() && $is_paid ) {
                $product_id = \Academy\Helper::get_course_product_id( $product_id );
                if ( $product_id ) {
                    $product = wc_get_product( $product_id );
                    $sale_price = !empty($product->get_sale_price()) ? $product->get_sale_price() : 0;
                    $regular_price = $product->get_regular_price();
                    
                }
            }
        }
        else {
            if( class_exists( 'LearnPress' ) ) {
                $tutor_course = LP_Course::get_course($product_id);
                if ($tutor_course) {
                    $sale_price = !empty($tutor_course->get_sale_price()) ?  $tutor_course->get_sale_price(): 0;
                    $regular_price = $tutor_course->get_regular_price();
                }
            }
        }

        if (empty($regular_price) || empty($sale_price)) {
            return 0; // If there is no sale, return 0% discount.
        }
        
        $discount_percentage = (($regular_price - $sale_price) / $regular_price) * 100;
            
        return (int) round($discount_percentage, 2);

    }
    
    public static function rb_get_approved_comments( $id ){
        $comment_array = get_approved_comments( $id );
        $commentscount = count($comment_array);

        $comment = esc_html__("Comment", "histudy");
        $comments  = esc_html__("Comments", "histudy"); 

        if($commentscount == 1):
            $commenttext = $comment;  
        endif; 
        
        if($commentscount > 1 || $commentscount == 0):
            $commenttext = $comments; 
        endif;

        return $commentscount.' '.$commenttext;
    }
    public static function get_single_product_category($product_id = null) {
        if(!class_exists('WooCommerce') || empty($product_id)) {
            return;
        }
        global $product;
        $categories = get_the_terms($product_id, 'product_cat');
        if ($categories && !is_wp_error($categories)) {
            $category_links = array();
            foreach ($categories as $category) {
                $category_links[] = '<a href="' . esc_url(get_term_link($category)) . '">' . esc_html($category->name) . '</a>';
            }
            return implode(' ', $category_links);
        } 
    }
    /**
     * Display product categories and tags in a formatted manner.
     */
    public static function rbt_display_product_categories_and_tags($product_id = null) {
        if(!class_exists('WooCommerce') || empty($product_id)) {
            return;
        }
        global $product;
        $categories = get_the_terms($product_id, 'product_cat');
        $tags = get_the_terms($product_id, 'product_tag');
        if (($categories && !is_wp_error($categories)) || ($tags && !is_wp_error($tags))) {
            $term_links = array();
            if ($categories) {
                foreach ($categories as $category) {
                    $term_links[] = '<a href="' . esc_url(get_term_link($category)) . '">' . esc_html($category->name) . '</a>';
                }
            }
            if ($tags) {
                foreach ($tags as $tag) {
                    $term_links[] = '<a href="' . esc_url(get_term_link($tag)) . '">' . esc_html($tag->name) . '</a>';
                }
            }
            return implode(' ', $term_links);
        }
    }
    public static function rbt_display_product_tags($product_id = null) {
        if(!class_exists('WooCommerce') || empty($product_id)) {
            return;
        }
        global $product;
        $tags = get_the_terms($product_id, 'product_tag');
        $term_links = array();
        if ($tags) {
            foreach ($tags as $tag) {
                $term_links[] = '<a href="' . esc_url(get_term_link($tag)) . '">' . esc_html($tag->name) . '</a>';
            }
        }
        return implode(' ', $term_links);
    }
    public static function rbt_display_product_categories($product_id = null) {
        if(!class_exists('WooCommerce') || empty($product_id)) {
            return;
        }
        global $product;
        $categories = get_the_terms($product_id, 'product_cat');
        if (($categories && !is_wp_error($categories)) || ($categories && !is_wp_error($categories))) {
            $term_links = array();
            if ($categories) {
                foreach ($categories as $category) {
                    $term_links[] = '<a href="' . esc_url(get_term_link($category)) . '">' . esc_html($category->name) . '</a>';
                }
            }
            return implode(' ', $term_links);
        }
    }

    public static function rbt_get_woo_price_markup($layout='layout-1') {
        if(!class_exists('WooCommerce')) {
            return;
        }
        if('layout-1' == $layout) {
            get_template_part('template-parts/components/price/woocommerce/layout', '1');
        } else {
            get_template_part('template-parts/components/price/woocommerce/layout', '1');
        }
    }
    public static function get_all_articles()
    {
    if (is_home() || is_archive() || is_search() || is_404()) {
        $count_posts = wp_count_posts();
            if ( $count_posts ) { 
                ?>
                <a href="#" class="rbt-badge-2">
                    <div class="image">🎉</div> <?php echo esc_attr( $published_posts = $count_posts->publish ) ?> <?php echo esc_html__('Articles', 'histudy'); ?>
                </a> 
            <?php } ?> 
        <?php } ?> 
    <?php }
    public static function get_all_product_count()
    {
        if ( class_exists( 'WooCommerce' ) ) {
            // Get total product count
            $product_count = class_exists( 'WooCommerce' ) ? wc_get_products( array(
                'limit' => -1,
                'return' => 'ids',
            ) ): array();
            return count( $product_count );
            
        } else {
            // WooCommerce is not active
            echo __( 'WooCommerce is not installed or activated.', 'histudy' );
        }
    }

    public static function get_projects_cat_text($postID)
    {

        $terms = wp_get_post_terms($postID, "rainbow_projects_category", array('fields' => 'all'));
        if (!empty($terms)) {
            foreach ($terms as $index => $term) { ?>
                <?php echo esc_html($term->name); ?>
                <?php echo esc_html(self::generate_array_iterator_postfix($terms, $index, "|")) ?>
                <?php
            }
        }
        return;
    }

    public static function get_projects_cat($postID)
    {

        $terms = wp_get_post_terms($postID, "rainbow_projects_category", array('fields' => 'all'));
        if (!empty($terms)) {
            foreach ($terms as $index => $term) { ?>
                <a href="<?php echo get_category_link($term->term_id); ?>"><?php echo esc_html($term->name); ?></a>
                <?php echo esc_html(self::generate_array_iterator_postfix($terms, $index, "|")) ?>
                <?php
            }
        }
        return;
    }

    public static function generate_array_iterator_postfix($array, $index, $postfix = ', ')
    {
        $length = count($array);
        if ($length) {
            $last_index = $length - 1;
            return $index < $last_index ? $postfix : '';
        }
    }

    public static function wp_set_temp_query($query)
    {
        global $wp_query;
        $temp = $wp_query;
        $wp_query = $query;
        return $temp;
    }

    public static function wp_reset_temp_query($temp)
    {
        global $wp_query;
        $wp_query = $temp;
        wp_reset_postdata();
    }

    /**
     * Generate Excerpt
     */
    public static function generate_excerpt($post, $length = 55, $dot = false)
    {
        if (has_excerpt($post)) {
            $final_content = wp_trim_words(get_the_excerpt($post), $length, '');
        }

        $post = get_post($post);
        $content = wp_strip_all_tags($post->post_content);
        $final_content = wp_trim_words($content, $length, '');

        if ($dot) {
            $final_content = "$final_content $dot";
        }
        return $final_content;
    }

    /**
     * File Requires
     */
    public static function file_requires($filename, $dir = false)
    {
        if ($dir) {
            $child_file = get_stylesheet_directory() . '/' . $dir . '/' . $filename;

            if (file_exists($child_file)) {
                $file = $child_file;
            } else {
                $file = get_template_directory() . '/' . $dir . '/' . $filename;
            }
        } else {
            $child_file = get_stylesheet_directory() . '/inc/' . $filename;

            if (file_exists($child_file)) {
                $file = $child_file;
            } else {
                $file = RAINBOW_DIRECTORY . $filename;
            }
        }

        require_once $file;
    }

    /**
     * Get Images Form Assets img folder
     */
    
    public static function get_img($img)
    {
        $img = get_template_directory_uri() . '/assets/images/' . $img;
        return $img;
    }

    /**
     * Get CSS Form Assets CSS Folder
     */
    public static function get_css_($file)
    {
        $file = get_template_directory_uri() . '/assets/css/' . $file . '.css';
        return $file;
    }

    /**
     * Convert hex2rgb
     */
    public static function hex2rgb($hex)
    {
        $hex = str_replace("#", "", $hex);
        if (strlen($hex) == 3) {
            $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
            $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
            $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
        } else {
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
        }
        $rgb = "$r, $g, $b";
        return $rgb;
    }

    /**
     * filter_content
     *
     * @param $content
     * @return string
     */
    public static function filter_content($content)
    {
        // wp filters
        $content = wptexturize($content);
        $content = convert_smilies($content);
        $content = convert_chars($content);
        $content = wpautop($content);
        $content = shortcode_unautop($content);

        // remove shortcodes
        $pattern = '/\[(.+?)\]/';
        $content = preg_replace($pattern, '', $content);

        // remove tags
        $content = strip_tags($content);

        return $content;
    }

    public static function is_page($arg)
    {
        if (function_exists($arg) && call_user_func($arg)) {
            return true;
        }
        return false;
    }

    public static function maybe_rtl($filename)
    {
        if (is_rtl()) {
            $file = get_template_directory_uri() . '/assets/css-auto-rtl/' . $filename . '.css';
            return $file;
        } else {
            $file = get_template_directory_uri() . '/assets/css/' . $filename . '.css';
            return $file;
        }
    }

    public static function maybe_vendors_rtl($filename)
    {
        if (is_rtl()) {
            $file = get_template_directory_uri() . '/assets/css-auto-rtl/' . $filename . '.css';
            return $file;
        } else {
            $file = get_template_directory_uri() . '/assets/css/vendor/' . $filename . '.css';
            return $file;
        }
    }
    public static function get_admin_js($filename)
    {
        $path = '/assets/admin/js/' . $filename . '.js';
        return self::get_file_uri($path);
    }

    public static function get_admin_css($filename)
    {
        $path = '/assets/admin/css/' . $filename . '.css';
        return self::get_file_uri($path);
    }

    public static function get_js($filename)
    {
        $path = '/assets/js/' . $filename . '.js';
        return self::get_file_uri($path);
    }

    public static function get_rtl_js($filename)
    {
        $path = '/assets/js/rtl/' . $filename . '.js';
        return self::get_file_uri($path);
    }

    public static function get_css($filename)
    {
        $path = '/assets/css/' . $filename . '.css';
        return self::get_file_uri($path);
    }


    public static function get_vendor_js($filename)
    {
        $path = '/assets/js/vendor/' . $filename . '.js';
        return self::get_file_uri($path);
    }

    public static function get_plugins_css($filename)
    {
        $path = '/assets/css/plugins/' . $filename . '.css';
        return self::get_file_uri($path);
    }


    public static function get_vendor_css($filename)
    {
        $path = '/assets/css/vendor/' . $filename . '.css';
        return self::get_file_uri($path);
    }

    public static function get_rtl_css($filename)
    {
        $path = '/assets/css/rtl/' . $filename . '.css';
        return self::get_file_uri($path);
    }

    public static function get_vendor_assets($file)
    {
        $path = '/assets/vendor/' . $file;
        return self::get_file_uri($path);
    }


    public static function get_template_part($template, $args = array())
    {
        extract($args);

        $template = '/' . $template . '.php';

        if (file_exists(get_stylesheet_directory() . $template)) {
            $file = get_stylesheet_directory() . $template;
        } else {
            $file = get_template_directory() . $template;
        }

        require $file;
    }

    public static function get_template_content($template)
    {
        ob_start();
        get_template_part($template);
        return ob_get_clean();
    }


    private static function get_file_uri($path)
    {
        $filepath = get_stylesheet_directory() . $path;
        $file = get_stylesheet_directory_uri() . $path;
        if (!file_exists($filepath)) {
            $file = get_template_directory_uri() . $path;
        }
        return $file;
    }

}