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

/**
 *  Defining Constants
 */

// Core Constants
define('KRYSTAL_REQUIRED_PHP_VERSION', '5.6' );
define('KRYSTAL_DIR_PATH', get_template_directory());
define('KRYSTAL_DIR_URI', get_template_directory_uri());
define('KRYSTAL_THEME_AUTH','https://www.spiraclethemes.com/');
define('KRYSTAL_THEME_URL','https://www.spiraclethemes.com/krystal-free-wordpress-theme/');
define('KRYSTAL_THEME_PRO_URL','https://www.spiraclethemes.com/krystal-pro-addons/');
define('KRYSTAL_THEME_DOC_URL','https://www.spiraclethemes.com/krystal-documentation/');
define('KRYSTAL_THEME_VIDEOS_URL','https://www.spiraclethemes.com/krystal-video-tutorials/');
define('KRYSTAL_THEME_SUPPORT_URL','https://wordpress.org/support/theme/krystal/');
define('KRYSTAL_THEME_RATINGS_URL','https://wordpress.org/support/theme/krystal/reviews/');
define('KRYSTAL_THEME_CHANGELOGS_URL','https://themes.trac.wordpress.org/log/krystal/');
define('KRYSTAL_THEME_CONTACT_URL','https://www.spiraclethemes.com/contact/');


// Register Custom Navigation Walker
require_once(get_template_directory() .'/inc/wp_bootstrap_navwalker.php');

//Register Required plugin
require_once(get_template_directory() .'/inc/class-tgm-plugin-activation.php');

/**
* Check for minimum PHP version requirement 
*
*/
function krystal_check_theme_setup( $oldtheme_name, $oldtheme ){
	// Compare versions.
	if ( version_compare(phpversion(), KRYSTAL_REQUIRED_PHP_VERSION, '<') ) :
	// Theme not activated info message.
	add_action( 'admin_notices', 'krystal_php_admin_notice' );
	function krystal_php_admin_notice() {
		?>
			<div class="update-nag">
		  		<?php esc_html_e( 'You need to update your PHP version to a minimum of 5.6 to run Krystal WordPress Theme.', 'krystal' ); ?> <br />
		  		<?php esc_html_e( 'Actual version is:', 'krystal' ) ?> <strong><?php echo phpversion(); ?></strong>, <?php esc_html_e( 'required is', 'krystal' ) ?> <strong><?php echo KRYSTAL_REQUIRED_PHP_VERSION; ?></strong>
			</div>
		<?php
	}
	// Switch back to previous theme.
	switch_theme( $oldtheme->stylesheet );
		return false;
	endif;
}
add_action( 'after_switch_theme', 'krystal_check_theme_setup', 10, 2  );


/**
 *  Theme Setup
 */

if ( ! function_exists( 'krystal_setup' ) ) :
function krystal_setup() {
	load_theme_textdomain( 'krystal', KRYSTAL_DIR_PATH . '/languages' );
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	register_nav_menus( array(
		'primary' => esc_html__( 'Primary', 'krystal' ),
	) );
	add_theme_support( 'html5', array(		
		'comment-form',
		'comment-list',
		'gallery',
		'caption',
	) );
	add_theme_support( 'post-formats', array( 'gallery' ));
	add_theme_support( 'customize-selective-refresh-widgets' );
	remove_theme_support( 'widgets-block-editor' );

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

	/**
	 * krystal theme info
	 */
	require KRYSTAL_DIR_PATH . '/inc/theme-info.php';

	/*
	* About page instance
	*/
	$config = array();
	Krystal_About_Page::krystal_init( $config );

	if ( is_customize_preview() ) {
		require KRYSTAL_DIR_PATH . '/inc/starter-content.php';
		add_theme_support( 'starter-content', krystal_get_starter_content() );
	}

}
endif;
add_action( 'after_setup_theme', 'krystal_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 krystal_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'krystal_content_width', 640 );
}
add_action( 'after_setup_theme', 'krystal_content_width', 0 );

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


	//Footer widget columns
    $widget_num = absint(get_theme_mod( 'kr_footer_widgets', '4' ));
    for ( $i=1; $i <= $widget_num; $i++ ) :
        register_sidebar( array(
            'name'          => esc_html__( 'Footer Column', 'krystal' ) . $i,
            'id'            => 'footer-column' . $i,
            'description'   => esc_html__( 'Add widgets here.', 'krystal' ),
            'before_widget' => '<div id="%1$s" class="section %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '<h4 class="widget-title">',
            'after_title'   => '</h4>',
        ) );
    endfor;

}
add_action( 'widgets_init', 'krystal_widgets_init' );

/**
* Admin Scripts
*/
if ( ! function_exists( 'krystal_admin_scripts' ) ) :
function krystal_admin_scripts($hook) {
  if('appearance_page_krystal-theme-info' != $hook)
    return;  
  	wp_enqueue_style( 'krystal-info-css', KRYSTAL_DIR_URI . '/css/krystal-theme-info.css', false );
}
endif;
add_action( 'admin_enqueue_scripts', 'krystal_admin_scripts' );


/**
 * Display Dynamic CSS.
 */
function krystal_dynamic_css_wrap() {

  require_once( KRYSTAL_DIR_PATH . '/css/dynamic.css.php' );
?>
  <style type="text/css" id="krystal-dynamic-style">
    <?php echo krystal_dynamic_css_stylesheet(); ?>
  </style>
<?php }
add_action( 'wp_head', 'krystal_dynamic_css_wrap' );


/**
 * Theme Styles and Scripts.
 */
function krystal_scripts() {
    // Define constants for template directory URIs
    $theme_uri = get_template_directory_uri();
    $theme_version = wp_get_theme()->get('Version');
    
    wp_enqueue_style( 'style', get_stylesheet_uri() );

    /* Check for minified styles */
    $enable_minify_styles = get_theme_mod( 'kr_enable_minify_styles', true );
    $stylesheets = [
        'bootstrap' => '/css/' . ($enable_minify_styles ? 'compressed/bootstrap.min.css' : 'bootstrap.css'),
        'fontawesome' => '/css/' . ($enable_minify_styles ? 'compressed/fontawesome.min.css' : 'fontawesome.css'),
        'magnific-popup' => '/css/' . ($enable_minify_styles ? 'compressed/magnific-popup.min.css' : 'magnific-popup.css'),
        'krystal-style' => '/css/' . ($enable_minify_styles ? 'compressed/krystal-style.min.css' : 'krystal-style.css'),
        'm-customscrollbar-css' => '/css/' . ($enable_minify_styles ? 'compressed/jquery.mCustomScrollbar.min.css' : 'jquery.mCustomScrollbar.css'),
    ];

    foreach ($stylesheets as $handle => $stylesheet) {
        wp_enqueue_style( $handle, $theme_uri . $stylesheet, [], $theme_version );
    }

    if ( is_singular() && has_blocks() ) {
        wp_enqueue_style( 'krystal-blocks-frontend', $theme_uri . '/css/' . ($enable_minify_styles ? 'compressed/blocks-frontend.min.css' : 'blocks-frontend.css'), [], $theme_version );
    }

    /* Check for minified scripts */
    $enable_minify_scripts = get_theme_mod( 'kr_enable_minify_scripts', true );
    $scripts = [
        'bootstrap-js' => '/js/' . ($enable_minify_scripts ? 'compressed/bootstrap.min.js' : 'bootstrap.js'),
        'jquery-easing' => '/js/' . ($enable_minify_scripts ? 'compressed/jquery.easing.1.3.min.js' : 'jquery.easing.1.3.js'),
        'modernizr' => '/js/' . ($enable_minify_scripts ? 'compressed/modernizr.min.js' : 'modernizr.js'),
        'parallax' => '/js/' . ($enable_minify_scripts ? 'compressed/parallax.min.js' : 'parallax.js'),
        'jquery-magnific' => '/js/' . ($enable_minify_scripts ? 'compressed/jquery.magnific-popup.min.js' : 'jquery.magnific-popup.js'),
        'krystal-script' => '/js/' . ($enable_minify_scripts ? 'compressed/krystal-main.min.js' : 'krystal-main.js'),
        'html5shiv' => '/js/' . ($enable_minify_scripts ? 'compressed/html5shiv.min.js' : 'html5shiv.js'),
        'respond' => '/js/' . ($enable_minify_scripts ? 'compressed/respond.min.js' : 'respond.js'),
    ];

    foreach ($scripts as $handle => $script) {
        wp_enqueue_script( $handle, $theme_uri . $script, [], $theme_version, true );
    }

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

    wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' );
    wp_script_add_data( 'respond', 'conditional', 'lt IE 9' );
}
add_action( 'wp_enqueue_scripts', 'krystal_scripts' );



/**
* Custom excerpt length.
*/
function krystal_my_excerpt_length($length) {
	if ( is_admin() ) {
		return $length;
	}
  	return 25;
}
add_filter('excerpt_length', 'krystal_my_excerpt_length');


/**
* Registers an editor stylesheet for the theme.
*/
function krystal_theme_add_editor_styles() {
    add_editor_style(KRYSTAL_DIR_URI . '/css/custom-editor-style.css');
}
add_action( 'admin_init', 'krystal_theme_add_editor_styles' );


/**
 * Custom search form
 */
function krystal_search_form( $form ) {
    $search_query = get_search_query();
    $form = sprintf(
        '<form method="get" id="searchform" class="searchform" action="%s">
            <div class="search">
                <input type="text" value="%s" class="blog-search" name="s" id="s" placeholder="%s">
                <label for="searchsubmit" class="search-icon"><i class="fas fa-search"></i></label>
                <input type="submit" id="searchsubmit" value="%s" />
            </div>
        </form>',
        esc_url(home_url('/')),
        esc_attr($search_query),
        esc_attr__('Search here', 'krystal'),
        esc_attr__('Search', 'krystal')
    );
    return $form;
}
add_filter( 'get_search_form', 'krystal_search_form', 100 );


/** 
 * Excerpt More
 */
function krystal_excerpt_more( $more ) {
    return is_admin() ? $more : '&hellip;';
}
add_filter('excerpt_more', 'krystal_excerpt_more');



/**
 * Add a pingback url auto-discovery header for singularly identifiable articles.
 */
function krystal_pingback_header() {
  if ( is_singular() && pings_open() ) {
    printf( '<link rel="pingback" href="%s">' . "\n", get_bloginfo( 'pingback_url' ) );
  }
}
add_action( 'wp_head', 'krystal_pingback_header' );


/**
 * Using home page title instead of site name 
 */
if ( !function_exists('krystal_breadcrumb_title') ) :
function krystal_breadcrumb_title($title, $type, $id) {
    return ($type[0] === 'home') ? get_the_title(get_option('page_on_front')) : $title;
}
endif;
add_filter('bcn_breadcrumb_title', 'krystal_breadcrumb_title', 42, 3);


/**
 * Add sticky header
 */
function krystal_sticky_header_script() {
    if ( get_theme_mod( 'kr_sticky_menu', true ) ) {
        $script_path = ( get_theme_mod( 'kr_enable_minify_scripts', true ) )
            ? '/js/compressed/krystal-sticky.min.js'
            : '/js/krystal-sticky.js';

        wp_enqueue_script( 'krystal-sticky-script', KRYSTAL_DIR_URI . $script_path, array( 'jquery' ), wp_get_theme()->get( 'Version' ), true );

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


/**
 * Check WooCommerce is active
*/

if ( ! function_exists( 'krystal_is_woocommerce_activated' ) ) :
	function krystal_is_woocommerce_activated() {
		if ( class_exists( 'woocommerce' ) ) { return true; } else { return false; }
	}
endif;


/**
 * Load our Block Editor styles to style the Editor like the front-end
 */
if ( ! function_exists( 'krystal_block_editor_width_styles' ) ) :
function krystal_block_editor_width_styles() {
    $krystal_layout_width = 1200;
    $styles = '';

    // Choose the correct stylesheet based on whether minification is enabled
    $style_path = ( get_theme_mod( 'kr_enable_minify_styles', true ) )
        ? '/css/compressed/blocks-style.min.css'
        : '/css/blocks-style.css';

    wp_enqueue_style( 'krystal-blocks-style', KRYSTAL_DIR_URI . $style_path, array(), wp_get_theme()->get( 'Version' ) );

    // Generate styles for the editor width and button background color
    $styles .= 'body.gutenberg-editor-page .edit-post-visual-editor .editor-post-title .editor-post-title__block,
                body.gutenberg-editor-page .edit-post-visual-editor .editor-block-list__block,
                body.gutenberg-editor-page .edit-post-visual-editor .editor-default-block-appender {
                    max-width: ' . esc_attr( $krystal_layout_width - 10 ) . 'px;
                }';

    // Wide block styles
    $styles .= 'body.gutenberg-editor-page .edit-post-visual-editor .editor-block-list__block[data-align="wide"] {
                    max-width: ' . esc_attr( $krystal_layout_width - 10 + 400 ) . 'px;
                }';

    // Full block styles
    $styles .= 'body.gutenberg-editor-page .edit-post-visual-editor .editor-block-list__block[data-align="full"] {
                    max-width: none;
                }';

    // Dynamic color for buttons
    $styles .= '.wp-block-button__link, .wc-block-grid__product-onsale, .wp-block-search .wp-block-search__button {
                    background-color: ' . sanitize_hex_color( get_theme_mod( 'own_shop_site_primary_color', '#cc9866' ) ) . ';
                }';

    // Output styles into the <head> when block styles are enqueued
    wp_add_inline_style( 'krystal-blocks-style', $styles );
}
endif;
add_action( 'enqueue_block_editor_assets', 'krystal_block_editor_width_styles' );



/**
 *  Set homepage and blog page after demo import
 */

if ( !function_exists('krystal_after_import_setup') ) :
function krystal_after_import_setup() {    
        
    //Assign menus to their locations
    $main_menu = get_term_by( 'name', 'Primary', 'nav_menu' );
    set_theme_mod( 'nav_menu_locations', array(
          'primary' => $main_menu->term_id,
        )
    );

    //Assign front page
    $front_page = get_page_by_title( 'Home' );  
    $blog_page = get_page_by_title( 'Blog' );  

    update_option( 'show_on_front', 'page' );
    update_option( 'page_on_front', $front_page -> ID );    
    update_option( 'page_for_posts', $blog_page -> ID );     
   
}
endif;
add_action( 'pt-ocdi/after_import', 'krystal_after_import_setup' );

/** 
*plugins Required
*/

function krystal_register_required_plugins() {

    $plugins = array(
      array(
          'name'               => 'Spiraclethemes Site Library',
          'slug'               => 'spiraclethemes-site-library',
          'source'             => '',
          'required'           => false,          
          'force_activation'   => false,
      ),    
    );

    $config = array(
            'id'           => 'krystal',
            'default_path' => '',
            'menu'         => 'tgmpa-install-plugins',
            'has_notices'  => true,
            'dismissable'  => true,
            'dismiss_msg'  => '',
            'is_automatic' => false,
            'message'      => '',
            'strings'      => array()
    );

    tgmpa( $plugins, $config );

}
add_action( 'tgmpa_register', 'krystal_register_required_plugins' );

/**
 * Theme includes.
 */
$includes = [
    'inc/customizer/customizer.php',
    'inc/template-functions.php',
    'inc/template-tags.php',
    'inc/template-hooks.php',
    'inc/extras.php',
    'inc/widgets.php',
    'krystal-pro/class-customize.php' // This one uses require_once
];

foreach ( $includes as $file ) {
    $file_path = KRYSTAL_DIR_PATH . '/' . $file;
    if ( strpos( $file, 'krystal-pro/class-customize.php' ) !== false ) {
        require_once( $file_path ); // Special case for require_once
    } else {
        require( $file_path );
    }
}
