<?php
/**
 * @version    $Id$
 * @package    IT_Theme_Framework
 * @author     InnoThemes Team <support@innothemes.com>
 * @copyright  Copyright (C) 2012 InnoThemes.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Websites: http://www.innothemes.com
 */

if ( class_exists( 'WP_Customize_Control' ) ) {
	/**
	 * Theme customizer.
	 *
	 * @package  IT_Theme_Framework
	 * @since    1.0.0
	 */
	class IT_Theme_Customizer extends WP_Customize_Control {
		/**
		 * Define control type.
		 *
		 * @var  string
		 */
		public $type = 'it-theme-customizer';

		/**
		 * Array of theme options.
		 *
		 * @var  array
		 */
		protected static $options;

		/**
		 * Active profile.
		 *
		 * @var  string
		 */
		protected static $profile;

		/**
		 * Theme options need refresh for live preview.
		 *
		 * @var  array
		 */
		protected static $post_message = array( 'icon_favicon', 'icon_apple', 'google_analytics_id' );

		/**
		 * Hook into WordPress.
		 *
		 * @return  void
		 */
		public static function hook() {
			// Add actions
			static $registered;

			if ( ! isset( $registered ) ) {
				global $pagenow;

				if ( 'customize.php' == $pagenow ) {
					add_action( 'admin_enqueue_scripts', array( __CLASS__, 'admin_enqueue_scripts' ) );
				}

				// Register theme options
				add_action( 'customize_register', array( __CLASS__, 'customize_register' ) );

				// Load theme preview script
				add_action( 'customize_preview_init', array( __CLASS__, 'customize_preview_init' ) );

				$registered = true;
			}
		}

		/**
		 * Do 'admin_enqueue_scripts' action.
		 */
		public static function admin_enqueue_scripts() {
			// Load WordPress's media selector
			wp_enqueue_media();
		}

		/**
		 * Register theme options.
		 *
		 * @param   object  $wp_customize  WordPress's theme customizer object.
		 *
		 * @return  void
		 */
		public static function customize_register( $wp_customize ) {
			// Remove all default sections
			$sections = array( 'title_tagline', 'colors', 'header_image', 'background_image', 'nav', 'static_front_page' );

			foreach ( $sections as $section ) {
				$wp_customize->remove_section( $section );
			}

			// Remove all default settings
			$settings = array(
				'blogname', 'blogdescription', 'header_textcolor', 'background_color', 'header_image',
				'header_image_data', 'background_image', 'background_image_thumb', 'background_repeat',
				'background_position_x', 'background_attachment', 'show_on_front', 'page_on_front', 'page_for_posts',
			);

			foreach ( $settings as $setting ) {
				$wp_customize->remove_setting( $setting );
			}

			// Add new theme option to put our theme options panel in
			$wp_customize->add_section(
				IT_THEME_ID,
				array(
					'title'    => __( 'IT Theme Customizer', IT_THEME_TEXTDOMAIN ),
					'priority' => 30,
				)
			);

			// Add new setting to generate our theme options panel
			$wp_customize->add_setting(
				'it-theme-options',
				array(
					'transport' => 'postMessage',
				)
			);

			// Add new control to render HTML code for our theme options panel
			$control = new IT_Theme_Customizer(
				$wp_customize,
				'it-theme-options',
				array(
					'section'  => IT_THEME_ID,
					'settings' => 'it-theme-options',
				)
			);

			$wp_customize->add_control( $control );

			// Prepare theme options
			self::$options = IT_Theme_Options::prepare( true );

			foreach ( self::$options['fields'] as $key => $define ) {
				// Preset option id
				$option_id = $key;

				// Check if profile is enabled
				if ( 'profile' == $key ) {
					// Get active profile
					if ( ! isset( self::$profile ) ) {
						if ( isset( $_GET['it-profile'] ) ) {
							self::$profile = $_GET['it-profile'];
						} else {
							self::$profile = get_theme_mod( 'profile', self::$options['fields']['profile']['default'] );
						}
					}
				}

				// Check if profile is enabled for this option
				if ( isset( $define['enable_profile'] ) && $define['enable_profile'] ) {
					// Add hidden settings for inactive profiles
					foreach ( array_keys( self::$options['fields']['profile']['choices'] ) as $profile ) {
						if ( $profile != self::$profile ) {
							// Alter option id
							$option_id = "{$key}_{$profile}";

							// Get profile value
							$default = isset( $define['default'] ) ? $define['default'] : null;

							if ( is_array( $define['enable_profile'] ) && isset( $define['enable_profile'][ $profile ] ) ) {
								$default = $define['enable_profile'][ $profile ];
							}

							$value = get_theme_mod( $option_id, $default );

							// Add hidden settings
							if ( null != $value || $value != $default ) {
								$wp_customize->add_setting(
									$option_id,
									array(
										'default' => $value,
									)
								);
							}
						}
					}

					// Reset option id
					$option_id = "{$key}_" . self::$profile;

					// Override option name
					self::$options['fields'][ $key ]['name'] = $option_id;
				}

				// Get option value
				$default = isset( $define['default'] ) ? $define['default'] : null;

				if ( @is_array( $define['enable_profile'] ) && isset( $define['enable_profile'][ self::$profile ] ) ) {
					$default = $define['enable_profile'][ self::$profile ];
				}

				if ( 'profile' == $key ) {
					$value = self::$profile;
				} else {
					$value = get_theme_mod( $option_id, $default );
				}

				// Add setting for theme option
				$wp_customize->add_setting(
					$option_id,
					array(
						'default'   => $value,
						'transport' => in_array( $key, self::$post_message ) ? 'postMessage' : 'refresh'
					)
				);

				// Prepare field for using with WordPress's Theme Customizer
				self::$options['fields'][ $key ]['value'] = $value;

				if ( isset( self::$options['fields'][ $key ]['attributes'] ) ) {
					self::$options['fields'][ $key ]['attributes']['data-customize-setting-link'] = $option_id;
				} else {
					self::$options['fields'][ $key ]['attributes'] = array( 'data-customize-setting-link' => $option_id );
				}

				if ( 'social-channels' == $define['type'] && ! isset( $social_channels_setting_added ) ) {
					// Add setting for social channels configuration
					$value = get_theme_mod( 'it_social_channels', array() );

					if ( ! count( $value ) && isset( $define['social_channels'] ) ) {
						foreach ( $define['social_channels'] as $name => $data ) {
							$value[ $name ] = isset( $data['link'] ) ? $data['link'] : '';
						}
					}

					$wp_customize->add_setting(
						'it_social_channels',
						array(
							'default'   => $value,
							'transport' => in_array( 'it_social_channels', self::$post_message ) ? 'postMessage' : 'refresh'
						)
					);

					$social_channels_setting_added = true;
				}
			}

			// Manipulate DOM tree
			add_action( 'customize_controls_print_footer_scripts', array( __CLASS__, 'customize_controls_print_footer_scripts' ) );
		}

		/**
		 * Remove unnecessary elements from DOM tree.
		 *
		 * @return  void
		 */
		public static function customize_controls_print_footer_scripts() {
			echo '
<style type="text/css">
	#customize-theme-controls.it-loading {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background: #fff url(' . IT_THEME_URI . '/assets/innothemes/images/icons-32/icon-32-loading-circle.gif) 50% 50% no-repeat !important;
	}
</style>
<script type="text/javascript">
(function($) {
	$("#customize-info, #customize-theme-controls > ul > li > h3").remove();
	$("#customize-theme-controls").addClass("it-loading").append($("#customize-theme-controls > ul > li > ul > li").children().addClass("hide hidden"));
	$("#customize-theme-controls > ul").remove();
	$(window).load(function() {
		$("#customize-theme-controls").removeClass("it-loading").children().removeClass("hide hidden");
	});
})(jQuery);
</script>';
		}

		/**
		 * Load theme preview script.
		 *
		 * @return  void
		 */
		public static function customize_preview_init() {
			/*wp_enqueue_script(
				'it-theme-customizer',
				IT_THEME_URI . '/assets/innothemes/js/theme-customizer.js',
				array( 'customize-preview' ),
				'1.0.0',
				true
			);*/
		}

		/**
		 * Render theme options panel.
		 *
		 * @return  void
		 */
		public function render_content() {
			// Register action to finalize form rendering
			add_action( 'it_post_render_form', array( __CLASS__, 'load_assets' ) );

			// Init form renderer
			$form = IT_Form::get_instance( 'it-theme-options', self::$options );

			// Get form section to render
			$section = null;

			if ( defined( 'IT_USE_AJAX' ) && IT_USE_AJAX ) {
				$sections = array_keys( self::$options['sections'] );
				$section  = isset( $_GET['section'] ) ? $_GET['section'] : array_shift( $sections );
			}

			// Render HTML form
			$form->render( 'theme-options', array( 'tabs', 'accordions' ), $section );
		}

		/**
		 * Load necessary assets.
		 *
		 * @return  void
		 */
		public static function load_assets() {
			IT_Init_Assets::load(
				array(
					// jQuery UI Dialog
					'jquery-ui-dialog', 'wp-jquery-ui-dialog-css',

					// Override WordPress's Theme Customizer
					'it-theme-admin-css', 'it-theme-admin-js',
				)
			);
		}
	}
}
