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

if ( ! function_exists( 'store_prima_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 store_prima_setup() {
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 * If you're building a theme based on store prima, use a find and replace
		 * to change 'store-prima' to the name of your theme in all the template files.
		 */
		load_theme_textdomain( 'store-prima', get_template_directory() . '/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' );
		add_image_size( 'store-prima-home-recent-posts', 600, 9999 );
		add_image_size( 'store-prima-ecomproduct', 720, 450, true );
		add_image_size( 'store-prima-ecomproduct-new', 900, 700, true );

		// This theme uses wp_nav_menu() in one location.
		register_nav_menus( array(
			'menu-1' => esc_html__( 'Primary', 'store-prima' ),
		) );

		/*
		 * 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( 'store_prima_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,
		) );
		
		add_post_type_support( 'page', 'excerpt' );
		
		// Enable WooCommerce.
		add_theme_support( 'woocommerce' );
		add_filter( 'woocommerce_enqueue_styles', '__return_false' );
		
	}
endif;
add_action( 'after_setup_theme', 'store_prima_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 store_prima_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( 'store_prima_content_width', 640 );
}
add_action( 'after_setup_theme', 'store_prima_content_width', 0 );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function store_prima_widgets_init() {
	
	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar', 'store-prima' ),
		'id'            => 'sidebar-1',
		'description'   => esc_html__( 'Add widgets here.', 'store-prima' ),
		'before_widget' => '<section id="%1$s" class="widget widgetContainer %2$s"><div class="widgetContainerInner">',
		'after_widget'  => '</div></section>',
		'before_title'  => '<h2 class="widget-title"><span>',
		'after_title'   => '</span></h2>',
	) );	
	
	register_sidebar( array(
		'name'          => esc_html__( 'Footer Left Widget Area', 'store-prima' ),
		'id'            => 'footer-left',
		'description'   => esc_html__( 'Add widgets here.', 'store-prima' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h2 class="widget-title"><span>',
		'after_title'   => '</span></h2>',
	) );
	
	register_sidebar( array(
		'name'          => esc_html__( 'Footer Middle Widget Area', 'store-prima' ),
		'id'            => 'footer-middle',
		'description'   => esc_html__( 'Add widgets here.', 'store-prima' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h2 class="widget-title"><span>',
		'after_title'   => '</span></h2>',
	) );
	
	register_sidebar( array(
		'name'          => esc_html__( 'Footer Right Widget Area', 'store-prima' ),
		'id'            => 'footer-right',
		'description'   => esc_html__( 'Add widgets here.', 'store-prima' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h2 class="widget-title"><span>',
		'after_title'   => '</span></h2>',
	) );
	
}
add_action( 'widgets_init', 'store_prima_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function store_prima_scripts() {
	
	wp_enqueue_style( 'store-prima-fonts', '//fonts.googleapis.com/css?family=Montserrat:400,600,700,800|Open+Sans:400,600,700' );
	
	wp_enqueue_style( 'store-prima-style', get_stylesheet_uri() );
	
	wp_enqueue_style( 'store-prima-slider-css', get_template_directory_uri() . '/assets/css/slider/owl.carousel.css' );
	wp_enqueue_style( 'store-prima-slider-theme', get_template_directory_uri() . '/assets/css/slider/owl.theme.css' );
	wp_enqueue_style( 'store-prima-slider-transitions', get_template_directory_uri() . '/assets/css/slider/owl.transitions.css' );	

	wp_enqueue_script( 'store-prima-owl', get_template_directory_uri() . '/assets/js/owl.carousel.js', array('jquery'), '20151215', true );
	
	wp_register_script( 'store-prima-general', get_template_directory_uri() . '/assets/js/general.js' );
	$store_prima_js_variable_array = array(
		'frontpage' => false,
	);
	if( 'page2.php' == get_page_template_slug() ){
		
		$store_prima_js_variable_array['frontpage'] = true;
		
	}
	wp_localize_script( 'store-prima-general', 'storePrimaJs', $store_prima_js_variable_array );
	wp_enqueue_script( 'store-prima-general', '', array('jquery'), '20151215', true );

	wp_enqueue_script( 'store-prima-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );

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

function store_prima_title( $title ) {

    if ( '' == $title ) {
        return __('no title', 'store-prima' );
    }

    return $title;
}
add_filter( 'the_title', 'store_prima_title', 10, 2 );

function store_prima_limitedstring($output, $max_char=100){
	
	$output = str_replace(']]>', ']]&gt;', $output);
    $output = strip_tags($output);
    $output = strip_shortcodes($output);

  	if ((strlen($output)>$max_char)){
        $output = substr($output, 0, $max_char);
		return $output;
   	}else{
      	return $output;
   	}
	
}

function store_prima_get_random_post(){
	
	$output = get_posts(
		
		array(
		
			'numberposts'      => 1,
			'orderby' => 'rand',
			'fields'          => 'ids',
		)
		
	);
	
	return $output[0];
	
}

function store_prima_woo_pagination( $paged = '', $max_page = '' ){
 
	$big = 999999999; // need an unlikely integer
        if( ! $paged )
            $paged = get_query_var('paged');
        if( ! $max_page )
            $max_page = $wp_query->max_num_pages;

        echo wp_kses(
			
				paginate_links( array(
					'base'       => str_replace($big, '%#%', esc_url(get_pagenum_link( $big ))),
					'format'     => '?paged=%#%',
					'current'    => max( 1, $paged ),
					'total'      => $max_page,
					'mid_size'   => 1,
					'prev_text'  => __('«', 'store-prima'),
					'next_text'  => __('»', 'store-prima'),
					'type'       => 'list'
				) ),
				array(
					'a' => array(
						'href' => array(),
						'class' => array(),
						'title' => array()
					),
					'ul' => array(
						'class' => array(),
					),	
					'li' => array(
						'class' => array(),
					),
					'span' => array(
						'class' => array(),
						'aria-current' => array(),
					),					
				)
			);
	
}

function store_prima_product_slider(){
    add_meta_box( 'store_prima_product_slider', __( 'Store Prima Slider Settings', 'store-prima' ), 'store_prima_product_slider_display_callback', 'product', 'side', 'high', null );
}
add_action( 'add_meta_boxes', 'store_prima_product_slider' );

$store_prima_meta_options = array(

        'slider_show' => array(
			'select' => __( "Select", "store-prima" ),
			'yes' => __( "Yes", "store-prima" ),
			'no' => __( "No", "store-prima" ),	
		),	
	
        'slider_type' => array(
			'select' => __( "Select", "store-prima" ),
			'one' => __( "One", "store-prima" ),
			'two' => __( "Two", "store-prima" ),
			'three' => __( "Three", "store-prima" ),	
		),
	
        'overlay_type' => array(
			'select' => __( "Select", "store-prima" ),
			'black' => __( "Black", "store-prima" ),
			'blue' => __( "Blue", "store-prima" ),
			'green' => __( "Green", "store-prima" ),
			'red' => __( "Red", "store-prima" ),
			'purple' => __( "Purple", "store-prima" ),
		),
	
        'bg_position' => array(
			'select' => __( "Select", "store-prima" ),
			'top right' => __( "Top Right", "store-prima" ),
			'top left' => __( "Top Left", "store-prima" ),
			'bottom right' => __( "Bottom Right", "store-prima" ),
			'bottom left' => __( "Bottom Left", "store-prima" ),
			'none' => __( "None", "store-prima" ),
		),	

);

function store_prima_product_slider_display_callback($object){

		wp_nonce_field(basename(__FILE__), "store-prima-product-slider-nonce");
		
		global $store_prima_meta_options;
	
		echo '<div>

            <p style="margin:0 0 6px 0;"><label for="store_prima_show_in_product_slider">' . esc_html__( "Show In Product Slider", "store-prima" ) . '</label></p>
            <select name="store_prima_show_in_product_slider">';

                    foreach($store_prima_meta_options['slider_show'] as $key => $value) 
                    {
                        if($key == get_post_meta($object->ID, "store_prima_show_in_product_slider", true))
                        {
                            echo '<option value="' . esc_attr($key) . '" selected>' . esc_html($value) . '</option>';    
                        }
                        else
                        {
                            echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
                        }
                    }

            echo '</select>';
	
		echo '</div>';	
	
		echo '<div style="padding-top:6px;">';		
	
            echo '<p style="margin:0 0 6px 0;"><label for="store_prima_product_slide_type">' . esc_html__( "Product Slide Type", "store-prima" ) . '</label></p>
            <select name="store_prima_product_slide_type">';

                    foreach($store_prima_meta_options['slider_type'] as $key => $value) 
                    {
                        if($key == get_post_meta($object->ID, "store_prima_product_slide_type", true))
                        {
                            echo '<option value="' . esc_attr($key) . '" selected>' . esc_html($value) . '</option>';    
                        }
                        else
                        {
                            echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
                        }
                    }

            echo '</select>';

		echo '</div>';
	
		echo '<div style="padding-top:6px;">';		
	
            echo '<p style="margin:0 0 6px 0;"><label for="store_prima_product_slide_overlay_type">' . esc_html__( "Slide Overlay Type", "store-prima" ) . '</label></p>
            <select name="store_prima_product_slide_overlay_type">';

                    foreach($store_prima_meta_options['overlay_type'] as $key => $value) 
                    {
                        if($key == get_post_meta($object->ID, "store_prima_product_slide_overlay_type", true))
                        {
                            echo '<option value="' . esc_attr($key) . '" selected>' . esc_html($value) . '</option>';    
                        }
                        else
                        {
                            echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
                        }
                    }

            echo '</select>';

		echo '</div>';	
	
		echo '<div style="padding-top:6px;">';		
	
            echo '<p style="margin:0 0 6px 0;"><label for="store_prima_product_slide_bg_position">' . esc_html__( "Slide BG Position", "store-prima" ) . '</label></p>
            <select name="store_prima_product_slide_bg_position">';

                    foreach($store_prima_meta_options['bg_position'] as $key => $value) 
                    {
                        if($key == get_post_meta($object->ID, "store_prima_product_slide_bg_position", true))
                        {
                            echo '<option value="' . esc_attr($key) . '" selected>' . esc_html($value) . '</option>';    
                        }
                        else
                        {
                            echo '<option value="' . esc_attr($key) . '">' . esc_html($value) . '</option>';
                        }
                    }

            echo '</select>';

		echo '</div>';	
	
}

function store_prima_product_slider_save_meta($post_id) {
		
	   if (!isset($_POST["store-prima-product-slider-nonce"]) || !wp_verify_nonce($_POST["store-prima-product-slider-nonce"], basename(__FILE__)))
			return $post_id;
	
		global $store_prima_meta_options;

		if(!current_user_can("edit_post", $post_id))
			return $post_id;

		if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
			return $post_id;

		if ( isset( $_POST['post_type'] ) && "product" === $_POST['post_type'] ) {

			$store_prima_show_in_product_slider_value = "";

			if(isset($_POST["store_prima_show_in_product_slider"]) && array_key_exists($_POST["store_prima_show_in_product_slider"], $store_prima_meta_options['slider_show'])){
				$store_prima_show_in_product_slider_value = $_POST["store_prima_show_in_product_slider"];
			}   
			update_post_meta($post_id, "store_prima_show_in_product_slider", $store_prima_show_in_product_slider_value);
			
			$store_prima_product_slide_type_value = "";

			if(isset($_POST["store_prima_product_slide_type"]) && array_key_exists($_POST["store_prima_product_slide_type"], $store_prima_meta_options['slider_type'])){
				$store_prima_product_slide_type_value = $_POST["store_prima_product_slide_type"];
			}   
			update_post_meta($post_id, "store_prima_product_slide_type", $store_prima_product_slide_type_value);
			
			$store_prima_product_slide_overlay_type_value = "";

			if(isset($_POST["store_prima_product_slide_overlay_type"]) && array_key_exists($_POST["store_prima_product_slide_overlay_type"], $store_prima_meta_options['overlay_type'])){
				$store_prima_product_slide_overlay_type_value = $_POST["store_prima_product_slide_overlay_type"];
			}   
			update_post_meta($post_id, "store_prima_product_slide_overlay_type", $store_prima_product_slide_overlay_type_value);
			
			$store_prima_product_slide_bg_position_value = "";
			
			if(isset($_POST["store_prima_product_slide_bg_position"]) && array_key_exists($_POST["store_prima_product_slide_bg_position"], $store_prima_meta_options['bg_position'])){
				$store_prima_product_slide_bg_position_value = $_POST["store_prima_product_slide_bg_position"];
			}   
			update_post_meta($post_id, "store_prima_product_slide_bg_position", $store_prima_product_slide_bg_position_value);			
			
		}else{
			
			return $post_id;
			
		}
		
}
add_action( 'save_post', 'store_prima_product_slider_save_meta' );


function store_prima_add_show_option_woo_product_cat() {
    ?>
	<div class="form-field">
		<label for="parent"><?php esc_html_e( "Show on front page?", "store-prima" ); ?></label>
		<select name="store-prima-show-on-front" id="parent" class="postform">
			<option value="no"><?php esc_html_e( "No", "store-prima" ); ?></option>
			<option value="yes"><?php esc_html_e( "Yes", "store-prima" ); ?></option>
		</select>
		<p><?php esc_html_e( "Set to yes if you want to show this category on front page in categories section", "store-prima" ); ?></p>
	</div>
    <?php
}


function store_prima_add_show_option_woo_product_cat_edit($term) {

    //getting term ID
    $term_id = $term->term_id;

    // retrieve the existing value(s) for this meta field.
    $store_prima_value = esc_html(get_term_meta($term_id, 'store-prima-show-on-front', true));
    ?>
	<div class="form-field">
		<label for="parent"><?php esc_html_e( "Show on front page?", "store-prima" ); ?></label>
		<select name="store-prima-show-on-front" id="parent" class="postform">
			<option <?php selected( $store_prima_value, 'no' ); ?> value="no"><?php esc_html_e( "No", "store-prima" ); ?></option>
			<option <?php selected( $store_prima_value, 'yes' ); ?> value="yes"><?php esc_html_e( "Yes", "store-prima" ); ?></option>
		</select>
		<p><?php esc_html_e( "Set to yes if you want to show this category on front page in categories section", "store-prima" ); ?></p>
	</div>
    <?php
}

add_action('product_cat_add_form_fields', 'store_prima_add_show_option_woo_product_cat', 10, 1);
add_action('product_cat_edit_form_fields', 'store_prima_add_show_option_woo_product_cat_edit', 10, 1);


function store_prima_add_show_option_woo_product_cat_save($term_id) {

    $store_prima_value = filter_input(INPUT_POST, 'store-prima-show-on-front');
	if( !in_array($store_prima_value, array('no', 'yes')) ){
		$store_prima_value = 'no';
	}

    update_term_meta($term_id, 'store-prima-show-on-front', $store_prima_value);
}

add_action('edited_product_cat', 'store_prima_add_show_option_woo_product_cat_save', 10, 1);
add_action('create_product_cat', 'store_prima_add_show_option_woo_product_cat_save', 10, 1);

/**
 * 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';

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

// Include the Loader class.
require_once get_theme_file_path( '/inc/Loader.php' );

// Create a new instance of the Loader class.
$store_prima_loader = new \WPTRT\Autoload\Loader();

// Add (one or multiple) namespaces and their paths.
$store_prima_loader->add( 'WPTRT\\Customize\\Section\\', get_template_directory() . '/inc/' );
$store_prima_loader->add( 'WPTRT\\AdminNotices\\', get_template_directory() . '/inc/admin-notices/src/' );

// Register all loaders.
$store_prima_loader->register();

/* UpGrade */
require get_template_directory() . '/inc/upgrade.php';

/* Notices */
require get_template_directory() . '/inc/notices.php';

/* Guide */
require get_template_directory() . '/inc/theme-info.php';