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

include get_theme_file_path( 'vendor/wptrt/autoload/src/Estore_Woocommerce_Loader.php' );

$Estore_Woocommerce_Loader = new \WPTRT\Autoload\Estore_Woocommerce_Loader();

$Estore_Woocommerce_Loader->estore_woocommerce_add( 'WPTRT\\Customize\\Section', get_theme_file_path( 'vendor/wptrt/customize-section-button/src' ) );

$Estore_Woocommerce_Loader->estore_woocommerce_register();

if ( ! function_exists( 'estore_woocommerce_setup' ) ) :

	function estore_woocommerce_setup() {

		/*
		 * Enable support for Post Formats.
		 *
		 * See: https://codex.wordpress.org/Post_Formats
		*/
		add_theme_support( 'post-formats', array('image','video','gallery','audio',) );

		add_theme_support( 'woocommerce' );
		add_theme_support( "responsive-embeds" );
		add_theme_support( "align-wide" );
		add_theme_support( "wp-block-styles" );
		add_theme_support( 'automatic-feed-links' );
		add_theme_support( 'title-tag' );
		add_theme_support( 'post-thumbnails' );
        add_image_size('estore-woocommerce-featured-header-image', 2000, 660, true);

        register_nav_menus( array(
            'primary' => esc_html__( 'Primary','estore-woocommerce' ),
	        'footer'=> esc_html__( 'Footer Menu','estore-woocommerce' ),
        ) );

		add_theme_support( 'html5', array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
		) );

		add_theme_support( 'custom-background', apply_filters( 'estore_woocommerce_custom_background_args', array(
			'default-color' => 'f7ebe5',
			'default-image' => '',
		) ) );

		add_theme_support( 'customize-selective-refresh-widgets' );

		add_theme_support( 'custom-logo', array(
			'height'      => 50,
			'width'       => 50,
			'flex-width'  => true,
		) );

		add_editor_style( array( '/editor-style.css' ) );
		add_action('wp_ajax_estore_woocommerce_dismissable_notice', 'estore_woocommerce_dismissable_notice');
		add_action( 'wp_ajax_tm-check-plugin-exists', 'tm_check_plugin_exists' );
		add_action( 'wp_ajax_tm_install_and_activate_plugin', 'tm_install_and_activate_plugin' );
	}
endif;
add_action( 'after_setup_theme', 'estore_woocommerce_setup' );

function tm_install_and_activate_plugin() {
	check_ajax_referer( 'theme_importer_nonce' );
	if ( ! current_user_can( 'install_plugins' ) ) {
		wp_send_json_error( 'Permission denied.' );
		return;
	}

	$post_plugin_details = $_POST['plugin_details'];
	$plugin_text_domain = $post_plugin_details['plugin_text_domain'];
	$plugin_main_file		=	$post_plugin_details['plugin_main_file'];
	$plugin_url					=	$post_plugin_details['plugin_url'];

	$plugin = array(
		'text_domain'	=> $plugin_text_domain,
		'path' 				=> $plugin_url,
		'install' 		=> $plugin_text_domain . '/' . $plugin_main_file
	);

	wp_cache_flush();

	$plugin_path = plugin_basename( trim( $plugin['install'] ) );


	$activate_plugin = activate_plugin( $plugin_path );

	if($activate_plugin) {

		echo $activate_plugin;

	} else {
		echo $activate_plugin;
	}

	$msg = 'installed';

	$response = array( 'status' => true, 'msg' => $msg );
	wp_send_json( $response );
	exit;
}

function tm_check_plugin_exists() {
	check_ajax_referer( 'theme_importer_nonce' );
	if ( ! current_user_can( 'install_plugins' ) ) {
		wp_send_json_error( 'Permission denied.' );
		return;
	}
		$plugin_text_domain = $_POST['plugin_text_domain'];
		$main_plugin_file 	= $_POST['main_plugin_file'];
		$plugin_path = $plugin_text_domain . '/' . $main_plugin_file;

		$get_plugins					= get_plugins();
		$is_plugin_installed	= false;
		$activation_status 		= false;
		if ( isset( $get_plugins[$plugin_path] ) ) {
		$is_plugin_installed = true;

		$activation_status = is_plugin_active( $plugin_path );
		}
		wp_send_json_success(
		array(
		'install_status'  =>	$is_plugin_installed,
			'active_status'		=>	$activation_status,
			'plugin_path'			=>	$plugin_path,
			'plugin_slug'			=>	$plugin_text_domain
		)
		);
}

if ( ! function_exists( 'estore_woocommerce_file_setup' ) ) :

	function estore_woocommerce_file_setup() {

		if ( ! defined( 'ESTORE_WOOCOMMERCE_CONTACT_SUPPORT' ) ) {

			define( 'FREE_MNSSP_API_URL', 'https://license.themagnifico.net/api/general/' );

			define('ESTORE_WOOCOMMERCE_CONTACT_SUPPORT',__('https://wordpress.org/support/theme/estore-woocommerce/','estore-woocommerce'));
		}
		if ( ! defined( 'ESTORE_WOOCOMMERCE_REVIEW' ) ) {
			define('ESTORE_WOOCOMMERCE_REVIEW',__('https://wordpress.org/support/theme/estore-woocommerce/reviews/','estore-woocommerce'));
		}
		if ( ! defined( 'ESTORE_WOOCOMMERCE_LIVE_DEMO' ) ) {
			define('ESTORE_WOOCOMMERCE_LIVE_DEMO',__('https://demo.themagnifico.net/woocommerce-estore/','estore-woocommerce'));
		}
		if ( ! defined( 'ESTORE_WOOCOMMERCE_GET_PREMIUM_PRO' ) ) {
			define('ESTORE_WOOCOMMERCE_GET_PREMIUM_PRO',__('https://www.themagnifico.net/products/estore-wordpress-theme','estore-woocommerce'));
		}
		if ( ! defined( 'ESTORE_WOOCOMMERCE_PRO_DOC' ) ) {
			define('ESTORE_WOOCOMMERCE_PRO_DOC',__('https://demo.themagnifico.net/eard/wathiqa/woocommerce-estore-doc/','estore-woocommerce'));
		}
		if ( ! defined( 'ESTORE_WOOCOMMERCE_FREE_DOC' ) ) {
			define('ESTORE_WOOCOMMERCE_FREE_DOC',__('https://demo.themagnifico.net/eard/wathiqa/woocommerce-estore-free-doc/','estore-woocommerce'));
		}
		if ( ! defined( 'ESTORE_WOOCOMMERCE_BUNDLE_LINK' ) ) {
			define('ESTORE_WOOCOMMERCE_BUNDLE_LINK',__('https://www.themagnifico.net/products/wordpress-theme-bundle','estore-woocommerce'));
		}

		load_theme_textdomain( 'estore-woocommerce', get_template_directory() . '/languages' );

		require_once get_theme_file_path( 'inc/wptt-webfont-loader.php' );

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

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

		/**
		 * Customizer additions.
		 */
		require get_template_directory() . '/inc/customizer.php';

		/**
		 * Customizer additions.
		 */
		require get_template_directory() . '/inc/tgm.php';

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


function estore_woocommerce_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'estore_woocommerce_content_width', 1170 );
}
add_action( 'after_setup_theme', 'estore_woocommerce_content_width', 0 );

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

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function estore_woocommerce_widgets_init() {
	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar', 'estore-woocommerce' ),
		'id'            => 'sidebar',
		'description'   => esc_html__( 'Add widgets here.', 'estore-woocommerce' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h5 class="widget-title">',
		'after_title'   => '</h5>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar 1', 'estore-woocommerce' ),
		'id'            => 'sidebar1',
		'description'   => esc_html__( 'Add widgets here.', 'estore-woocommerce' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h5 class="widget-title">',
		'after_title'   => '</h5>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar 2', 'estore-woocommerce' ),
		'id'            => 'sidebar2',
		'description'   => esc_html__( 'Add widgets here.', 'estore-woocommerce' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h5 class="widget-title">',
		'after_title'   => '</h5>',
	) );


	register_sidebar( array(
		'name'          => esc_html__( 'Woocommerce Single Product Page Sidebar', 'estore-woocommerce' ),
		'id'            => 'woocommerce-single-product-page-sidebar',
		'description'   => '',
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h5 class="widget-title">',
		'after_title'   => '</h5>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Woocommerce Shop Page Sidebar', 'estore-woocommerce' ),
		'id'            => 'woocommerce-shop-page-sidebar',
		'description'   => '',
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h5 class="widget-title">',
		'after_title'   => '</h5>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Footer Column 1', 'estore-woocommerce' ),
		'id'            => 'estore-woocommerce-footer1',
		'description'   => '',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h5 class="footer-column-widget-title">',
		'after_title'   => '</h5>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Footer Column 2', 'estore-woocommerce' ),
		'id'            => 'estore-woocommerce-footer2',
		'description'   => '',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h5 class="footer-column-widget-title">',
		'after_title'   => '</h5>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Footer Column 3', 'estore-woocommerce' ),
		'id'            => 'estore-woocommerce-footer3',
		'description'   => '',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h5 class="footer-column-widget-title">',
		'after_title'   => '</h5>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Footer Column 4', 'estore-woocommerce' ),
		'id'            => 'estore-woocommerce-footer4',
		'description'   => '',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h5 class="footer-column-widget-title">',
		'after_title'   => '</h5>',
	) );
}
add_action( 'widgets_init', 'estore_woocommerce_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function estore_woocommerce_scripts() {

	wp_enqueue_style(
		'montserrat',
		wptt_get_webfont_url( 'https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap' ),
		array(),
		'1.0'
	);

	wp_enqueue_style( 'estore-woocommerce-block-editor-style', get_theme_file_uri('/assets/css/block-editor-style.css') );

	// load bootstrap css
    wp_enqueue_style( 'bootstrap-css', get_template_directory_uri() . '/assets/css/bootstrap.css');

    wp_enqueue_style( 'owl.carousel-css', get_template_directory_uri() . '/assets/css/owl.carousel.css');

	wp_enqueue_style( 'estore-woocommerce-style', get_stylesheet_uri() );
	require get_parent_theme_file_path( '/custom-option.php' );
	wp_add_inline_style( 'estore-woocommerce-style',$estore_woocommerce_theme_css );

	wp_style_add_data('estore-woocommerce-basic-style', 'rtl', 'replace');

	// fontawesome
	wp_enqueue_style( 'fontawesome-style', get_template_directory_uri() .'/assets/css/fontawesome/css/all.css' );

    wp_enqueue_script('estore-woocommerce-theme-js', get_template_directory_uri() . '/assets/js/theme-script.js', array('jquery'), '', true );

    wp_enqueue_script('owl.carousel-js', get_template_directory_uri() . '/assets/js/owl.carousel.js', array('jquery'), '', true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'estore_woocommerce_scripts' );

/**
 * Enqueue Preloader.
 */
function estore_woocommerce_preloader() {

  $estore_woocommerce_theme_color_css = '';
  $estore_woocommerce_preloader_bg_color = get_theme_mod('estore_woocommerce_preloader_bg_color');
  $estore_woocommerce_preloader_dot_1_color = get_theme_mod('estore_woocommerce_preloader_dot_1_color');
  $estore_woocommerce_preloader_dot_2_color = get_theme_mod('estore_woocommerce_preloader_dot_2_color');
  $estore_woocommerce_preloader2_dot_color = get_theme_mod('estore_woocommerce_preloader2_dot_color');
  $estore_woocommerce_logo_max_height = get_theme_mod('estore_woocommerce_logo_max_height');
  $estore_woocommerce_related_product_display_setting = get_theme_mod('estore_woocommerce_related_product_display_setting', true);

  	if(get_theme_mod('estore_woocommerce_logo_max_height') == '') {
		$estore_woocommerce_logo_max_height = '24';
	}

	if(get_theme_mod('estore_woocommerce_preloader_dot_1_color') == '') {
		$estore_woocommerce_preloader_dot_1_color = 'var(--first-color)';
	}
	if(get_theme_mod('estore_woocommerce_preloader_dot_2_color') == '') {
		$estore_woocommerce_preloader_dot_2_color = '#151515';
	}

	// Start CSS build
	$estore_woocommerce_theme_color_css = '';

	
	if (!$estore_woocommerce_related_product_display_setting) {
	    $estore_woocommerce_theme_color_css .= '
	        .related.products,
	        .related h2 {
	            display: none !important;
	        }
	    ';
	}

	$estore_woocommerce_theme_color_css .= '
		.custom-logo-link img{
			max-height: '.esc_attr($estore_woocommerce_logo_max_height).'px;
	 	}
		.loading, .loading2{
			background-color: '.esc_attr($estore_woocommerce_preloader_bg_color).';
		 }
		 @keyframes loading {
		  0%,
		  100% {
		  	transform: translatey(-2.5rem);
		    background-color: '.esc_attr($estore_woocommerce_preloader_dot_1_color).';
		  }
		  50% {
		  	transform: translatey(2.5rem);
		    background-color: '.esc_attr($estore_woocommerce_preloader_dot_2_color).';
		  }
		}
		.load hr {
			background-color: '.esc_attr($estore_woocommerce_preloader2_dot_color).';
		}
	';
    wp_add_inline_style( 'estore-woocommerce-style',$estore_woocommerce_theme_color_css );

}
add_action( 'wp_enqueue_scripts', 'estore_woocommerce_preloader' );

/** * Posts pagination. */
if ( ! function_exists( 'estore_woocommerce_blog_posts_pagination' ) ) {
	function estore_woocommerce_blog_posts_pagination() {
		$pagination_type = get_theme_mod( 'estore_woocommerce_blog_pagination_type', 'blog-nav-numbers' );
		if ( $pagination_type == 'blog-nav-numbers' ) {
			the_posts_pagination();
		} else {
			the_posts_navigation();
		}
	}
}

if ( class_exists( 'WP_Customize_Control' ) ) {
	// Image Toggle Radio Buttpon
	class Estore_Woocommerce_Image_Radio_Control extends WP_Customize_Control {

	    public function render_content() {
	 
	        if (empty($this->choices))
	            return;
	 
	        $name = '_customize-radio-' . $this->id;
	        ?>
	        <span class="customize-control-title"><?php echo esc_html($this->label); ?></span>
	        <ul class="controls" id='estore-woocommerce-img-container'>
	            <?php
	            foreach ($this->choices as $value => $label) :
	                $class = ($this->value() == $value) ? 'estore-woocommerce-radio-img-selected estore-woocommerce-radio-img-img' : 'estore-woocommerce-radio-img-img';
	                ?>
	                <li style="display: inline;">
	                    <label>
	                        <input <?php $this->link(); ?>style = 'display:none' type="radio" value="<?php echo esc_attr($value); ?>" name="<?php echo esc_attr($name); ?>" <?php
	                          	$this->link();
	                          	checked($this->value(), $value);
	                          	?> />
	                        <img src='<?php echo esc_url($label); ?>' class='<?php echo esc_attr($class); ?>' />
	                    </label>
	                </li>
	                <?php
	            endforeach;
	            ?>
	        </ul>
	        <?php
	    } 
	}
}

function estore_woocommerce_sanitize_select( $input, $setting ){
    $input = sanitize_key($input);
    $choices = $setting->manager->get_control( $setting->id )->choices;
    return ( array_key_exists( $input, $choices ) ? $input : $setting->default );
}

function estore_woocommerce_preloader1(){
	if(get_theme_mod('estore_woocommerce_preloader_type', 'Preloader 1') == 'Preloader 1' ) {
		return true;
	}
	return false;
}

function estore_woocommerce_preloader2(){
	if(get_theme_mod('estore_woocommerce_preloader_type', 'Preloader 1') == 'Preloader 2' ) {
		return true;
	}
	return false;
}

/*dropdown page sanitization*/
function estore_woocommerce_sanitize_dropdown_pages( $page_id, $setting ) {
	$page_id = absint( $page_id );
	return ( 'publish' == get_post_status( $page_id ) ? $page_id : $setting->default );
}

function estore_woocommerce_sanitize_checkbox( $input ) {
  // Boolean check
  return ( ( isset( $input ) && true == $input ) ? true : false );
}

// Filter to change the number of related products displayed
add_filter( 'woocommerce_output_related_products_args', 'estore_woocommerce_products_args' );
function estore_woocommerce_products_args( $args ) {
    $args['posts_per_page'] = get_theme_mod( 'custom_related_products_number', 6 );
    $args['columns'] = get_theme_mod( 'custom_related_products_number_per_row', 3 );
    return $args;
}

function estore_woocommerce_get_page_id_by_title($estore_woocommerce_pagename){

    $args = array(
        'post_type' => 'page',
        'posts_per_page' => 1,
        'post_status' => 'publish',
        'title' => $estore_woocommerce_pagename
    );
    $query = new WP_Query( $args );

    $page_id = '1';
    if (isset($query->post->ID)) {
        $page_id = $query->post->ID;
    }

    return $page_id;
}


/*radio button sanitization*/
function estore_woocommerce_sanitize_choices( $input, $setting ) {
    global $wp_customize;
    $control = $wp_customize->get_control( $setting->id );
    if ( array_key_exists( $input, $control->choices ) ) {
        return $input;
    } else {
        return $setting->default;
    }
}

function estore_woocommerce_sanitize_number_absint( $number, $setting ) {
	// Ensure $number is an absolute integer (whole number, zero or greater).
	$number = absint( $number );

	// If the input is an absolute integer, return it; otherwise, return the default
	return ( $number ? $number : $setting->default );
}

function estore_woocommerce_sanitize_number_range( $number, $setting ) {
	
	// Ensure input is an absolute integer.
	$number = absint( $number );
	
	// Get the input attributes associated with the setting.
	$atts = $setting->manager->get_control( $setting->id )->input_attrs;
	
	// Get minimum number in the range.
	$min = ( isset( $atts['min'] ) ? $atts['min'] : $number );
	
	// Get maximum number in the range.
	$max = ( isset( $atts['max'] ) ? $atts['max'] : $number );
	
	// Get step.
	$step = ( isset( $atts['step'] ) ? $atts['step'] : 1 );
	
	// If the number is within the valid range, return it; otherwise, return the default
	return ( $min <= $number && $number <= $max && is_int( $number / $step ) ? $number : $setting->default );
}

// Change number or products per row to 3
add_filter('loop_shop_columns', 'estore_woocommerce_loop_columns');
if (!function_exists('estore_woocommerce_loop_columns')) {
	function estore_woocommerce_loop_columns() {
		$columns = get_theme_mod( 'estore_woocommerce_products_per_row', 3 );
		return $columns; // 3 products per row
	}
}

add_filter( 'woocommerce_sale_flash', 'estore_woocommerce_woocommerce_sale_flash_percentage', 10, 3 );

function estore_woocommerce_woocommerce_sale_flash_percentage( $html, $post, $product ) {

	$found = preg_match( '#(<span.*?>)(.*?)(</span>)#', $html, $matches );

	if ( ! $found ) {
		return $html;
	}

	$tag_open      = $matches[1];
	$tag_close     = $matches[3];
	$original_text = $matches[2];

	$percentages = estore_woocommerce_woocommerce_get_product_sale_percentages( $product );
	$label       = estore_woocommerce_woocommerce_get_product_sale_percentage_label( $percentages, $original_text );

	$html = $tag_open . $label . $tag_close;

	return $html;
}

function estore_woocommerce_woocommerce_get_product_sale_percentages( $product ) {
	$percentages = array(
		'min' => false,
		'max' => false,
	);

	switch ( $product->get_type() ) {
		case 'grouped':
			$children = array_filter( array_map( 'wc_get_product', $product->get_children() ), 'wc_products_array_filter_visible_grouped' );

			foreach ( $children as $child ) {
				if ( $child->is_purchasable() && ! $child->is_type( 'grouped' ) && $child->is_on_sale() ) {
					$child_percentage = estore_woocommerce_woocommerce_get_product_sale_percentages( $child );

					$percentages['min'] = false !== $percentages['min'] ? $percentages['min'] : $child_percentage['min'];
					$percentages['max'] = false !== $percentages['max'] ? $percentages['max'] : $child_percentage['max'];

					if ( $child_percentage['min'] < $percentages['min'] ) {
						$percentages['min'] = $child_percentage['min'];
					}

					if ( $child_percentage['max'] > $percentages['max'] ) {
						$percentages['max'] = $child_percentage['max'];
					}
				}
			}

			break;

		case 'variable':
			$prices = $product->get_variation_prices();

			foreach ( $prices['price'] as $variation_id => $price ) {
				$regular_price = (float) $prices['regular_price'][ $variation_id ];
				$sale_price    = (float) $prices['sale_price'][ $variation_id ];

				if ( $sale_price < $regular_price ) {
					$variation_percentage = ( ( $regular_price - $sale_price ) / $regular_price ) * 100;

					$percentages['min'] = false !== $percentages['min'] ? $percentages['min'] : $variation_percentage;
					$percentages['max'] = false !== $percentages['max'] ? $percentages['max'] : $variation_percentage;

					if ( $variation_percentage < $percentages['min'] ) {
						$percentages['min'] = $variation_percentage;
					}

					if ( $variation_percentage > $percentages['max'] ) {
						$percentages['max'] = $variation_percentage;
					}
				}
			}
			break;

		case 'external':
		case 'variation':
		case 'simple':
		default:
			$regular_price = (float) $product->get_regular_price();
			$sale_price    = (float) $product->get_sale_price();

			if ( $sale_price < $regular_price ) {
				$percentages['max'] = ( ( $regular_price - $sale_price ) / $regular_price ) * 100;
			}
	}
	return $percentages;
}

function estore_woocommerce_woocommerce_get_product_sale_percentage_label( $percentages, $original_label ) {
	$label = '';

	$rounded_percentages = $percentages;
	$rounded_percentages = array_map( 'round', $percentages );
	$rounded_percentages = array_map( 'intval', $rounded_percentages );

	if ( ( empty( $percentages['min'] ) || empty( $percentages['max'] ) ) || ( $percentages['min'] === $percentages['max'] ) ) {
		$label = sprintf( _x( '-%1$d%%', 'product discount', 'estore-woocommerce' ), max( $rounded_percentages ) );
	} else {
		$label = sprintf( _x( '-%1$d%% / -%2$d%%', 'product discount', 'estore-woocommerce' ), $rounded_percentages['min'], $rounded_percentages['max'] );
	}

	$label = apply_filters( 'estore_woocommerce_woocommerce_sale_flash_percentage_label', $label, $rounded_percentages, $percentages, $original_label );

	return $label;
}

function estore_woocommerce_getpage_css($hook) {
	wp_register_script( 'admin-notice-script', get_template_directory_uri() . '/inc/admin/js/admin-notice-script.js', array( 'jquery' ) );
    wp_localize_script('admin-notice-script','estore_woocommerce',
		array('admin_ajax'	=>	admin_url('admin-ajax.php'),'wpnonce'  =>	wp_create_nonce('estore_woocommerce_dismissed_notice_nonce')
		)
	);
	wp_enqueue_script('admin-notice-script');

    wp_localize_script( 'admin-notice-script', 'estore_woocommerce_ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
    );
	if ( 'appearance_page_estore-woocommerce-info' != $hook ) {
		return;
	}
	wp_enqueue_style( 'estore-woocommerce-demo-style', get_template_directory_uri() . '/assets/css/demo.css' );
}
add_action( 'admin_enqueue_scripts', 'estore_woocommerce_getpage_css' );

//Admin Notice For Getstart
function estore_woocommerce_ajax_notice_handler() {
    check_ajax_referer( 'estore_woocommerce_dismissed_notice_nonce', 'wpnonce' );
    if ( isset( $_POST['type'] ) ) {
        $type = sanitize_text_field( wp_unslash( $_POST['type'] ) );
        update_option( 'dismissed-' . $type, TRUE );
    }
    wp_die();
}
add_action( 'wp_ajax_estore_woocommerce_ajax_notice_handler', 'estore_woocommerce_ajax_notice_handler' );

function estore_woocommerce_deprecated_hook_admin_notice() {

    $dismissed = get_user_meta(get_current_user_id(), 'estore_woocommerce_dismissable_notice', true);
    if ( !$dismissed) { ?>
        <div class="updated notice notice-success is-dismissible notice-get-started-class" data-notice="get_started" style="background: #f7f9f9; padding: 20px 10px; display: flex;">
	    	<div class="tm-admin-image">
	    		<img style="width: 100%;max-width: 320px;line-height: 40px;display: inline-block;vertical-align: top;border: 2px solid #ddd;border-radius: 4px;" src="<?php echo esc_url(get_stylesheet_directory_uri()) .'/screenshot.png'; ?>" />
	    	</div>
	    	<div class="tm-admin-content" style="padding-left: 30px; align-self: center">
	    		<h2 style="font-weight: 600;line-height: 1.3; margin: 0px;"><?php esc_html_e('Thank You For Choosing ', 'estore-woocommerce'); ?><?php echo esc_html( wp_get_theme() ); ?></h2>
	    		<p style="color: #3c434a; font-weight: 400; margin-bottom: 30px;"><?php esc_html_e('Get Started With Theme By Clicking On Getting Started.', 'estore-woocommerce'); ?></p>
	        	<a class="admin-notice-btn button button-primary button-hero" href="<?php echo esc_url( admin_url( 'themes.php?page=estore-woocommerce-info' )); ?>"><?php esc_html_e( 'Get started', 'estore-woocommerce' ) ?></a>
	        	<a class="admin-notice-btn button button-primary button-hero notice-pro-btn" target="_blank" href="<?php echo esc_url( ESTORE_WOOCOMMERCE_GET_PREMIUM_PRO ); ?>"><?php esc_html_e( 'Get Premium ', 'estore-woocommerce' ) ?></a>
	        	<a class="admin-notice-btn button button-primary button-hero notice-bundle-btn" target="_blank" href="<?php echo esc_url( ESTORE_WOOCOMMERCE_BUNDLE_LINK ); ?>"><?php esc_html_e( 'Buy All Themes - 130+ Templates', 'estore-woocommerce' ) ?></a>
	        	<span style="padding-top: 15px; display: inline-block; padding-left: 8px;">
	        	<span style="padding-top: 15px; display: inline-block; padding-left: 8px;">
	        	<a class="admin-notice-btn"	 target="_blank" href="<?php echo esc_url( ESTORE_WOOCOMMERCE_LIVE_DEMO ); ?>"><?php esc_html_e( 'View Demo', 'estore-woocommerce' ) ?></a>
	        	</span>
	    	</div>
        </div>
    <?php }
}

add_action( 'admin_notices', 'estore_woocommerce_deprecated_hook_admin_notice' );

function estore_woocommerce_switch_theme() {
    delete_user_meta(get_current_user_id(), 'estore_woocommerce_dismissable_notice');
}
add_action('after_switch_theme', 'estore_woocommerce_switch_theme');
function estore_woocommerce_dismissable_notice() {
    check_ajax_referer( 'estore_woocommerce_dismissed_notice_nonce', 'wpnonce' );
    update_user_meta(get_current_user_id(), 'estore_woocommerce_dismissable_notice', true);
    wp_die();
}

// Demo Content Code start //

// Ensure WordPress is loaded
if (!defined('ABSPATH')) {
    exit;
}


// Add the AJAX action to trigger theme mods import
add_action('wp_ajax_import_theme_mods', 'estore_woocommerce_demo_importer_ajax_handler');

// Handle the AJAX request
function estore_woocommerce_demo_importer_ajax_handler() {
    check_ajax_referer( 'theme_importer_nonce' );
    if ( ! current_user_can( 'edit_theme_options' ) ) {
        wp_send_json_error( 'Permission denied.' );
        return;
    }
    // Sample data to import
    $theme_mods_data = array(
        'header_textcolor' => '000000',  // Example: change header text color
        'background_color' => 'ffffff',  // Example: change background color
        'custom_logo'      => 123,       // Example: set a custom logo by attachment ID
        'footer_text'      => 'Custom Footer Text', // Example: custom footer text
    );

    // Call the function to import theme mods
    if (estore_woocommerce_demo_theme_importer($theme_mods_data)) {
        // After importing theme mods, create the menu
        estore_woocommerce_create_demo_menu();
        wp_send_json_success(array(
        	'msg' => 'Theme mods and widgets imported successfully.',
        	'redirect' => home_url()
        ));
    } else {
        wp_send_json_error('Failed to import theme mods.');
    }

    wp_die();
}

// Function to set theme mods
function estore_woocommerce_demo_theme_importer($import_data) {
    if (is_array($import_data)) {
        foreach ($import_data as $mod_name => $mod_value) {
            set_theme_mod($mod_name, $mod_value);
        }
        return true;
    } else {
        return false;
    }
}

// Function to create demo menu
function estore_woocommerce_create_demo_menu() {

    $menu_structure = [

        [
            'title' => 'Home',
            'slug'  => 'home',
            'template' => 'page-template/home-template.php',
        ],
        [
            'title' => 'About',
            'slug'  => 'about',
            'content' => "
                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>
            "
        ],
        [
            'title' => 'Shop',
            'slug'  => 'shop',
        ],
        [
            'title' => 'Pages',
            'slug'  => 'pages',
           
        ],
        
        
        [
            'title' => 'Contact',
            'slug'  => 'contact',
        ],
    ];

    // ----------------------------------------------------
    // Do not modify below this line unless needed
    // ----------------------------------------------------

    $created_pages = [];

    $menu_name = 'Primary Menu';
    $location  = 'primary';
    $menu = wp_get_nav_menu_object($menu_name);

    $menu_id = (!$menu) ? wp_create_nav_menu($menu_name) : $menu->term_id;

    $create_page_and_menu = function($item, $parent_menu_id = 0, $parent_page_id = 0) 
        use (&$create_page_and_menu, &$created_pages, $menu_id) {

        $pages = get_posts( array(
            'title'          => $item['title'],
            'post_type'      => 'page',
            'post_status'    => 'any',
            'posts_per_page' => 1,
            'orderby'        => 'post_date',
            'order'          => 'ASC',
        ) );
        $page = ! empty( $pages ) ? $pages[0] : null;

        if (!$page) {
            $page_id = wp_insert_post([
                'post_title'   => $item['title'],
                'post_type'    => 'page',
                'post_status'  => 'publish',
                'post_name'    => $item['slug'],
                'post_parent'  => $parent_page_id,
                'post_content' => !empty($item['content']) ? $item['content'] : '',
            ]);

            if (!empty($item['template'])) {
                update_post_meta($page_id, '_wp_page_template', $item['template']);
            }

        } else {
            $page_id = $page->ID;
        }

        $created_pages[$item['title']] = $page_id;

        $menu_item_id = wp_update_nav_menu_item($menu_id, 0, [
            'menu-item-title'     => $item['title'],
            'menu-item-object'    => 'page',
            'menu-item-object-id' => $page_id,
            'menu-item-type'      => 'post_type',
            'menu-item-parent-id' => $parent_menu_id,
            'menu-item-status'    => 'publish'
        ]);

        if (!empty($item['children'])) {
            foreach ($item['children'] as $child) {
                $create_page_and_menu($child, $menu_item_id, $page_id);
            }
        }
    };

    foreach ($menu_structure as $item) {
        $create_page_and_menu($item);
    }

    if (!empty($created_pages['Home'])) {
        update_option('page_on_front', $created_pages['Home']);
        update_option('show_on_front', 'page');
    }

    if (!empty($created_pages['Blog'])) {
        update_option('page_for_posts', $created_pages['Blog']);
    }

    $locations = get_theme_mod('nav_menu_locations');
    $locations[$location] = $menu_id;
    set_theme_mod('nav_menu_locations', $locations);

    // topbar
    set_theme_mod( 'estore_woocommerce_topbar_phone_text', 'Telephone Enquiry :' );
    set_theme_mod( 'estore_woocommerce_topbar_phone_number', '123456789' );
    set_theme_mod( 'estore_woocommerce_topbar_checkout_button', 'Checkout' );
    set_theme_mod( 'estore_woocommerce_topbar_about_url', '#' );
    set_theme_mod( 'estore_woocommerce_topbar_order_button', 'Track Your Order' );
    set_theme_mod( 'estore_woocommerce_topbar_order_url', '#' );
    set_theme_mod( 'estore_woocommerce_topbar1_wishlist_url', '#' );
    set_theme_mod( 'estore_woocommerce_header_location_button', 'Update Your Location' );
    set_theme_mod( 'estore_woocommerce_header_locaion_url', '#' );

    //Slider
    set_theme_mod( 'estore_woocommerce_slider_button_text', 'Shop Collection' );

   	for($i=1;$i<=4;$i++){
         $title = 'Your Product Title';
         $content = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,';
            // Create post object
         $my_post = array(
         'post_title'    => wp_strip_all_tags( $title ),
         'post_content'  => $content,
         'post_status'   => 'publish',
         'post_type'     => 'page',
         );

         // Insert the post into the database
         $post_id = wp_insert_post( $my_post );

         if ($post_id) {
	        // Set the theme mod for the slider page
	        set_theme_mod('estore_woocommerce_top_slider_page' . $i, $post_id);

	        $image_url = get_template_directory_uri().'/assets/image/slider.png';

			$image_id = media_sideload_image($image_url, $post_id, null, 'id');

		        if (!is_wp_error($image_id)) {
		            // Set the downloaded image as the post's featured image
		            set_post_thumbnail($post_id, $image_id);
		        }
      	}
    }

    //About Us
    set_theme_mod( 'estore_woocommerce_best_sells_section_heading', 'Best Selling Products' );
    set_theme_mod( 'estore_woocommerce_best_sells_section_button', 'View All Products' );
    set_theme_mod( 'estore_woocommerce_best_sells_section_button_url', '#' );

	set_theme_mod('estore_woocommerce_cate_tab', 'productcat1');

    // Define product category names and product titles
    $estore_woocommerce_procategory_names = array('productcat1');
    $estore_woocommerce_protitle_array = array(
        array("Product Full Title Here", "Product Full Title Here", "Product Full Title Here", "Product Full Title Here"),

    );

    foreach ($estore_woocommerce_procategory_names as $estore_woocommerce_index => $estore_woocommerce_category_name) {
        // Create or retrieve the product category term ID
        $estore_woocommerce_term = term_exists($estore_woocommerce_category_name, 'product_cat');
        if ($estore_woocommerce_term === 0 || $estore_woocommerce_term === null) {
            // If the term does not exist, create it
            $estore_woocommerce_term = wp_insert_term($estore_woocommerce_category_name, 'product_cat');
        }

        if (is_wp_error($estore_woocommerce_term)) {
            error_log('Error creating category: ' . $estore_woocommerce_term->get_error_message());
            continue; // Skip to the next iteration if category creation fails
        }

        // Loop to create 4 products for each category
        for ($estore_woocommerce_i = 0; $estore_woocommerce_i < 4; $estore_woocommerce_i++) {
            // Create product content
            $estore_woocommerce_title = $estore_woocommerce_protitle_array[$estore_woocommerce_index][$estore_woocommerce_i];
            $estore_woocommerce_content = 'Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s.';

            // Create product post object
            $estore_woocommerce_my_post = array(
                'post_title'    => wp_strip_all_tags($estore_woocommerce_title),
                'post_content'  => $estore_woocommerce_content,
                'post_status'   => 'publish',
                'post_type'     => 'product', // Post type set to 'product'
            );

            // Insert the product into the database
            $estore_woocommerce_post_id = wp_insert_post($estore_woocommerce_my_post);

            if (is_wp_error($estore_woocommerce_post_id)) {
                error_log('Error creating product: ' . $estore_woocommerce_post_id->get_error_message());
                continue; // Skip to the next product if creation fails
            }

            // Assign the category to the product
            wp_set_object_terms($estore_woocommerce_post_id, (int)$estore_woocommerce_term['term_id'], 'product_cat');

            // Add product meta (price, etc.)
            update_post_meta($estore_woocommerce_post_id, '_regular_price', '95'); // Regular price
            update_post_meta($estore_woocommerce_post_id, '_sale_price', '87.00'); // Sale price
            update_post_meta($estore_woocommerce_post_id, '_price', '87.00'); // Active price

            // Handle the featured image using media_sideload_image
            $estore_woocommerce_image_url = get_template_directory_uri() . '/assets/image/product' . ($estore_woocommerce_i + 1) . '.png';
            $estore_woocommerce_image_id = media_sideload_image($estore_woocommerce_image_url, $estore_woocommerce_post_id, null, 'id');

            if (is_wp_error($estore_woocommerce_image_id)) {
                error_log('Error downloading image: ' . $estore_woocommerce_image_id->get_error_message());
                continue; // Skip to the next product if image download fails
            }

            // Assign featured image to product
            set_post_thumbnail($estore_woocommerce_post_id, $estore_woocommerce_image_id);

        }
    }


}

// Enqueue necessary scripts
add_action('admin_enqueue_scripts', 'demo_importer_enqueue_scripts');

function demo_importer_enqueue_scripts() {
    wp_enqueue_script(
        'demo-theme-importer',
        get_template_directory_uri() . '/assets/js/theme-importer.js', // Path to your JS file
        array('jquery'),
        null,
        true
    );

    wp_enqueue_style('demo-importer-style', get_template_directory_uri() . '/assets/css/importer.css', array(), '');

    // Localize script to pass AJAX URL to JS
    wp_localize_script(
        'demo-theme-importer',
        'demoImporter',
        array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('theme_importer_nonce')
        )
    );
}

/**
 * Theme Info.
 */
function estore_woocommerce_theme_info_load() {
	require get_theme_file_path( '/inc/theme-installation/theme-installation.php' );
}
add_action( 'init', 'estore_woocommerce_theme_info_load' );


// Getstart Function

function free_mnssp_get_filtered_products($cursor = '', $search = '', $collection = 'pro') {
    $endpoint_url = FREE_MNSSP_API_URL . 'getFilteredProducts';

    $remote_post_data = array(
        'collectionHandle' => $collection,
        'productHandle' => $search,
        'paginationParams' => array(
            "first" => 12,
            "afterCursor" => $cursor,
            "beforeCursor" => "",
            "reverse" => true
        )
    );

    $body = wp_json_encode($remote_post_data);

    $options = [
        'body' => $body,
        'headers' => [
            'Content-Type' => 'application/json'
        ]
    ];
    $response = wp_remote_post($endpoint_url, $options);

    if (!is_wp_error($response)) {
        $response_body = wp_remote_retrieve_body($response);
        $response_body = json_decode($response_body);

        if (isset($response_body->data) && !empty($response_body->data)) {
            if (isset($response_body->data->products) && !empty($response_body->data->products)) {
                return  array(
                    'products' => $response_body->data->products,
                    'pagination' => $response_body->data->pageInfo
                );
            }
        }
        return [];
    }
    
    return [];
}

function free_mnssp_get_filtered_products_ajax() {
    $cursor = isset($_POST['cursor']) ? sanitize_text_field(wp_unslash($_POST['cursor'])) : '';
    $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
    $collection = isset($_POST['collection']) ? sanitize_text_field(wp_unslash($_POST['collection'])) : 'pro';

    check_ajax_referer('free_mnssp_create_pagination_nonce_action', 'mnssp_pagination_nonce');

    $get_filtered_products = free_mnssp_get_filtered_products($cursor, $search, $collection);
    ob_start();
    if (isset($get_filtered_products['products']) && !empty($get_filtered_products['products'])) {
        foreach ( $get_filtered_products['products'] as $product ) {

            $product_obj = $product->node;
            
            if (isset($product_obj->inCollection) && !$product_obj->inCollection) {
                continue;
            }

            $product_obj = $product->node;

            $demo_url = isset($product->node->metafield->value) ? $product->node->metafield->value : '';
            $product_url = isset($product->node->onlineStoreUrl) ? $product->node->onlineStoreUrl : '';
            $image_src = isset($product->node->images->edges[0]->node->src) ? $product->node->images->edges[0]->node->src : '';
            $price = isset($product->node->variants->edges[0]->node->price) ? '$' . $product->node->variants->edges[0]->node->price : ''; ?>

            <div class="mnssp-grid-item">
                <div class="mnssp-image-wrap">
                    <img src="<?php echo esc_url($image_src); ?>" alt="<?php echo esc_attr($product_obj->title); ?>">
                    <div class="mnssp-image-overlay">
                        <a class="mnssp-demo-url mnssp-btn" href="<?php echo esc_attr($demo_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html('Demo'); ?></a>
                        <a class="mnssp-buy-now mnssp-btn" href="<?php echo esc_attr($product_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html('Buy Now'); ?></a>
                    </div>
                </div>
                <footer>
                    <h3><?php echo esc_html($product_obj->title); ?></h3>
                </footer>
                <div class="mnssp-grid-item-price">Price: <?php echo esc_html($price); ?></div>
            </div>
        <?php }
    }
    $output = ob_get_clean();

    $pagination = isset($get_filtered_products['pagination']) ?  $get_filtered_products['pagination'] : [];
    wp_send_json(array(
        'content' => $output,
        'pagination' => $pagination
    ));
}

add_action('wp_ajax_free_mnssp_get_filtered_products', 'free_mnssp_get_filtered_products_ajax');
add_action('wp_ajax_nopriv_free_mnssp_get_filtered_products', 'free_mnssp_get_filtered_products_ajax');

function free_mnssp_get_collections() {
    
    $endpoint_url = FREE_MNSSP_API_URL . 'getCollections';

    $options = [
        'body' => [],
        'headers' => [
            'Content-Type' => 'application/json'
        ]
    ];
    $response = wp_remote_post($endpoint_url, $options);

    if (!is_wp_error($response)) {
        $response_body = wp_remote_retrieve_body($response);
        $response_body = json_decode($response_body);

        if (isset($response_body->data) && !empty($response_body->data)) {
           return  $response_body->data;
        }
        return  [];
    }

    return  [];
}