<?php
/**
 * hostiko functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package hostiko
 */
 
/**
 * Define Const for theme Dir
 * @since 1.0.0
 * */
define('HOSTIKO_ROOT_PATH',get_template_directory());
define('HOSTIKO_ROOT_URL',get_template_directory_uri());
define('HOSTIKO_CSS',HOSTIKO_ROOT_URL .'/assets/css');
define('HOSTIKO_JS',HOSTIKO_ROOT_URL .'/assets/js');
define('HOSTIKO_IMG',HOSTIKO_ROOT_URL .'/assets/img');
define('HOSTIKO_INC',HOSTIKO_ROOT_PATH .'/inc');
define('HOSTIKO_THEME_STYLESHEETS',HOSTIKO_INC .'/theme-stylesheets');

/**
 * define theme info
 * @since 1.0.0
 * */
if (is_child_theme()){
	$theme = wp_get_theme();
	$parent_theme = $theme->Template;
	$theme_info = wp_get_theme($parent_theme);
}else{
	$theme_info = wp_get_theme();
}
define('HOSTIKO_DEV_MODE',true);
$gazania_version = HOSTIKO_DEV_MODE ? time() : $theme_info->get('Version');
define('HOSTIKO_NAME',$theme_info->get('Name'));
define('HOSTIKO_VERSION',$gazania_version);
define('HOSTIKO_AUTHOR',$theme_info->get('Author'));
define('HOSTIKO_AUTHOR_URI',$theme_info->get('AuthorURI'));

require_once(__DIR__ . '/welcome.php');

/*
 * include template helper function
 * @since 1.0.0
 * */
if (file_exists(HOSTIKO_INC.'/template-functions.php') && HOSTIKO_INC.'/template-tags.php'){
	require_once  HOSTIKO_INC.'/template-functions.php';
	require_once  HOSTIKO_INC.'/template-tags.php';

	function Hostiko_Function($instance){
		$new_instance = false;
		switch ($instance){
			case ("Functions"):
				$new_instance = class_exists('Hostiko_Functions') ? Hostiko_Functions::getInstance() : false;
				break;
			case ("Tags"):
				$new_instance = class_exists('Hostiko_Tags') ? Hostiko_Tags::getInstance() : false;
				break;
			default:
				 $new_instance = false;
			break;
		}

		return $new_instance;
	}
}


/*
* Include theme init file
* @since 1.0.0
*/
if ( file_exists(HOSTIKO_INC.'/class-hostiko-init.php' ) ) {
	require_once  HOSTIKO_INC.'/class-hostiko-init.php';
}

if ( file_exists(HOSTIKO_INC.'/plugins/tgma/activate.php') ) {
	require_once  HOSTIKO_INC.'/plugins/tgma/activate.php';
}		

/**
 * Custom template helper function for this theme.
 */
require_once HOSTIKO_INC . '/template-helper.php';
require_once HOSTIKO_INC . '/hostiko_customizer.php';
require_once HOSTIKO_INC . '/hostiko_customizer_data.php';
require_once HOSTIKO_INC . '/wc-hostiko-functions.php';
require_once HOSTIKO_INC . '/wc-hostiko-template-hooks.php';

// Move comments textarea to bottom
function gazania_move_comment_field_to_bottom( $fields ) {
	$comment_field = $fields['comment'];
	unset( $fields['comment'] );
	$fields['comment'] = $comment_field;
	return $fields;
}
add_filter( 'comment_form_fields', 'gazania_move_comment_field_to_bottom' );

/**
 * Nav menu fallback function
 * @since 1.0.0
 */
 function hostiko_primary_menu_fallback()
{
    get_template_part('template-parts/default', 'menu');
}


function hostiko_block_editor_styles() {
	wp_enqueue_style( 'block-editor-bootstrap', get_theme_file_uri( 'assets/css/block-editor.bootstrap.css' ), array(), null );
	wp_enqueue_style( 'block-editor-theme', get_theme_file_uri( 'assets/css/block-editor.theme.css' ), array(), null );
}
add_action( 'enqueue_block_editor_assets', 'hostiko_block_editor_styles', 1, 1 );

/**
* admin js
**/
add_action('admin_enqueue_scripts', 'hostiko_admin_custom_scripts');
function hostiko_admin_custom_scripts(){
	wp_enqueue_media();
	wp_register_script('hostiko-admin-custom', get_template_directory_uri().'/inc/js/admin_custom.js', array('jquery'), '', true);
	wp_enqueue_script('hostiko-admin-custom');
}

/**
* shortcode supports for removing extra p, spance etc
*
*/
add_filter( 'the_content', 'hostiko_shortcode_extra_content_remove' );
/**
 * Filters the content to remove any extra paragraph or break tags
 * caused by shortcodes.
 *
 * @since 1.0.0
 *
 * @param string $content  String of HTML content.
 * @return string $content Amended string of HTML content.
 */
function hostiko_shortcode_extra_content_remove( $content ) {

    $array = array(
        '<p>['    => '[',
        ']</p>'   => ']',
        ']<br />' => ']'
    );
    return strtr( $content, $array );
}


/**
 * Nav menu fallback function
 * @since 1.0.0
 */
 function hostiko_theme_fallback_menu()
{
    get_template_part('template-parts/default', 'menu');
}


/**
 * Hostiko CSS Include
 */
function enqueue_our_required_stylesheet(){
	wp_enqueue_style('load-fa-pro', get_template_directory_uri(). '/assets/fonts/fontawesome-pro-v5.css');
	wp_enqueue_style('load-fa', get_template_directory_uri(). '/assets/fonts/fontawesome-v6.css');
	wp_enqueue_style('roboto-font', get_template_directory_uri() . '/assets/fonts/roboto.css' );
	wp_enqueue_style('hostiko-owl-carousel', get_template_directory_uri() . '/assets/css/owl.carousel.min.css' );
	wp_enqueue_style('popups', get_template_directory_uri() . '/assets/css/magnific-popup.css' );
	wp_enqueue_style('hostiko-style-css', get_template_directory_uri() . '/assets/css/hostiko-custom.css' );
	
}
add_action( 'wp_enqueue_scripts', 'enqueue_our_required_stylesheet' );

/**
 * Hostiko CSS Include In Footer
 */
function add_css_in_footer() {
	$rtl_class = get_body_class();
	if(in_array('rtl', $rtl_class)) {
		?>
<link rel='stylesheet' href='<?php echo esc_url( get_template_directory_uri() . '/assets/css/style-rtl.css' ); ?>' type='text/css' media="all"/>

<?php
	}

}

function enqueue_theme_styles() { 
	wp_register_style( 'header-style', HOSTIKO_CSS . '/style.css', array(), time(), 'all' ); 
	wp_register_style( 'responsive', HOSTIKO_CSS . '/responsive.css', array(), time(), 'all' ); 
	
	wp_enqueue_style( 'header-style' ); 
	wp_enqueue_style( 'responsive' ); 
	} 
	add_action( 'wp_enqueue_scripts', 'enqueue_theme_styles' );

	/**
	 * Framwork redux
	*/
	require_once (get_template_directory() . '/inc/options/function.options.php');



/**
 * Hostiko JS Include
 */
function enqueue_load_js() {
	wp_enqueue_script( 'jquery.cycle.all', get_template_directory_uri() . '/assets/js/jquery.cycle.all.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'jquery.slicknav', get_template_directory_uri() . '/assets/js/jquery.slicknav.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'slider', get_template_directory_uri() . '/assets/js/slider.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'custom.min', get_template_directory_uri() . '/assets/js/jquery-ui-1.9.2.custom.min.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'effects.core', get_template_directory_uri() . '/assets/js/jquery.effects.core.min.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'touch-punch', get_template_directory_uri() . '/assets/js/jquery.ui.touch-punch.min.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'scripts', get_template_directory_uri() . '/assets/js/scripts.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'owl_crousel1', get_template_directory_uri() . '/assets/js/owl.carousel.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'owl_crousel_min', get_template_directory_uri() . '/assets/js/owl.carousel.min.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/assets/js/custom.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'video-popup-js', get_template_directory_uri() . '/assets/js/video-popup.js', array( 'jquery' ), '', true );
	wp_enqueue_script( 'video-section-js', get_template_directory_uri() . '/assets/js/video-section.js', array( 'jquery' ), '', true );
	wp_localize_script( 'custom', 'HostikoAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),'HOME_URL'=> home_url() ));  
}
add_action( 'wp_enqueue_scripts', 'enqueue_load_js' );

	  
/**
 * Function For Elementor Global Colors after import.
 */
add_action('akd_elementor_global', 'hostiko_elementor_global_setup');
function hostiko_elementor_global_setup()
{
    $hostiko_elementor_kit = apply_filters('hostiko_elementor_global', false);
    if ($hostiko_elementor_kit)
    {
        esc_attr($hostiko_elementor_kit);
    }
}

/**
 * Get Elementor Template list
 */
function hostiko_get_elementor_templates()
{
    $args = array(
        'post_type' => 'elementor_library',
        'post_status' => 'publish',
		'posts_per_page' => -1,

    );
    $hostiko_the_query = new WP_Query($args);
    $hostiko_elementor_posts = array();
    if ($hostiko_the_query->have_posts()):
        foreach ($hostiko_the_query->posts as $hostiko_post):
            $hostiko_elementor_posts[$hostiko_post->ID] = apply_filters('the_title', get_the_title($hostiko_post));
        endforeach;
    endif;
    return $hostiko_elementor_posts;
}

// Add support for featured image
add_theme_support( 'post-thumbnails' );

add_filter('loop_shop_per_page', 'custom_products_per_page');

function custom_products_per_page() {
    return 9; // Adjust this number to the desired products per page
}

// Add product title in Woocoomerce single product
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
function woocommerce_template_single_title_custom()
{
    the_title( '<h3 class="product_title entry-title">',' </h3>' );
}
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title_custom', 5);


/**
 * Get Elementor Template list
*/

function hostiko_get_elementor_header_templates()
{	
	$args = array(
		'post_type' => 'elementor_library',
		'posts_per_page' => -1,
		'tax_query' => array(
			array(
				'taxonomy' => 'elementor_library_category',
				'field' => 'slug',
				'terms' => 'header',
			),
		),
	);
	
	$query = new WP_Query( $args );
	$hostiko_header_templates = array();
	if ( $query->have_posts() ) {
		foreach ($query->posts as $hostiko_post):
            $hostiko_header_templates[$hostiko_post->ID] = apply_filters('the_title', get_the_title($hostiko_post));
        endforeach;
	}
	return $hostiko_header_templates;	
}

// Preloader Customizer Section
function add_preloader_customizer_section( $wp_customize ) {
    $wp_customize->add_section( 'preloader_section', array(
        'title' => __( 'Preloader', 'hostiko' ),
        'priority' => 30,
    ) );

    $wp_customize->add_setting( 'show_preloader', array(
        'default' => true,
        'sanitize_callback' => 'wp_validate_boolean',
    ) );

    $wp_customize->add_control( 'show_preloader', array(
        'type' => 'checkbox',
        'label' => __( 'Show Preloader', 'hostiko' ),
        'section' => 'preloader_section',
    ) );
}
add_action( 'customize_register', 'add_preloader_customizer_section' );

//Banner Hide/Show Option
add_action( 'elementor/element/wp-page/document_settings/after_section_end', function( $element, $args ) {
	$element->start_controls_section(
		'section_page_settings',
		[
			'label' => __( 'Banner Settings', 'hostiko' ),
			'tab' => \Elementor\Controls_Manager::TAB_SETTINGS,
		]
	);
	$element->add_control(
		'banner_display',
		[
			'label' => __( 'Hide Banner', 'hostiko' ),
			'type' => \Elementor\Controls_Manager::SWITCHER,
			'default' => 'Show',
			'label_on' => __( 'Hide', 'hostiko' ),
			'label_off' => __( 'Show', 'hostiko' ),
		]
	);
	$element->end_controls_section();
}, 10, 2 );




// // Function to get options for the Elementor templates dropdown
function get_elementor_template_options() {
    $templates = get_posts( [
        'post_type'      => 'elementor_library',
        'posts_per_page' => -1,
    ] );
    $options = [];
    foreach ( $templates as $template ) {
        $options[ $template->ID ] = $template->post_title;
    }
    return $options;
}

add_action( 'elementor/element/wp-page/document_settings/after_section_end', 'add_elementor_template_dropdown', 10, 2 );
function add_elementor_template_dropdown( $element, $args ) {
	$hostiko_footer_e = get_theme_mod('choose_elementor_footer');
	$element->start_controls_section(
		'page_footer_settings',
		[
			'label' => __( 'Footer Settings', 'hostiko' ),
			'tab' => \Elementor\Controls_Manager::TAB_SETTINGS,
		]
	);
	$element->add_control(
		'page_footer_display',
		[
			'label' => __( 'Show footers', 'hostiko' ),
			'type' => \Elementor\Controls_Manager::SWITCHER,
			'default' => '',
			'label_on' => __( 'Show', 'hostiko' ),
			'label_off' => __( 'Hide', 'hostiko' ),
		]
	);
	
	$element->add_control(
		'choose_elementor_page_footer',
		[
			'label' => __( 'Show footers', 'hostiko' ),
			'type' => \Elementor\Controls_Manager::SELECT,
			'options' => get_elementor_template_options(),
			'transport'	=> 'refresh',
			'required' => ['footer_source_type',
							'=',
							'e'],
			'default' => $hostiko_footer_e,
			'condition' => [
				'page_footer_display' => 'yes',
			]
		]
	);
	$element->end_controls_section();
}


function update_akd_theme_colors_option() {
	// Retrieve the existing options array
	$akd_options = get_option( 'akd-framework-admin-page' );

	// Check if the options array exists
	if ( $akd_options ) {
		// Get the active kit ID for Elementor
		$active_kit_id = get_option( 'elementor_active_kit' );
		
		// Get the Elementor global colors from the active kit's page settings
		$elementor_data = get_post_meta( $active_kit_id, '_elementor_page_settings', true );

		// Ensure we have the global colors data under 'system_colors'
		if ( isset( $elementor_data['system_colors'] ) && is_array( $elementor_data['system_colors'] ) ) {
			// Initialize color defaults if not set
			$color_defaults = [
				'primary'   => '#000000',
				'secondary' => '#FFFFFF',
				'text'      => '#333333',
				'accent'    => '#FF5733',
			];

			// Map each color in 'system_colors' to the akd-theme-colors array, using defaults if not found
			foreach ( $elementor_data['system_colors'] as $color ) {
				if ( isset( $color['_id'], $color['color'] ) ) {
					switch ( $color['_id'] ) {
						case 'primary':
							$akd_options['akd-theme-colors']['primary'] = $color['color'] ?? $color_defaults['primary'];
							break;
						case 'secondary':
							$akd_options['akd-theme-colors']['secondary'] = $color['color'] ?? $color_defaults['secondary'];
							break;
						case 'text':
							$akd_options['akd-theme-colors']['text'] = $color['color'] ?? $color_defaults['text'];
							break;
						case 'accent':
							$akd_options['akd-theme-colors']['accent'] = $color['color'] ?? $color_defaults['accent'];
							break;
					}
				}
			}

			// Process custom colors if available
			if ( isset( $elementor_data['custom_colors'] ) && is_array( $elementor_data['custom_colors'] ) ) {
				// Map each custom color from Elementor's 'custom_colors' to the akd-theme-colors array with the 'custom-color-{id}' format
				foreach ( $elementor_data['custom_colors'] as $color ) {
					if ( isset( $color['title'], $color['color'] ) ) {
						$custom_color_key = 'custom-color-' . $color['_id']; // Create the key using the custom color ID
	
						// Save the custom color in the format 'custom-color-{id}' 
						$akd_options['akd-custom-colors'][$custom_color_key] = $color['color'];
					}
				}
			}

			// Check for typography settings under 'system_typography'
			if (isset($elementor_data['system_typography']) && is_array($elementor_data['system_typography'])) {
				$typography_defaults = [
					'akd-primary-typography'         => 'Gulzar',
					'akd-primary-font-weight'        => '400',
					'akd-primary-font-size'          => '36',
					'akd-primary-text-transform'     => 'uppercase',
				
					'akd-secondary-typography'       => 'Indie Flower',
					'akd-secondary-font-weight'      => '200',
					'akd-secondary-font-size'        => '34',
					'akd-secondary-text-transform'   => 'capitalize',
				
					'akd-text-typography'            => 'Inria Serif',
					'akd-text-font-weight'           => '800',
					'akd-text-font-size'             => '30',
					'akd-text-text-transform'        => 'none',
				
					'akd-accent-typography'          => 'Jockey One',
					'akd-accent-font-weight'         => '400',
					'akd-accent-font-size'           => '26',
					'akd-accent-text-transform'      => 'inherit',
				
					'akd-c20c515-typography'         => 'Hind',
					'akd-c20c515-font-weight'        => '500',
					'akd-c20c515-font-size'          => '80',
					'akd-c20c515-text-transform'     => 'none',
				
					'akd-ca0c7c3-typography'         => 'Inknut Antiqua',
					'akd-ca0c7c3-font-weight'        => '600',
					'akd-ca0c7c3-font-size'          => '34',
					'akd-ca0c7c3-text-transform'     => 'capitalize',
				];
				// Map each typography in 'system_typography' to the akd-theme-typography array, using defaults if not found
				foreach ( $elementor_data['system_typography'] as $typo ) {
					if ( isset( $typo['_id'], $typo['typography_font_family'] ) ) {
						switch ( $typo['_id'] ) {
							case 'primary':
								$akd_options['akd-primary-typography']         = $typo['typography_font_family'] ?? $typography_defaults['akd-primary-typography'];
								$akd_options['akd-primary-font-weight']        = $typo['typography_font_weight'] ?? $typography_defaults['akd-primary-font-weight'];
								$akd_options['akd-primary-font-size']          = $typo['typography_font_size']['size'] ?? $typography_defaults['akd-primary-font-size'];
								$akd_options['akd-primary-text-transform']     = $typo['typography_text_transform'] ?? $typography_defaults['akd-primary-text-transform'];
								break;
							case 'secondary':
								$akd_options['akd-secondary-typography']       = $typo['typography_font_family'] ?? $typography_defaults['akd-secondary-typography'];
								$akd_options['akd-secondary-font-weight']      = $typo['typography_font_weight'] ?? $typography_defaults['akd-secondary-font-weight'];
								$akd_options['akd-secondary-font-size']        = $typo['typography_font_size']['size'] ?? $typography_defaults['akd-secondary-font-size'];
								$akd_options['akd-secondary-text-transform']   = $typo['typography_text_transform'] ?? $typography_defaults['akd-secondary-text-transform'];
								break;
							case 'text':
								$akd_options['akd-text-typography']            = $typo['typography_font_family'] ?? $typography_defaults['akd-text-typography'];
								$akd_options['akd-text-font-weight']           = $typo['typography_font_weight'] ?? $typography_defaults['akd-text-font-weight'];
								$akd_options['akd-text-font-size']             = $typo['typography_font_size']['size'] ?? $typography_defaults['akd-text-font-size'];
								$akd_options['akd-text-text-transform']        = $typo['typography_text_transform'] ?? $typography_defaults['akd-text-text-transform'];
								break;
							case 'accent':
								$akd_options['akd-accent-typography']          = $typo['typography_font_family'] ?? $typography_defaults['akd-accent-typography'];
								$akd_options['akd-accent-font-weight']         = $typo['typography_font_weight'] ?? $typography_defaults['akd-accent-font-weight'];
								$akd_options['akd-accent-font-size']           = $typo['typography_font_size']['size'] ?? $typography_defaults['akd-accent-font-size'];
								$akd_options['akd-accent-text-transform']      = $typo['typography_text_transform'] ?? $typography_defaults['akd-accent-text-transform'];
								break;
							default:
								// For custom typography settings
								$custom_typo_key = 'akd-' . $typo['_id'];
								$akd_options[ $custom_typo_key . '-typography' ]               = $typo['typography_font_family'] ?? $typography_defaults[ $custom_typo_key . '-typography' ] ?? '';
								$akd_options[ $custom_typo_key . '-font-weight']  = $typo['typography_font_weight'] ?? $typography_defaults[ $custom_typo_key . '-font-weight' ] ?? '';
								$akd_options[ $custom_typo_key . '-font-size']    = $typo['typography_font_size']['size'] ?? $typography_defaults[ $custom_typo_key . '-font-size' ] ?? '';
								$akd_options[ $custom_typo_key . '-text-transform'] = $typo['typography_text_transform'] ?? $typography_defaults[ $custom_typo_key . '-text-transform' ] ?? '';
								break;
						}
					}
				}

				// Map each typography in 'custom_typography' to the akd-theme-typography array, using defaults if not found
				foreach ( $elementor_data['custom_typography'] as $typo ) {
					if ( isset( $typo['_id'], $typo['typography_font_family'] ) ) {
						// For custom typography settings
						$custom_typo_key = 'akd-' . $typo['_id'];
						$akd_options[ $custom_typo_key . '-typography' ]     = $typo['typography_font_family'] ?? $typography_defaults[ $custom_typo_key . '-typography' ] ?? '';
						$akd_options[ $custom_typo_key . '-font-weight']     = $typo['typography_font_weight'] ?? $typography_defaults[ $custom_typo_key . '-font-weight' ] ?? '';
						$akd_options[ $custom_typo_key . '-font-size']       = $typo['typography_font_size']['size'] ?? $typography_defaults[ $custom_typo_key . '-font-size' ] ?? '';
						$akd_options[ $custom_typo_key . '-text-transform']  = $typo['typography_text_transform'] ?? $typography_defaults[ $custom_typo_key . '-text-transform' ] ?? '';
					}
				}
			}

			// Save the updated options back to the database
			update_option( 'akd-framework-admin-page', $akd_options );
		}
	}
}
add_action( 'elementor/editor/after_save', 'update_akd_theme_colors_option', 10, 2 );

function hostiko_theme_setup() {
    // Enable WordPress features
    add_theme_support( 'title-tag' );          // Modern title handling
    add_theme_support( 'wp-block-styles' );    // Default Gutenberg block styles
    add_theme_support( 'align-wide' );         // Wide & full alignment for blocks
    add_theme_support( 'responsive-embeds' );  // Responsive embeds for videos
    add_theme_support( 'post-thumbnails' );    // Featured images
    add_theme_support( 'custom-logo' );        // Optional: logo support

    // Register a custom block style for buttons
    if ( function_exists( 'register_block_style' ) ) {
        register_block_style(
            'core/button',
            array(
                'name'  => 'hostiko-outline',
                'label' => __( 'Outline', 'hostiko' ),
            )
        );
    }

    // Register custom block patterns
    if ( function_exists( 'register_block_pattern' ) ) {
        register_block_pattern(
            'hostiko/hero-section',
            array(
                'title'       => __( 'Hero Section', 'hostiko' ),
                'description' => __( 'A simple hero section with heading and button.', 'hostiko' ),
                'content'     => '<!-- wp:heading --><h2>Hello World</h2><!-- /wp:heading -->',
            )
        );
    }
}
add_action( 'after_setup_theme', 'hostiko_theme_setup' );

