<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Redux options framework
if ( class_exists( 'ReduxFramework' ) ) {
	add_action( 'redux/construct', 'shrk_redux_modify_construct' );
	add_action( 'redux/loaded', 'shrk_redux_modify_args' );
	add_action( 'redux/loaded', 'shrk_redux_remove_css_output' );
	add_action( 'admin_enqueue_scripts', 'shrk_redux_backend_scripts', 10 );
	add_action( 'shrk_theme_first_install', 'shrk_redux_setup_first_install' );
	add_action( 'shrk_redux_sections_after_page_cover', 'shrk_set_mmenu_bg_options', 10, 1 );

	// Redux configuration
	if ( !isset( $redux_demo ) && file_exists( SHRK_THEME_MODULES . '/redux/redux.config.php' ) ) {
		require_once( SHRK_THEME_MODULES . '/redux/redux.config.php' );
	}
}






function shrk_redux_modify_args($redux) {
	global $shrk_options;

	// Setup either user specified google api key, or theme's custom api url.
	if ( !empty($shrk_options['shrk_googlemaps_api_key']) && trim($shrk_options['shrk_googlemaps_api_key']) != '' ) {
		$redux->args['google_api_key'] = $shrk_options['shrk_googlemaps_api_key'];
	} else {
		add_filter( 'redux-google-fonts-api-url', function() { return SHRK_GOOGLE_FONTS_URL . '?key='; });
	}

}

function shrk_redux_modify_construct($redux) {
	// Disable redux tracking
	$tr_options = get_option( 'redux-framework-tracking' );
	$tr_options['allow_tracking'] = false;
	update_option('redux-framework-tracking', $tr_options);
}


function shrk_redux_set_frontpage( $old, $new ) {
	if ( !class_exists( 'ReduxFrameworkInstances' ) ) return;

	$redux = ReduxFrameworkInstances::get_instance( 'shrk_theme_options' );
	if ( $redux ) {
		$redux->set('site_front_page', $new);		
	}
}
add_action( 'update_option_page_on_front', 'shrk_redux_set_frontpage', 10, 2 );


function shrk_redux_set_blogpage( $old, $new ) {
	if ( !class_exists( 'ReduxFrameworkInstances' ) ) return;

	$redux = ReduxFrameworkInstances::get_instance( 'shrk_theme_options' );
	if ( $redux ) {
		$redux->set('site_blog_page', $new);	
	}
}
add_action( 'update_option_page_for_posts', 'shrk_redux_set_blogpage', 10, 2 );


function shrk_save_customizer_to_redux() {
	if ( !class_exists( 'ReduxFrameworkInstances' ) ) return;

	$redux = ReduxFrameworkInstances::get_instance( 'shrk_theme_options' );
	if ( !$redux ) {
		return;
	}
	
	// Save custom logo	
	if ( get_theme_mod( 'custom_logo' ) ) {
		$redux->set( 'site_logo', shrk_redux_img_array( get_theme_mod( 'custom_logo' ) ) );	
	} else {
		$redux->set( 'site_logo', false );	
	}

	// Save site icon	
	if ( absint( get_option( 'site_icon' ) ) ) {
		$redux->set( 'site_icon', shrk_redux_img_array( absint( get_option( 'site_icon' ) ) ) );	
	} else {
		$redux->set( 'site_icon', false );	
	}

	// Save Header image -> default cover image
	if ( $header_image = get_custom_header() && isset( $header_image->attachment_id ) ) {
		$redux->set( 'cover_default_image', shrk_redux_img_array( $header_image->attachment_id ) );	
	} else {
		$redux->set( 'cover_default_image', false );	
	}

	// Save 'Products per row' to 'Shop Columns grid'
	if ( get_option('woocommerce_catalog_columns' ) ) {
		$redux->set( 'woo_shop_columns_grid', shrk_redux_columns_grid_limited( shrk_get_theme_option( 'woo_shop_columns_grid' ), get_option( 'woocommerce_catalog_columns' ) ) );
	}

}
add_action( 'customize_save_after', 'shrk_save_customizer_to_redux');

/**
 * When in customizer preview, 
 * Change theme options to the customized values
 * 
 * @param  array $theme_options redux's theme options
 * @return array                Filtered options
 */
function shrk_redux_customizer_preview_options( $theme_options ) {
	global $wp_customize;

	if ( is_customize_preview() && is_object( $wp_customize ) ) {
		$customized_values = !empty( $_REQUEST['customized'] ) ? json_decode( wp_unslash( $_REQUEST['customized'] ), true ) : false;

		if ( !empty( $customized_values['woocommerce_catalog_columns'] ) ) {
			$woocommerce_catalog_columns = $customized_values['woocommerce_catalog_columns'];
		} 

		if ( empty( $woocommerce_catalog_columns ) ) {
			$customized_values = $wp_customize->changeset_data();
			$woocommerce_catalog_columns = !empty( $customized_values ) && !empty( $customized_values['woocommerce_catalog_columns'] ) && !empty( $customized_values['woocommerce_catalog_columns']['value'] ) ? $customized_values['woocommerce_catalog_columns']['value'] : false; 
		}

		if ( !empty( $woocommerce_catalog_columns ) ) {
			$theme_options['woo_shop_columns_grid'] = shrk_redux_columns_grid_limited( $theme_options['woo_shop_columns_grid'], $woocommerce_catalog_columns );
		}
	}

	return $theme_options;
}
add_filter( 'redux/options/shrk_theme_options/global_variable', 'shrk_redux_customizer_preview_options' );


function shrk_redux_save_wp_options() {
	global $shrk_options;

	// Set front page 
	if ( !empty( $shrk_options['site_front_page'] ) ) {
		update_option( 'page_on_front', $shrk_options['site_front_page'] );
	} else {
		update_option( 'page_on_front', 0 );
	}

	// Set blog page
	if ( !empty( $shrk_options['site_blog_page'] ) ) {
		update_option( 'page_for_posts', $shrk_options['site_blog_page'] );
	} else {
		update_option( 'page_for_posts', 0 );
	}

	// Set what to show option
	if ( empty($shrk_options['site_front_page']) && empty($shrk_options['site_blog_page']) ) {
		update_option( 'show_on_front', 'posts' );	
	} else {
		update_option( 'show_on_front', 'page' );
	}

	// Set site logo to WP custom log (4.5) theme mod
	if ( function_exists( 'the_custom_logo' ) && isset( $shrk_options['site_logo']['id'] ) && !empty( $shrk_options['site_logo']['id'] ) ) {
		set_theme_mod( 'custom_logo', intval( $shrk_options['site_logo']['id'] ) );
	} else {
		set_theme_mod( 'custom_logo', false );
	}

	// Set site logo to WP site icon (4.3) theme mod
	if ( function_exists( 'site_icon_url' ) && isset( $shrk_options['site_icon']['id'] ) && !empty( $shrk_options['site_icon']['id'] ) ) {
		update_option( 'site_icon', intval( $shrk_options['site_icon']['id'] ) );
	} else {
		delete_option( 'site_icon' );
	}

	// Set default cover image to site header
	if ( isset( $shrk_options['cover_default_image'] ) && !empty( $shrk_options['cover_default_image']['id'] ) ) {
		$cover_id          = intval( $shrk_options['cover_default_image']['id'] );
		$header_image_data = shrk_customizer_img_obj( $cover_id );

		set_theme_mod( 'header_image_data', $header_image_data );
		set_theme_mod( 'header_image', $header_image_data->url );
		update_post_meta( $cover_id, '_wp_attachment_is_custom_header', get_stylesheet() );
	} else {
		set_theme_mod( 'header_image_data', false );
		set_theme_mod( 'header_image', false );
	}

	// Set Shop Columns grid's 1st value to 'Products per row'
	if ( isset( $shrk_options['woo_shop_columns_grid'] ) && !empty( $shrk_options['woo_shop_columns_grid'][0] ) && $shrk_options['woo_shop_columns_grid'][0]['opr'] == 'min' ) {
		update_option('woocommerce_catalog_columns', $shrk_options['woo_shop_columns_grid'][0]['cols'] );
	}
}
add_action( 'redux/options/shrk_theme_options/saved', 'shrk_redux_save_wp_options' );


function shrk_redux_setup_first_install() {
	if ( !class_exists( 'ReduxFrameworkInstances' ) ) return;

	$redux = ReduxFrameworkInstances::get_instance( 'shrk_theme_options' );
	if ( !$redux ) {
		return;
	}

	if ( get_option( 'show_on_front' ) == 'page' ) {
		$front_page = get_option( 'page_on_front' );
		$blog_page = get_option( 'page_for_posts' );
		
		if ( !empty($front_page) ) {
			$redux->set( 'site_front_page', $front_page );	
		}

		if ( !empty($blog_page) ) {
			$redux->set( 'site_blog_page', $blog_page );	
		}
	}

	shrk_save_customizer_to_redux();
}

function shrk_redux_get_page_sections() {

	$args      = array('posts_per_page' => -1, 'post_type' => 'pagesections');
	$sections  = get_posts( $args );
	$array_out = array();

	foreach ($sections as $section) {
		$array_out[$section->ID] = $section->post_title;
	}

	return $array_out;
}

function shrk_redux_get_css_selectors_array( $option_id, $output_props ) {
	$map_file = SHRK_THEME_MODULES . '/redux/redux.class_extends.php';
	$ret      = array();

	if ( file_exists( $map_file ) ) {
		include( $map_file );
	}
	
	if ( !empty( $map ) ) {
		foreach ($output_props as $out_prop) {
			if ( isset($map[$option_id][$out_prop]) ) {
				$ret[$out_prop] = shrk_simple_minify($map[$option_id][$out_prop]);
			}
		}
	} else {
		trigger_error('File \'' . $map_file . '\' not found or not valid. Cannot generate dynamic css.', E_USER_NOTICE );
	}
	return $ret;	
}

function shrk_redux_get_page_layout_options() {
	return array(
		'no_sidebar'    => array(
				'alt' => esc_html__( 'No Sidebar', 'ux-shop' ),
				'img' => ReduxFramework::$_url . 'assets/img/1col.png'
			),
		'left_sidebar'    => array(
				'alt' => esc_html__( 'Left Sidebar', 'ux-shop' ),
				'img' => ReduxFramework::$_url . 'assets/img/2cl.png'
			),
		'right_sidebar'    => array(
				'alt' => esc_html__( 'Right Sidebar', 'ux-shop' ),
				'img' => ReduxFramework::$_url . 'assets/img/2cr.png'
			),
		);
}

function shrk_redux_img_array( $attachment_id ) {
	$img    = wp_get_attachment_image_src( $attachment_id, 'full' );
	$img_th = wp_get_attachment_image_src( $attachment_id, 'thumb' );

	return array(
		'url'       => $img[0],
		'id'        => $attachment_id,
		'height'    => $img[2],
		'width'     => $img[1],
		'thumbnail' => $img_th[0]
		);
}

function shrk_customizer_img_obj( $attachment_id ) {
	$img = wp_get_attachment_image_src( $attachment_id, 'full' );
	return (object) array(
		'attachment_id' => $attachment_id,
		'url'           => $img[0],
		'thumbnail_url' => $img[0],
		'height'        => $img[2],
		'width'         => $img[1]
		);	
}

function shrk_redux_backend_scripts() {
	global $shrk_theme_info;
	$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';

	wp_enqueue_script( 'redux-shrk-js' , SHRK_THEME_MODULES_URI . 'redux/js/redux' . $suffix . '.js', array(), $shrk_theme_info['Version'] );
}

/**
 * Expose selected options to js
 */
add_filter( 'shrk_redux_options_to_js', function( $redux_options ) {
	$redux_options[] = 'autocollapse_menu';
	$redux_options[] = 'no_mobile_parallax';
	return $redux_options;
});

/**
 * Dynamically set redux sections for all the configured
 * mega menu items. Adds background fields
 * 
 * @param  string $opt_name the redux $opt_name
 * @return none
 */
function shrk_set_mmenu_bg_options( $opt_name ) {
	$fields = array();
	$mmenu_items = shrk_get_mmenu_items();

	if ( count( $mmenu_items ) ) {
		$fields[] = array(
			'id' => 'notice_info_mmenu_backgrounds',
			'type' => 'info',
			'notice' => true,
			'style' => 'info',
			'desc' => esc_html__('The menu items that have the \'Mega menu\' property checked are listed here so you can set a background image for each of them if you wish.', 'ux-shop'),
		);

		foreach ($mmenu_items as $menu_id => $menu_item) {
			$fields[] = array(
				'id'                => 'mmenu_bg_' . $menu_id,
				'type'              => 'background',
				'output'            => array('.site-navigation .menu-item-' . $menu_id . ' > .sub-menu'),
				'title'             => sprintf( esc_html__( 'Menu background for [%s]', 'ux-shop' ), $menu_item['menu_title'] ),
				'subtitle'          => sprintf( esc_html__( 'Menu item id: %d', 'ux-shop' ), $menu_id ),
				'desc'              => $menu_item['fullwidth'] == '1' ? esc_html__( 'In full-width menu items the background color is the same as the header\'s background color and cannot be set individually.', 'ux-shop' ) : NULL,
				'background-color'  => $menu_item['fullwidth'] == '0',
				'default'           => array(
					'background-size'       => 'cover',
					'background-attachment' => 'scroll',
					'background-position'   => 'center center',
					),
			);
		}

		Redux::setSection( $opt_name, array(
			'title' => esc_html__( 'Menu backgrounds', 'ux-shop'),
			'subsection' => true,
			'fields' => $fields
		) );	
	}
}

/**
 * Validation function for
 * unique values in 
 * multi_text fields
 */
function shrk_redux_multi_validate_unique( $field, $value, $existing_value ) {
	$error = false;

	if ( is_array( $value ) ) {
		$duplicates = array_diff_assoc($value, array_unique($value));
	}

	if ( !empty( $duplicates ) ) {
		$error = true;
		$value = $existing_value;
		$field['msg'] = esc_html__( 'Duplicate values not allowed.', 'ux-shop' );
	} 
	
	$return['value'] = $value;
	if ( $error == true ) {
	    $return['error'] = $field;
	}
	return $return;
}

/**
 * Remove Redux CSS output from wp_head
 * so it can be attached via wp_add_inline_style
 * to the theme style
 * 
 * @param  object $redux redux instance
 * @return none
 */
function shrk_redux_remove_css_output( $redux ) {
    remove_action( 'wp_head', array( &$redux, '_output_css' ), 150 );
}

/**
 * Get Redux dynamic CSS and attach it 
 * to the main theme style using wp_add_inline_style.
 *
 * Used _output_css from class ReduxFramework
 * $redux->outputCSS is ready after wp_enqueue_scripts:150
 * 
 * @return none
 */
function shrk_redux_add_custom_css() {
	if ( !class_exists( 'ReduxFrameworkInstances' ) ) return;

	$redux = ReduxFrameworkInstances::get_instance( 'shrk_theme_options' );
	if ( $redux->args['output'] == false && $redux->args['compiler'] == false ) {
	    return;
	}

	if ( isset ( $redux->no_output ) ) {
	    return;
	}

	if ( ! empty ( $redux->outputCSS ) && ( $redux->args['output_tag'] == true || ( isset ( $_POST['customized'] ) ) ) ) {
		// Fix for Redux messing up styles of typography assigned elements
		$redux_css = str_replace( 'opacity: 1;visibility: visible;-webkit-transition: opacity 0.24s ease-in-out;-moz-transition: opacity 0.24s ease-in-out;transition: opacity 0.24s ease-in-out;', ' ', $redux->outputCSS );
		$redux_css = shrk_simple_minify( $redux_css );
		wp_add_inline_style( 'shrk-style-overrides', $redux_css );
	}
}

/**
 * Return the value of the $columns_grid option (multi_bp_select)
 * with a max column of $limit_to and the 1st (min) set to $limit_to
 * 
 * @param  array $columns_grid The array of option values
 * @param  int   $limit_to     The column to limit/set
 * @return array               The filtered option values
 */
function shrk_redux_columns_grid_limited( $columns_grid, $limit_to ) {
	$limit_to = absint( $limit_to );

	for ($i=0; $i < count( $columns_grid ); $i++) { 
		$columns_grid[$i]['cols'] = ( $columns_grid[$i]['cols'] >= $limit_to ) || ( $i == 0 && $columns_grid[$i]['opr'] == 'min' ) ? (string) $limit_to : $columns_grid[$i]['cols'];
	}

	return $columns_grid;
}

?>