<?php

add_action( 'widgets_init', 'wft_register_general_widgets' );
function wft_register_general_widgets() {
	register_widget('WFT_StaticBlock_Widget');
	register_widget('WFT_Nav_Menu_Widget');

	// WooCommerce widgets
	if ( class_exists( 'WooCommerce' ) ) {
		register_widget('WFT_Widget_Product_Categories');
		register_widget('WFT_Widget_Cart');
	}

	// WPML widgets
	if ( class_exists('woocommerce_wpml') ) {
		register_widget('WFT_Language_selector_widget');
		register_widget('WFT_WPML_Currency_Switcher_Widget');
	}

	// Social Login Widget
	if ( function_exists('wsl_activate') ) {
		register_widget('WFT_Social_Login_Widget');
	}

}

// **********************************************************************// 
// ! Recent posts Widget
// **********************************************************************// 
class WFT_StaticBlock_Widget extends WP_Widget {

    function __construct() {
        $widget_ops = array('classname' => 'wft_widget_satic_block', 'description' => __( "Insert static block, that you've created earlier.", WFT_DOMAIN) );
        $this->WP_Widget('wft-static-block', __('Static Block', WFT_DOMAIN), $widget_ops);
        $this->alt_option_name = 'wft_widget_static_block';
    }

    function widget($args, $instance) {
        extract($args);

        $block_id = $instance['block_id'];
        
        et_show_block($block_id);

    }

    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        $instance['block_id'] = $new_instance['block_id'];

        return $instance;
    }

    function form( $instance ) {
        $block_id = 0;
        if(!empty($instance['block_id']))
            $block_id = esc_attr($instance['block_id']);

?>
        <p><label for="<?php echo $this->get_field_id('block_id'); ?>"><?php _e('Block name:', WFT_DOMAIN); ?></label>
            <?php $sb = et_get_static_blocks(); ?>
            <select name="<?php echo $this->get_field_name('block_id'); ?>" id="<?php echo $this->get_field_id('block_id'); ?>">
                <option>--Select--</option>
                <?php if (count($sb > 0)): ?>
                    <?php foreach ($sb as $key): ?>
                        <option value="<?php echo $key['value']; ?>" <?php selected( $block_id, $key['value'] ); ?>><?php echo $key['label'] ?></option>
                    <?php endforeach ?>
                <?php endif ?>
            </select>
        </p>
<?php
    }
}


// WFT Widgets
class WFT_Language_selector_widget extends WP_Widget {

	public function __construct() {
		// указываем в конструкторе общие настройки которые будут видны в админке
		// название и описание виджета
		$widget_ops = array(
			'classname' => 'sidebar-box',
			'description' => __( "WPML Language selector for your site", WFT_DOMAIN) );
		parent::__construct('wft_lang_sel_widget','WFT Language Selector', $widget_ops);
		$this->alt_option_name = 'wft_lang_sel_widget';

		// при сохранении поста или удалении поста, а так же при смене темы
		// кеш виджета будет очищаться
		add_action( 'save_post', array(&$this, 'flush_widget_cache') );
		add_action( 'deleted_post', array(&$this, 'flush_widget_cache') );
		add_action( 'switch_theme', array(&$this, 'flush_widget_cache') );
	}

	// этот метод срабатывает непосредственно при выводе выджета на странице
	function widget($args, $instance) {

		// загружаем кеш, если есть кеш для данного виджета выводим его и выходим
		$cache = wp_cache_get('wft_lang_sel_widget', 'widget');

		global $wpdb;

		if ( !is_array($cache) ) {
			$cache = array();
		}

		if ( ! isset( $args['widget_id'] ) ) {
			$args['widget_id'] = $this->id;
		}

		if ( isset( $cache[ $args['widget_id'] ] ) ) {
			echo $cache[ $args['widget_id'] ];
			return;
		}

		extract($args);

		if ( function_exists('is_plugin_active') && is_plugin_active( 'woocommerce-multilingual/wpml-woocommerce.php' ) ) {

			ob_start();

			$langs = icl_get_languages('skip_missing=N&orderby=KEY&order=DIR&link_empty_to=str');

			if ( !isset($no_wrapper) || !$no_wrapper ) {
				echo $before_widget;
			}

			if ( isset($title) && $title ) {
				echo $before_title . $title . $after_title;
			}

			echo '<span class="link_label">'. __('Language', WFT_DOMAIN) . ':</span>';

			echo '<div class="fadelink">';

			echo '<a href="#">'.$langs[ICL_LANGUAGE_CODE]['native_name'].'</a>';

			echo '<div class="ul_wrapper" style="display: none; opacity: 1;"><ul>';

			foreach ( $langs as $lang ) {
				echo '<li><img alt="" src="'. $lang['country_flag_url'] . '"><a href="'. $lang['url'] . '">' . $lang['native_name'] . '</a></li>';
			}

			echo '</ul></div></div>';

			if ( !isset($no_wrapper) || !$no_wrapper ) {
				echo $after_widget;
			}

			// сохраняем кеш
			$cache[$args['widget_id']] = ob_get_flush();
			wp_cache_set('wft_lang_sel_widget', $cache, 'widget');
		} else {

			if ( !isset($no_wrapper) || !$no_wrapper ) {
				echo $before_widget;
			}

			if ( $title ) {
				echo $before_title . $title . $after_title;
			}

			echo __('Language switcher disabled. WPML plugin is not active.', WFT_DOMAIN);

			if ( !isset($no_wrapper) || !$no_wrapper ) {
				echo $after_widget;
			}

		}


	}

	function flush_widget_cache() {
		wp_cache_delete('wft_lang_sel_widget', 'widget');
	}

}


class WFT_Widget_Cart extends WP_Widget {

	var $woo_widget_cssclass;
	var $woo_widget_description;
	var $woo_widget_idbase;
	var $woo_widget_name;

	/**
	 * constructor
	 *
	 * @access public
	 * @return void
	 */
	public function __construct() {

		/* Widget variable settings. */
		$this->woo_widget_cssclass 		= 'woocommerce widget_shopping_cart';
		$this->woo_widget_description 	= __( "Display the user's Cart in the sidebar.", 'woocommerce' );
		$this->woo_widget_idbase 		= 'woocommerce_widget_cart';
		$this->woo_widget_name 			= __( 'WFT WooCommerce Cart', 'woocommerce' );

		/* Widget settings. */
		$widget_ops = array( 'classname' => $this->woo_widget_cssclass, 'description' => $this->woo_widget_description );

		/* Create the widget. */
		$this->WP_Widget( 'shopping_cart', $this->woo_widget_name, $widget_ops );
	}


	/**
	 * widget function.
	 *
	 * @see WP_Widget
	 * @access public
	 * @param array $args
	 * @param array $instance
	 * @return void
	 */
	function widget( $args, $instance ) {

		global $woocommerce;

		extract( $args );

		$title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Cart', 'woocommerce' ) : $instance['title'], $instance, $this->id_base );
		$hide_if_empty = empty( $instance['hide_if_empty'] ) ? 0 : 1;

		echo $before_widget;

		?>

		<div class="shoppingcart">
			<div class="fadelink">
				<span class="pull-right">
					<a class="btn" href="<?php echo $woocommerce->cart->get_cart_url(); ?>">
						<i class="icon-basket icon-large"></i>
					</a>
				</span>
				<span class="badge badge-inverse"><?php echo count($woocommerce->cart->get_cart()) ?></span>
				<div class="shopping_cart_mini hidden-phone hidden-tablet widget_shopping_cart_content" style="display: none;">
				</div>
			</div>
		</div>

		<?php

		echo $after_widget;


	}


	/**
	 * update function.
	 *
	 * @see WP_Widget->update
	 * @access public
	 * @param array $new_instance
	 * @param array $old_instance
	 * @return array
	 */
	function update( $new_instance, $old_instance ) {
		$instance['title'] = strip_tags( stripslashes( $new_instance['title'] ) );
		$instance['hide_if_empty'] = empty( $new_instance['hide_if_empty'] ) ? 0 : 1;
		return $instance;
	}


	/**
	 * form function.
	 *
	 * @see WP_Widget->form
	 * @access public
	 * @param array $instance
	 * @return void
	 */
	function form( $instance ) {
		$hide_if_empty = empty( $instance['hide_if_empty'] ) ? 0 : 1;
		?>
		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:', 'woocommerce' ) ?></label>
			<input type="text" class="widefat" id="<?php echo esc_attr( $this->get_field_id('title') ); ?>" name="<?php echo esc_attr( $this->get_field_name('title') ); ?>" value="<?php if (isset ( $instance['title'])) {echo esc_attr( $instance['title'] );} ?>" /></p>

		<p><input type="checkbox" class="checkbox" id="<?php echo esc_attr( $this->get_field_id('hide_if_empty') ); ?>" name="<?php echo esc_attr( $this->get_field_name('hide_if_empty') ); ?>"<?php checked( $hide_if_empty ); ?> />
			<label for="<?php echo $this->get_field_id('hide_if_empty'); ?>"><?php _e( 'Hide if cart is empty', 'woocommerce' ); ?></label></p>
	<?php
	}

}


class WFT_Social_Login_Widget extends WP_Widget {

	public $widget_cssclass;
	public $widget_description;
	public $widget_idbase;
	public $widget_name;

	public function __construct() {

		/* Widget variable settings. */
		$this->widget_cssclass 		= '';
		$this->widget_description 	= __( "Let users login to your site using social network accounts.", 'wordpress' );
		$this->widget_idbase 		= 'wft_social_login_widget';
		$this->widget_name 			= __( 'WFT Social Login', 'wordpress' );

		/* Widget settings. */
		$widget_ops = array( 'classname' => $this->widget_cssclass, 'description' => $this->widget_description );

		/* Create the widget. */
		$this->WP_Widget( 'wft_social_login_widget', $this->widget_name, $widget_ops );
	}

	/**
	 * widget function.
	 *
	 * @see WP_Widget
	 * @access public
	 * @param array $args
	 * @param array $instance
	 * @return void
	 */
	public function widget( $args, $instance ) {

		if ( !function_exists('is_plugin_active') || ! is_plugin_active( 'wordpress-social-login/wp-social-login.php' ) ) {
			return;
		}

		global $woocommerce;

		extract( $args );

		echo $before_widget;

		do_shortcode('[wordpress_social_login]');

		echo $after_widget;

	}

}


class WFT_WPML_Currency_Switcher_Widget extends WP_Widget {

	public $widget_cssclass;
	public $widget_description;
	public $widget_idbase;
	public $widget_name;

	public function __construct() {

		/* Widget variable settings. */
		$this->widget_cssclass 		= '';
		$this->widget_description 	= __( 'Allows your customers to switch currency using WPML Plugin "Woocommerce Multilingual"', 'woocommerce' );
		$this->widget_idbase 		= 'wft_wpml_currency_switcher_widget';
		$this->widget_name 			= __( 'WFT WPML Currency Switcher', 'woocommerce' );

		/* Widget settings. */
		$widget_ops = array( 'classname' => $this->widget_cssclass, 'description' => $this->widget_description );

		/* Create the widget. */
		$this->WP_Widget( 'wft_wpml_currency_switcher_widget', $this->widget_name, $widget_ops );
	}

	/**
	 * widget function.
	 *
	 * @see WP_Widget
	 * @access public
	 * @param array $args
	 * @param array $instance
	 * @return void
	 */
	public function widget( $args, $instance ) {

		if ( !function_exists('is_plugin_active') || ! is_plugin_active( 'woocommerce-multilingual/wpml-woocommerce.php' ) ) {
			return;
		}

		global $woocommerce;

		extract( $args );

		echo $before_widget;

		do_shortcode('[wft_wpml_currency_switcher]');

		echo $after_widget;

	}

}

/**
 * Navigation Menu widget class
 *
 * @since 3.0.0
 */
class WFT_Nav_Menu_Widget extends WP_Widget {

	function __construct() {
		$widget_ops = array( 'description' => __('Use this widget to add one of your custom menus as a widget.', WFT_DOMAIN) );
		parent::__construct( 'wft_nav_menu', __('WFT Custom Menu', WFT_DOMAIN), $widget_ops );
	}

	function widget($args, $instance) {
		// Get menu
		$nav_menu = ! empty( $instance['nav_menu'] ) ? wp_get_nav_menu_object( $instance['nav_menu'] ) : false;

		if ( !$nav_menu ) {
			return;
		}

		$instance['title'] = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );

		echo $args['before_widget'];

		if ( !empty($instance['title']) ) {
			echo $args['before_title'] . $instance['title'] . $args['after_title'];
		}

		$atts = array(
			'fallback_cb' => '',
			'menu' => $nav_menu,
			'menu_class' => ( isset($instance['menu_class']) ? $instance['menu_class'] : 'nav sidenav' ),
			'walker' => new Et_Navigation
		);

		//wp_nav_menu( array( 'fallback_cb' => '', 'menu' => $nav_menu ) );
		wft_wp_nav_menu($atts);

		echo $args['after_widget'];
	}

	function update( $new_instance, $old_instance ) {
		$instance['title'] = strip_tags( stripslashes($new_instance['title']) );
		$instance['nav_menu'] = (int) $new_instance['nav_menu'];
		return $instance;
	}

	function form( $instance ) {
		$title = isset( $instance['title'] ) ? $instance['title'] : '';
		$nav_menu = isset( $instance['nav_menu'] ) ? $instance['nav_menu'] : '';

		// Get menus
		$menus = wp_get_nav_menus( array( 'orderby' => 'name' ) );

		// If no menus exists, direct the user to go and create some.
		if ( !$menus ) {
			echo '<p>'. sprintf( __('No menus have been created yet. <a href="%s">Create some</a>.', WFT_DOMAIN), admin_url('nav-menus.php') ) .'</p>';
			return;
		}
		?>
		<p>
			<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', WFT_DOMAIN) ?></label>
			<input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $title; ?>" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('nav_menu'); ?>"><?php _e('Select Menu:', WFT_DOMAIN); ?></label>
			<select id="<?php echo $this->get_field_id('nav_menu'); ?>" name="<?php echo $this->get_field_name('nav_menu'); ?>">
				<?php
				foreach ( $menus as $menu ) {
					echo '<option value="' . $menu->term_id . '"'
						. selected( $nav_menu, $menu->term_id, false )
						. '>'. $menu->name . '</option>';
				}
				?>
			</select>
		</p>
	<?php
	}
}

class WFT_Widget_Product_Categories extends WP_Widget {

	var $woo_widget_cssclass;
	var $woo_widget_description;
	var $woo_widget_idbase;
	var $woo_widget_name;
	var $cat_ancestors;
	var $current_cat;

	/**
	 * constructor
	 *
	 * @access public
	 * @return void
	 */
	function __construct() {

		/* Widget variable settings. */
		$this->woo_widget_cssclass = 'woocommerce widget_product_categories';
		$this->woo_widget_description = __( 'A list or dropdown of product categories.', 'woocommerce' );
		$this->woo_widget_idbase = 'woocommerce_product_categories';
		$this->woo_widget_name = __( 'WFT WooCommerce Product Categories', 'woocommerce' );

		/* Widget settings. */
		$widget_ops = array( 'classname' => $this->woo_widget_cssclass, 'description' => $this->woo_widget_description );

		/* Create the widget. */
		$this->WP_Widget('product_categories', $this->woo_widget_name, $widget_ops);
	}


	/**
	 * widget function.
	 *
	 * @see WP_Widget
	 * @access public
	 * @param array $args
	 * @param array $instance
	 * @return void
	 */
	function widget( $args, $instance ) {
		extract( $args );

		$title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Product Categories', 'woocommerce' ) : $instance['title'], $instance, $this->id_base);
		$c = $instance['count'] ? '1' : '0';
		$h = $instance['hierarchical'] ? true : false;
		$s = (isset($instance['show_children_only']) && $instance['show_children_only']) ? '1' : '0';
		$d = $instance['dropdown'] ? '1' : '0';
		$o = isset($instance['orderby']) ? $instance['orderby'] : 'order';

		echo $before_widget;
		if ( $title ) echo $before_title . $title . $after_title;

		$cat_args = array( 'show_count' => $c, 'hierarchical' => $h, 'taxonomy' => 'product_cat' );

		$cat_args['menu_order'] = false;

		if ( $o == 'order' ) {

			$cat_args['menu_order'] = 'asc';

		} else {

			$cat_args['orderby'] = 'title';

		}

		if ( $d ) {

			// Stuck with this until a fix for http://core.trac.wordpress.org/ticket/13258
			woocommerce_product_dropdown_categories( $c, $h, 0, $o );

			?>
			<script type='text/javascript'>
				/* <![CDATA[ */
				var product_cat_dropdown = document.getElementById("dropdown_product_cat");
				function onProductCatChange() {
					if ( product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value !=='' ) {
						location.href = "<?php echo home_url(); ?>/?product_cat="+product_cat_dropdown.options[product_cat_dropdown.selectedIndex].value;
					}
				}
				product_cat_dropdown.onchange = onProductCatChange;
				/* ]]> */
			</script>
		<?php

		} else {

			global $wp_query, $post, $woocommerce;

			$this->current_cat = false;
			$this->cat_ancestors = array();

			if ( is_tax('product_cat') ) {

				$this->current_cat = $wp_query->queried_object;
				$this->cat_ancestors = get_ancestors( $this->current_cat->term_id, 'product_cat' );

			} elseif ( is_singular('product') ) {

				$product_category = wc_get_product_terms( $post->ID, 'product_cat', array( 'orderby' => 'parent' ) );

				if ( $product_category ) {
					$this->current_cat   = end( $product_category );
					$this->cat_ancestors = get_ancestors( $this->current_cat->term_id, 'product_cat' );
				}

			}

			$cat_args['walker'] 			= new WFT_Product_Cat_List_Walker;
			$cat_args['title_li'] 			= '';
			$cat_args['show_children_only']	= ( isset( $instance['show_children_only'] ) && $instance['show_children_only'] ) ? 1 : 0;
			$cat_args['pad_counts'] 		= 1;
			$cat_args['show_option_none'] 	= __('No product categories exist.', 'woocommerce' );
			$cat_args['current_category']	= ( $this->current_cat ) ? $this->current_cat->term_id : '';
			$cat_args['current_category_ancestors']	= $this->cat_ancestors;

			echo '<ul class="product-categories collapsed-menu">';

			wp_list_categories( apply_filters( 'woocommerce_product_categories_widget_args', $cat_args ) );

			echo '</ul>';

		}

		echo $after_widget;
	}


	/**
	 * update function.
	 *
	 * @see WP_Widget->update
	 * @access public
	 * @param array $new_instance
	 * @param array $old_instance
	 * @return array
	 */
	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['orderby'] = strip_tags($new_instance['orderby']);
		$instance['count'] = !empty($new_instance['count']) ? 1 : 0;
		$instance['hierarchical'] = !empty($new_instance['hierarchical']) ? true : false;
		$instance['dropdown'] = !empty($new_instance['dropdown']) ? 1 : 0;
		$instance['show_children_only'] = !empty($new_instance['show_children_only']) ? 1 : 0;

		return $instance;
	}


	/**
	 * form function.
	 *
	 * @see WP_Widget->form
	 * @access public
	 * @param array $instance
	 * @return void
	 */
	function form( $instance ) {
		//Defaults
		$instance = wp_parse_args( (array) $instance, array( 'title' => '') );
		$title = esc_attr( $instance['title'] );
		$orderby = isset( $instance['orderby'] ) ? $instance['orderby'] : 'order';
		$count = isset($instance['count']) ? (bool) $instance['count'] :false;
		$hierarchical = isset( $instance['hierarchical'] ) ? (bool) $instance['hierarchical'] : false;
		$dropdown = isset( $instance['dropdown'] ) ? (bool) $instance['dropdown'] : false;
		$show_children_only = isset( $instance['show_children_only'] ) ? (bool) $instance['show_children_only'] : false;
		?>
		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:', 'woocommerce' ); ?></label>
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id('title') ); ?>" name="<?php echo esc_attr( $this->get_field_name('title') ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></p>

		<p><label for="<?php echo $this->get_field_id('orderby'); ?>"><?php _e( 'Order by:', 'woocommerce' ) ?></label>
			<select id="<?php echo esc_attr( $this->get_field_id('orderby') ); ?>" name="<?php echo esc_attr( $this->get_field_name('orderby') ); ?>">
				<option value="order" <?php selected($orderby, 'order'); ?>><?php _e( 'Category Order', 'woocommerce' ); ?></option>
				<option value="name" <?php selected($orderby, 'name'); ?>><?php _e( 'Name', 'woocommerce' ); ?></option>
			</select></p>

		<p><input type="checkbox" class="checkbox" id="<?php echo esc_attr( $this->get_field_id('dropdown') ); ?>" name="<?php echo esc_attr( $this->get_field_name('dropdown') ); ?>"<?php checked( $dropdown ); ?> />
			<label for="<?php echo $this->get_field_id('dropdown'); ?>"><?php _e( 'Show as dropdown', 'woocommerce' ); ?></label><br />

			<input type="checkbox" class="checkbox" id="<?php echo esc_attr( $this->get_field_id('count') ); ?>" name="<?php echo esc_attr( $this->get_field_name('count') ); ?>"<?php checked( $count ); ?> />
			<label for="<?php echo $this->get_field_id('count'); ?>"><?php _e( 'Show post counts', 'woocommerce' ); ?></label><br />

			<input type="checkbox" class="checkbox" id="<?php echo esc_attr( $this->get_field_id('hierarchical') ); ?>" name="<?php echo esc_attr( $this->get_field_name('hierarchical') ); ?>"<?php checked( $hierarchical ); ?> />
			<label for="<?php echo $this->get_field_id('hierarchical'); ?>"><?php _e( 'Show hierarchy', 'woocommerce' ); ?></label><br/>

			<input type="checkbox" class="checkbox" id="<?php echo esc_attr( $this->get_field_id('show_children_only') ); ?>" name="<?php echo esc_attr( $this->get_field_name('show_children_only') ); ?>"<?php checked( $show_children_only ); ?> />
			<label for="<?php echo $this->get_field_id('show_children_only'); ?>"><?php _e( 'Only show children for the current category', 'woocommerce' ); ?></label></p>
	<?php
	}

}