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

if ( ! function_exists( 'code_manas_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 code_manas_setup() {
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 * If you're building a theme based on Code Manas, use a find and replace
		 * to change 'code-manas' to the name of your theme in all the template files.
		 */
		load_theme_textdomain( 'code-manas', get_theme_file_path( '/languages' ) );

		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

		/*
		 * Let WordPress manage the document title.
		 * By adding theme support, we declare that this theme does not use a
		 * hard-coded <title> tag in the document head, and expect WordPress to
		 * provide it for us.
		 */
		add_theme_support( 'title-tag' );

		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support( 'post-thumbnails' );

		// This theme uses wp_nav_menu() in one location.
		register_nav_menus( array(
			'menu-1' => esc_html__( 'Primary', 'code-manas' ),
			'menu-2' => esc_html__( 'Secondary', 'code-manas' ),
			'menu-3' => esc_html__( 'Social', 'code-manas' ),
		) );

		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support( 'html5', array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
		) );

		// Set up the WordPress core custom background feature.
		add_theme_support( 'custom-background', apply_filters( 'code_manas_custom_background_args', array(
			'default-color' => 'ffffff',
			'default-image' => '',
		) ) );

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

		/**
		 * Add support for core custom logo.
		 *
		 * @link https://codex.wordpress.org/Theme_Logo
		 */
		add_theme_support( 'custom-logo', array(
			'height'      => 250,
			'width'       => 250,
			'flex-width'  => true,
			'flex-height' => true,
		) );

		if( code_manas_is_woo_active() ) {
			add_theme_support( 'woocommerce' );
			add_theme_support( 'wc-product-gallery-zoom' );
			add_theme_support( 'wc-product-gallery-lightbox' );
			add_theme_support( 'wc-product-gallery-slider' );
		}
	}
endif;
add_action( 'after_setup_theme', 'code_manas_setup' );

/**
 * 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 code_manas_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( 'code_manas_content_width', 640 );
}

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

/**
 * Register custom fonts.
 */
function code_manas_fonts_url() {
	$fonts_url     = '';
	$font_families = array();

	/* translators: If there are characters in your language that are not supported by Merriweather, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Oxygen font: on or off', 'code-manas' ) ) {
		$font_families[] = 'Oxygen: 400bold,400regular';
	}

	/* translators: If there are characters in your language that are not supported by Montserrat, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'PlayfairDisplay font: on or off', 'code-manas' ) ) {
		$font_families[] = 'Playfair Display: bold,regular';
	}

	if ( $font_families ) {
		$fonts_url = add_query_arg(
			array(
				'family' => urlencode( implode( '|', $font_families ) ),
				'subset' => urlencode( 'latin,latin-ext' ),
			), 'https://fonts.googleapis.com/css'
		);
	}

	return esc_url_raw( $fonts_url );
}

/**
 * Add preconnect for Google Fonts.
 *
 * @since Code Manas 1.0
 *
 * @param array  $urls          URLs to print for resource hints.
 * @param string $relation_type The relation type the URLs are printed.
 *
 * @return array $urls           URLs to print for resource hints.
 */
function code_manas_resource_hints( $urls, $relation_type ) {
	if ( wp_style_is( 'code_manas-fonts', 'queue' ) && 'preconnect' === $relation_type ) {
		$urls[] = array(
			'href' => 'https://fonts.gstatic.com',
			'crossorigin',
		);
	}

	return $urls;
}

add_filter( 'wp_resource_hints', 'code_manas_resource_hints', 10, 2 );

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

	register_sidebars( 4, array(
		// translators: Replace %d with each count.
		'name'          => esc_html__( 'Footer %d', 'code-manas' ),
		'description'   => esc_html__( 'Add footer widgets here.', 'code-manas' ),
		'before_widget' => '<aside id="%1$s" class="widget footer-menu">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );
}

add_action( 'widgets_init', 'code_manas_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function code_manas_scripts() {
	$ver        = wp_get_theme()->get( 'Version' );
	$assets_url = get_theme_file_uri( '/assets/' );

	wp_enqueue_style( 'code-manas-fonts', code_manas_fonts_url(), array(), null );
	wp_enqueue_style( 'code-manas-woocommerce', $assets_url . 'css/woocommerce.css', array( 'woocommerce-layout', 'woocommerce-general', 'code-manas-style' ), $ver );
	wp_enqueue_style( 'code-manas-style', get_stylesheet_uri(), '', $ver );

	// Theme block stylesheet.
	wp_enqueue_style( 'code-manas-block-style', $assets_url . 'css/blocks.css', array( 'code-manas-style' ), $ver );

	wp_enqueue_style( 'font-awesome', $assets_url.'css/font-awesome.min.css', '', $ver );

	wp_enqueue_script( 'code-manas-navigation', $assets_url.'js/navigation.js', array( 'jquery' ), $ver, true );

	wp_enqueue_script( 'code-manas-skip-link-focus-fix', $assets_url.'js/skip-link-focus-fix.js', array( 'jquery' ), $ver, true );

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

	wp_register_script( 'js-cookie', $assets_url.'js/js-cookie.min.js', '', '2.2.1', true );
	$js_dependencies = array('jquery');
	/**
	 * Check if WooCommerce is active
	 **/
	if ( !in_array('woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
	    $js_dependencies[] = 'js-cookie';
	}
	wp_enqueue_script( 'code-manas-custom', $assets_url.'js/custom.js', $js_dependencies, $ver, true );
}

add_action( 'wp_enqueue_scripts', 'code_manas_scripts' );

/**
 * Enqueues styles for the block-based editor.
 *
 * @since Code Manas 1.0.0
 */
function code_manas_block_editor_styles() {
	// Block styles.
	wp_enqueue_style( 'code-manas-block-editor-style', get_theme_file_uri( '/assets/css/editor-blocks.css' ), array(), '1.1' );
	// Add custom fonts.
	wp_enqueue_style( 'code-manas-fonts', code_manas_fonts_url(), array(), null );
}

add_action( 'enqueue_block_editor_assets', 'code_manas_block_editor_styles' );

/*
 * Include helper funtions to be used in other templates.
 */
require_once get_parent_theme_file_path( '/inc/helper.php' );

/*
 * Include Kirki
 */
require_once get_parent_theme_file_path( '/inc/kirki/kirki.php' );

/*
 * Include woocommerce modifications
 */
if ( code_manas_is_woo_active() ) {
	require_once get_parent_theme_file_path( '/inc/woo/woo-hooks.php' );
}

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

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

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

if ( class_exists( 'Kirki' ) ) {
	/**
	 * Implement the Custom Header feature.
	 */
	require get_theme_file_path( '/inc/custom-header.php' );

	/**
	 * Implement the theme options using Kirki.
	 */
	require get_theme_file_path( '/inc/classes/class-cm-kirki-fields.php' );

	add_filter( 'kirki_telemetry', '__return_false' );
}

/**
 * Load Jetpack compatibility file.
 */
if ( defined( 'JETPACK__VERSION' ) ) {
	require get_theme_file_path( '/inc/jetpack.php' );
}

/**
 * TGM Plugin Activation additions.
 */
require get_theme_file_path( '/inc/classes/class-tgm-plugin-activation.php' );

if ( class_exists( 'TGM_Plugin_Activation' ) ) {
	add_action( 'tgmpa_register', function () {
		$plugins = array(
			array(
				'name'     => esc_html__( 'One Click Demo Import', 'code-manas' ),
				'slug'     => 'one-click-demo-import',
				'required' => false,
			),
		);

		$config = array(
			'id'           => 'code-manas',                 // Unique ID for hashing notices for multiple instances of TGMPA.
			'menu'         => 'tgmpa-install-plugins', // Menu slug.
			'parent_slug'  => 'themes.php',            // Parent menu slug.
			'capability'   => 'edit_theme_options',    // Capability needed to view plugin install page, should be a capability associated with the parent menu used.
			'has_notices'  => true,                    // Show admin notices or not.
			'dismissable'  => true,                    // If false, a user cannot dismiss the nag message.
			'is_automatic' => false,                   // Automatically activate plugins after installation or not.
		);

		tgmpa( $plugins, $config );
	} );
}
/**
 * Demo importer compatibility
 */
if ( class_exists( 'OCDI_Plugin' ) ) {
	add_filter( 'pt-ocdi/import_files', function () {
		return array(
			array(
				'import_file_name'             => esc_html__( 'Demo Import 1', 'code-manas' ),
				'local_import_file'            => get_theme_file_path( '/assets/ocdi/demo-content.xml' ),
				'local_import_widget_file'     => get_theme_file_path( '/assets/ocdi/widgets.wie' ),
				'local_import_customizer_file' => get_theme_file_path( '/assets/ocdi/customizer.dat' ),
			),
		);
	} );

	add_action( 'pt-ocdi/after_import', function () {
		// Assign menus to their locations.
		$primary_menu   = get_term_by( 'name', esc_html__( 'Primary', 'code-manas' ), 'nav_menu' );
		$secondary_menu = get_term_by( 'name', esc_html__( 'Secondary', 'code-manas' ), 'nav_menu' );
		$social_menu    = get_term_by( 'name', esc_html__( 'Social', 'code-manas' ), 'nav_menu' );

		set_theme_mod( 'nav_menu_locations', array(
				'menu-1' => $primary_menu->term_id,
				'menu-2' => $secondary_menu->term_id,
				'menu-3' => $social_menu->term_id,
			)
		);

		update_option( 'show_on_front', 'posts' );
	} );
}

/**
 * Add search form to the primary menu
 *
 * @param  string   $items The HTML list content for the menu items.
 * @param  stdClass $args  An object containing wp_nav_menu() arguments.
 *
 * @return  Mixed Menu output if $echo is false, false if there are no items or no menu was found.
 */
function code_manas_add_search_form( $items, $args ) {
	if ( $args->theme_location == 'menu-1' && get_theme_mod( 'primary_menu_search_enable', 1 ) ) {
		$items
			.= '<li>
		  		<a href="#" id="togglesearchbar"> <i class="fa fa-search" aria-hidden="true"></i> </a>
				<div class="search-form-nav" id="top-search" style="display:none">
					' . get_search_form( false ) . '               
				</div>
		  	</li>';
	}

	if ( $args->theme_location == 'menu-2' && get_theme_mod( 'secondary_menu_search_enable', 1 ) ) {
		$form = '<form id="custom-search-form" method="get" class="form-search" action="' . esc_url( home_url( '/' ) ) . '">
					<label>
						<input type="text" class="search-query" placeholder="' . esc_attr_x( 'Search your keyword', 'placeholder', 'code-manas' ) . '" value="' . esc_attr( get_search_query() ) . '" name="s" />
					</label>
					<input type="submit" class="search-submit" value="&#xf002">
				</form>';

		$items
			.= '<li class="custom-search">
						<div class="menu-search-wrapper">
							' . $form . ' 
						</div>
					</li>';
	}

	return $items;
}

add_filter( 'wp_nav_menu_items', 'code_manas_add_search_form', 10, 2 );

/**
 * Filter the excerpt "read more" string.
 *
 * @param string $more "Read more" excerpt string.
 *
 * @return string (Maybe) modified "read more" excerpt string.
 */
function code_manas_excerpt_more( $more ) {
	if ( is_admin() ) {
		return $more;
	}

	$defaults = cm_kirki_fields()->get_theme_mods_defaults();

	return sprintf( '<a class="continue-link" href="%1$s">%2$s</a>',
		esc_url( get_permalink( get_the_ID() ) ),
		esc_html( get_theme_mod( 'blog_excerpt_more', $defaults['blog_excerpt_more'] ) )
	);
}

add_filter( 'excerpt_more', 'code_manas_excerpt_more' );

/**
 * Add TRT customizer upsell.
 */
require get_theme_file_path( '/inc/trt-customize-pro/class-customize.php' );
