<?php
/**
* Registers options with the Theme Customizer
*
* @param object $wp_customize The WordPress Theme Customizer
* @package bloomy
* @since 1.0
*/

$bloomy_customizer_dir = get_template_directory() .'/inc/customizer/';

/**
 * Sets up the WordPress core custom header and custom background features.
 *
 * @since Bloomy 1.0
 *
 * @see bloomy_header_style()
 */
function bloomy_custom_header_and_background() {

	/**
	 * Filter the arguments used when adding 'custom-background' support in Bloomy.
	 *
	 * @since Bloomy 1.0
	 *
	 * @param array $args {
	 *     An array of custom-background support arguments.
	 *
	 *     @type string $default-color Default color of the background.
	 * }
	 */
	add_theme_support( 'custom-background', apply_filters( 'min_custom_background_args', array(
		'default-color' => 'F9F9F9',
	) ) );

	/**
	 * Filter the arguments used when adding 'custom-header' support in Bloomy.
	 *
	 * @since Bloomy 1.0
	 *
	 * @param array $args {
	 *     An array of custom-header support arguments.
	 *
	 *     @type string $default-text-color Default color of the header text.
	 *     @type callable $wp-head-callback Callback function used to style the header image and text
	 *                                      displayed on the blog.
	 * }
	 */
	add_theme_support( 'custom-header', apply_filters( 'bloomy_custom_header_args', array(
		'default-text-color' => '#2a2c2b',
		'wp-head-callback'   => 'bloomy_header_style',
	) ) );
}
add_action( 'after_setup_theme', 'bloomy_custom_header_and_background' );

if ( ! function_exists( 'bloomy_header_style' ) ) :
/**
 * Styles the header text displayed on the site.
 *
 * Create your own bloomy_header_style() function to override in a child theme.
 *
 * @since Bloomy 1.0
 *
 * @see bloomy_custom_header_and_background().
 */
function bloomy_header_style() {
	// If the header text option is untouched, let's bail.
	if ( display_header_text() ) {
		return;
	}

	// If the header text has been hidden.
	?>
	<style type="text/css" id="bloomy-header-css">
		.logo-wrap #logo,
		.site-description {
			clip: rect(1px, 1px, 1px, 1px);
            left: 0;
			position: absolute;
		}
	</style>
	<?php
}
endif; // bloomy_header_style

function bloomy_get_categories_select() {
 $the_cats = get_categories();
    $results;
    $count = count($the_cats);
    for ( $i=0; $i < $count; $i++ ) {
      if ( isset( $the_cats[$i] ) )
        $results[$the_cats[$i]->slug] = $the_cats[$i]->name;
      else
        $count++;
    }
  return $results;
}

function bloomy_register_theme_customizer( $wp_customize ) {

    $bloomy_customizer_dir = get_template_directory() .'/inc/customizer/';
    
    $wp_customize->get_setting( 'blogname' )->transport         = 'postMessage';
	$wp_customize->get_setting( 'blogdescription' )->transport  = 'postMessage';

	if ( isset( $wp_customize->selective_refresh ) ) {
		$wp_customize->selective_refresh->add_partial( 'blogname', array(
			'selector'            => '.logo a',
			'container_inclusive' => false,
			'render_callback'     => 'bloomy_customize_partial_blogname',
		) );
		$wp_customize->selective_refresh->add_partial( 'blogdescription', array(
			'selector'            => '.tagline',
			'container_inclusive' => false,
			'render_callback'     => 'bloomy_customize_partial_blogdescription',
		) );
	}
	
	// Custom Divide Control
	class Bloomy_Customize_Divide_Control extends WP_Customize_Control {
		public $type = 'divide';
	 
		public function render_content() {
			?>
				<h3 class="customize-divide"><?php echo esc_html( $this->label ); ?></h3>
			<?php
		}
	}
	
	// Custom Layout Control
	class Bloomy_Layout_Picker_Custom_Control extends WP_Customize_Control {
		  /**
		   * Render the content on the theme customizer page
		   */
		public function render_content() {
			?>
			<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
			<ul>
				<?php
				foreach ( $this->choices as $key => $value ) {
					?>
					<li class="customizer-control-row">
				        <input type="radio" value="<?php echo esc_attr( $key ) ?>" name="<?php echo esc_attr( $this->id ); ?>" <?php echo esc_attr( $this->link() ); ?> <?php if( $this->value() === $key ) echo 'checked="checked"'; ?>>
						<label for="<?php echo esc_attr( $key ) ?>"></label>
					</li>
					<?php
				}
				?>
			</ul>
			<?php
		}
	}
} // end bloomy_register_theme_customizer
add_action( 'customize_register', 'bloomy_register_theme_customizer' );
 
/**
 * Render the site title for the selective refresh partial.
 *
 * @since Bloomy 1.0
 * @see bloomy_register_theme_customizer()
 *
 * @return void
 */
function bloomy_customize_partial_blogname() {
    bloginfo( 'name' );
}

/**
 * Render the site tagline for the selective refresh partial.
 *
 * @since Bloomy 1.0
 * @see bloomy_register_theme_customizer()
 *
 * @return void
 */
function bloomy_customize_partial_blogdescription() {
    bloginfo( 'description' );
}

// Customizer Panels
//--------------------------------------------//
require get_template_directory() . '/inc/customizer/panels.php';

// Customizer Sections
//--------------------------------------------//
require get_template_directory() . '/inc/customizer/sections.php';

// Customizer Settings
//--------------------------------------------//
require get_template_directory() . '/inc/customizer/settings.php';

// Include Fonts
//--------------------------------------------//
require get_template_directory() . '/inc/customizer/fonts.php';

/**
 * Registers customizer settings and controls.
 *
 * @since Bloomy 1.0
 *
 */
function bloomy_customizer_settings_register($wp_customize) {
    $fields = array();
    $fields = apply_filters( 'bloomy_customizer_settings_register', $fields );
    
    foreach ( $fields as $field ) {
		$wp_customize->add_setting( $field[ 'id' ], array(
			'default'           => empty( $field[ 'default' ] ) ? null : $field[ 'default' ],
			'type'              => empty( $field[ 'type' ] ) ? null : $field[ 'type' ],
			'capability'        => empty( $field[ 'capability' ] ) ? 'edit_theme_options' : $field[ 'capability' ],
			'transport'         => empty( $field[ 'transport' ] ) ? null : $field[ 'transport' ],
			'sanitize_callback' => empty( $field[ 'sanitize_callback' ] ) ? null : $field[ 'sanitize_callback' ],
		) );
        
        if ( 'color' === $field[ 'control' ] ) {
			$wp_customize->add_control(
                new WP_Customize_Color_Control( $wp_customize, $field['id'], array(
					'label'           => empty( $field[ 'label' ] ) ? null : $field[ 'label' ],
					'description'     => empty( $field[ 'description' ] ) ? null : $field[ 'description' ],
					'section'         => empty( $field[ 'section' ] ) ? null : $field[ 'section' ],
					'settings'        => $field['id'],
					'active_callback' => empty( $field[ 'active_callback' ] ) ? null : $field[ 'active_callback' ],
				)
			) );
		} elseif ( 'layout' === $field[ 'control' ] ) {
            $wp_customize->add_control(
                new Bloomy_Layout_Picker_Custom_Control ( $wp_customize, $field['id'], array(
                    'label'           => empty( $field[ 'label' ] ) ? null : $field[ 'label' ],
                    'section'         => empty( $field[ 'section' ] ) ? null : $field[ 'section' ],
                    'settings'        => $field['id'],
                    'choices'         => $field['choices'],
                )
            ) );
		} elseif ( 'divide' === $field[ 'control' ] ) {
            $wp_customize->add_control(
                new Bloomy_Customize_Divide_Control ( $wp_customize, $field['id'], array(
                    'label'           => empty( $field[ 'label' ] ) ? null : $field[ 'label' ],
                    'section'         => empty( $field[ 'section' ] ) ? null : $field[ 'section' ],
                    'settings'        => $field['id'],
                )
            ) );
		} elseif ( 'image' === $field[ 'control' ] ) {
            $wp_customize->add_control(
                new WP_Customize_Image_Control ( $wp_customize, $field['id'], array(
                    'label'           => empty( $field[ 'label' ] ) ? null : $field[ 'label' ],
                    'section'         => empty( $field[ 'section' ] ) ? null : $field[ 'section' ],
                    'settings'        => $field['id'],
                )
            ) );
		} else {
            $wp_customize->add_control( $field[ 'id' ], array(
                'type'            => empty( $field[ 'control' ] ) ? null : $field[ 'control' ],
                'section'         => empty( $field[ 'section' ] ) ? null : $field[ 'section' ],
                'default'         => empty( $field[ 'default' ] ) ? 0 : $field[ 'default' ],
                'settings'        => $field['id'],
                'label'           => empty( $field[ 'label' ] ) ? null : $field[ 'label' ],
                'description'     => empty( $field[ 'description' ] ) ? null : $field[ 'description' ],
                'choices'         => empty( $field[ 'choices' ] ) ? null : $field[ 'choices' ],
                'input_attrs'     => empty( $field[ 'input_attrs' ] ) ? null : $field[ 'input_attrs' ],
                'active_callback' => empty( $field[ 'active_callback' ] ) ? null : $field[ 'active_callback' ],
            ) );
        }
    }
    
    if ( $wp_customize->is_preview() && ! is_admin() ) {
        add_action( 'wp_footer', 'bloomy_customize_preview', 21);
    }
}
add_action( 'customize_register', 'bloomy_customizer_settings_register' );

function bloomy_customize_preview() {
    ?>
    <script type="text/javascript">
    ( function( $ ){
 
        wp.customize( 'color_scheme_1', function( value ) {
            value.bind( function( to ) {
 
                var style, el;
 
                // build the style element
                style = '<style class="hover-styles">a, a:hover, .featuredslider .read-more, .read-more a, .total-post, .articles-count, .comment-form .submit, #wp-calendar caption, #wp-calendar tbody td a { color: ' + to + '; } .menu-btn, .search-button, .pagination .current, .pagination a:hover, .comment-form .submit:hover { background-color: ' + to + '; } .pagination .current, .pagination a:hover { border-color: ' + to + '; }</style>';
 
                $( 'head' ).append( style ); // style element doesn't exist so add it
            } );
        } );
 
        wp.customize( 'color_scheme_2', function( value ) {
            value.bind( function( to ) {
 
                var style, el;
 
                // build the style element
                style = '<style class="hover-styles">.featuredslider .read-more, .featured-cats:before, .read-more a, .total-post, .articles-count, .comment-form .submit, .post-meta:before, #wp-calendar caption, #wp-calendar tbody td a { background-color: ' + to + '; }</style>';
 
                $( 'head' ).append( style ); // style element doesn't exist so add it
            } );
        } );
    } )( jQuery )
    </script>
    <?php 
}

/**
 * Output customizer CSS. Default values are used for output when new settings are not saved
 *
 * @since Bloomy 1.0
 *
 */
function bloomy_customizer_apply_css() {
    $fields = array();
	$fields = apply_filters( 'bloomy_customizer_apply_css', $fields );
    
    $css = '';
    $new_array = array();
    foreach ( $fields as $field ) {
        if ( !empty( $field['output'] ) && is_array($field['output']) ){
            foreach ( $field['output'] as $property => $selector ) {
                $value = get_theme_mod( $field['id'] );
                
                if ( empty( $value ) ) {
                    $value = $field['default'];
                }
                
                if ( !isset($new_array[$selector]) ) {
                    $new_array[$selector] = '';
                }

				$new_array[$selector] .= $property . ':' . esc_html( $value ) . ';';
            }
        }
    }
                
    foreach( $new_array as $new_property => $new_value ){ 

        $css .= $new_property . '{' . $new_value . '}';
        
    }
    
	$bloomy_custom_css = '';    
    
    // Header Colors
    $bloomy_header_css = '';
    $bloomy_header_image = get_header_image();
    $header_text_color = get_header_textcolor();
    
    if ( !empty( $bloomy_header_image ) ) {
        $bloomy_header_css .= '.main-header { background: url('. esc_url( $bloomy_header_image ) . ') no-repeat 100% 50%; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }';
    
        $css .= "\n" . $bloomy_header_css;
    }
    
    if ( !empty( $header_text_color ) ) {
        $css .= "\n" . '.site-description { color: #'.$header_text_color.'}';
    }
    
	// Custom CSS
    $bloomy_custom_css = get_theme_mod('custom_css');
	if ( $bloomy_custom_css != '' ) {
        $css .= "\n" . $bloomy_custom_css;
	}
    
    return $css;
	echo "\n";
}

/**
*
* Adds Google Web Fonts to '<head>' based on fonts selected
* in the Theme Customizer.
*
*/
function bloomy_google_fonts() {
	$fonts = array();
    $fields = array();
	$fields = apply_filters( 'bloomy_customizer_google_fonts', $fields );
    
    foreach ( $fields as $field ) {
        if ( !empty ( $field['key'] ) ) {
            if ( $field['key'] == 'fonts_family' ) {
                $font_family = get_theme_mod( $field['id'] );
                
				//$value = empty( $field['default'] ) ? $value : $field['default'];
                
                if ( empty( $font_family ) ) {
                    $font_family = $field['default'];
                }
                
                if ( !in_array( $font_family, $fonts ) ) {
                    array_push( $fonts, $font_family );
                }
            }
        }
    }
	
    if ( !empty( $fonts ) ) {
        $bloomy_protocol = is_ssl() ? 'https' : 'http';
        $bloomy_google_font = implode(':300,400,500,600,700,800|', $fonts);
        $bloomy_google_fonts_url = $bloomy_protocol.'://fonts.googleapis.com/css?family='.$bloomy_google_font.':300,400,500,600,700,800';
        wp_enqueue_style( 'bloomy-google-font', "$bloomy_google_fonts_url", array(), null );
    }
}
add_action( 'wp_enqueue_scripts', 'bloomy_google_fonts' );

function bloomy_sanitize_checkbox( $input ) {
    if ( $input ) {
            $output = '1';
    } else {
            $output = false;
    }
    return $output;
}
function bloomy_sanitize_choices( $input, $setting ) {
    global $wp_customize;

    $control = $wp_customize->get_control( $setting->id );

    if ( array_key_exists( $input, $control->choices ) ) {
        return $input;
    } else {
        return $setting->default;
    }
}

/**
* Sanitizes Font Select Field
*/
function bloomy_sanitize_fonts( $input ) {
    global $bloomy_fonts_list;
    $valid = $bloomy_fonts_list;

    if ( array_key_exists( $input, $valid ) ) {
        return $input;
    } else {
        return '';
    }
}

/**
* Sanitizes Categories Select Field
*/
function bloomy_sanitize_cat( $input ) {
    $valid = bloomy_get_categories_select();

    if ( array_key_exists( $input, $valid ) ) {
        return $input;
    } else {
        return '';
    }
}

/**
*
* Registers the Theme Customizer Preview with WordPress.
*
*/
function bloomy_customizer_live_preview() {
	wp_enqueue_script(
		'bloomy-themecustomizer',
		get_template_directory_uri() . '/js/theme-customizer.js',
		array( 'jquery', 'customize-preview' ),
		'',
		true
	);
} // end bloomy_customizer_live_preview
add_action( 'customize_preview_init', 'bloomy_customizer_live_preview' );