<?php
/*
 * Category Colors - Admin
 * @since 1.0
 * 
 * This file is loaded at after_setup_theme @10
 */


/***** HootKit *****/


/* Grid - Category at top */
add_filter( 'hootkit_post_grid_display_catblock', '__return_true' );


/***** Single Cat Block *****/


add_filter( 'maglume_customizer_options', 'maglume_modify_cat_customizer_options', 1 );
function maglume_modify_cat_customizer_options( $options ) {
	if ( isset( $options['settings'] ) && is_array( $options['settings'] ) ) {
		$posts = hoot_arrayel( $options['settings'], array( 'singular_post_page', 'options', 'posts' ) );
		if ( is_array( $posts ) ) {
			$newposts = array();
			foreach ( $posts as $key => $postoption ) {
				$newposts[ $key ] = $postoption;
				if ( $key === 'post_meta' ) {
					$newposts['post_catblock_top'] = array(
						'label'       => esc_html__( 'Show Categories at Top (next to the Heading)', 'magazine-lume' ),
						'description' => esc_html__( 'You may want to hide Categories in the above list when this is enabled', 'magazine-lume' ),
						'type'        => 'bettertoggle',
						'default'     => 1,
						'selective_refresh' => array( 'post_catblock_top_partial', array(
							'selector'            => '.singular-post .entry-byline.entry-byline-catsblock',
							'settings'            => array( 'post_catblock_top' ),
							'render_callback'     => 'maglume_callback_post_catblock_top',
							'container_inclusive' => true,
							'fallback_refresh'    => false, // prevents full refresh on non applicable views
							) ),
					);
				}
			}
			$options['settings']['singular_post_page']['options']['posts'] = $newposts;
		}
	}
	return $options;
}
// Callback Functions for selective refresh
function maglume_callback_post_catblock_top(){
	$catblocktop = hoot_get_mod('post_catblock_top');
	$catblockmetarray = !$catblocktop ? array() : array( 'cats' );
	hoot_display_meta_info( $catblockmetarray, 'loop-meta-catsblock', false, 'entry-byline-catsblock' );
}
add_filter( 'maglume_singular_loopmeta_hascallback', '__return_true' );
add_action( 'maglume_singular_loopmeta_callback', 'maglume_singular_loopmeta_catblocks', 10, 5 );
function maglume_singular_loopmeta_catblocks( $metarray, $loc, $metarraytop, $has_meta, $is_cpreview ) {
	$catblocktop = hoot_get_mod('post_catblock_top');
	if ( ( $catblocktop || $is_cpreview ) || $metarraytop ) {
		?><div <?php hoot_attr( 'loop-description' ); ?>><?php
		// Only add this for 'posts'
		if ( ( $catblocktop || $is_cpreview ) && get_post_type() === 'post' ) {
			$catblockmetarray = !$catblocktop && $is_cpreview ? array() : array( 'cats' );
			hoot_display_meta_info( $catblockmetarray, 'loop-meta-catsblock', false, 'entry-byline-catsblock' );
		}
		if ( $metarraytop ) {
			hoot_display_meta_info( $metarray, 'loop-meta', true, 'entry-byline-metarray' );
		}
		?></div><!-- .loop-description --><?php
	};
}


/***** Category Colors : 1. Admin *****/


$taxonomies = apply_filters( 'maglume_taxonomy_fields_taxonomies', array( 'category' ) );
if ( !empty( $taxonomies ) ) {
	if ( is_admin() ) :
		add_action( 'admin_enqueue_scripts', 'maglume_taxonomy_enqueue' );
		foreach ( $taxonomies as $taxonomy ) {
			add_filter( "manage_edit-{$taxonomy}_columns", 'maglume_taxonomy_columns_header' );
			add_filter( "manage_{$taxonomy}_custom_column", 'maglume_taxonomy_column', 10, 3 );
			add_action( "{$taxonomy}_add_form_fields", 'maglume_add_taxonomy_field' );
			add_filter( "{$taxonomy}_edit_form_fields", 'maglume_edit_taxonomy_field' );
		}
		// add_action( 'create_term', 'maglume_term_save' );
		add_action( 'created_term', 'maglume_term_update', 10, 3 );
		add_action( 'edit_term', 'maglume_term_update', 10, 3 );
	endif;
	add_filter( 'hoot_display_meta_info', 'maglume_display_meta_catblock', 5, 4 );
}

function maglume_taxonomy_enqueue( $hook ) {
	$screen = get_current_screen();
	if ( !$screen || !is_object( $screen ) || !isset( $screen->id ) )
		return;
	$currenttax = str_replace( 'edit-', '', $screen->id );
	if ( in_array( $currenttax, apply_filters( 'maglume_taxonomy_fields_taxonomies', array( 'category' ) ) ) ) {
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );
		wp_add_inline_script(
			'wp-color-picker',
			"jQuery(document).ready(function($){
				'use strict';
				$('.hoot-color').wpColorPicker();
			});"
		);
	}
}

function maglume_taxonomy_columns_header( $defaults ){
	$defaults['hoot_term_colors']  = __( 'Label Color', 'magazine-lume' );
	return $defaults;
}

function maglume_taxonomy_column( $columns, $column, $id ){
	if ( 'hoot_term_colors' === $column ) {
		$bg = get_term_meta( $id, 'hoot_term_bg', true );
		$font = get_term_meta( $id, 'hoot_term_font', true );
		$columns .= ( empty( $bg ) ) ? __( 'Auto', 'magazine-lume' ) . ' / ' : '<span style="display:inline-block;height:15px;width:15px;border:solid 1px #999;background:' . sanitize_hex_color( $bg ) . ';margin-right:5px;"></span>';
		$columns .= ( empty( $font ) ) ? __( 'Auto', 'magazine-lume' ) : '<span style="display:inline-block;height:15px;width:15px;border:solid 1px #999;background:' . sanitize_hex_color( $font ) . ';"></span>';
	}
	return $columns;
}

function maglume_add_taxonomy_field( $term ) {
	?><div class="form-field">
		<label for="hoot_term_bg"><?php esc_html_e( 'Label Background', 'magazine-lume' ); ?></label>
		<input type="input" id="hoot_term_bg" class="hoot-color" name="hoot_term_bg" value="" />
	</div><div class="form-field">
		<label for="hoot_term_font"><?php esc_html_e( 'Label Font', 'magazine-lume' ); ?></label>
		<input type="input" id="hoot_term_font" class="hoot-color" name="hoot_term_font" value="" />
	</div><?php
}

function maglume_edit_taxonomy_field( $term ) {
	$bg = get_term_meta( $term->term_id, 'hoot_term_bg', true );
	$font = get_term_meta( $term->term_id, 'hoot_term_font', true );
	?><tr class="form-field">
		<th scope="row" valign="top">
			<label for="hoot_term_bg"><?php esc_html_e( 'Label Background', 'magazine-lume' ); ?></label>
		</th>
		<td>
			<input type="input" id="hoot_term_bg" class="hoot-color" name="hoot_term_bg" value="<?php echo sanitize_hex_color( $bg ); ?>" />
			<p class="description" style="margin:0"><?php _e( 'Leave empty for automatic color selection', 'magazine-lume' ) ?></p>
		</td>
	</tr><tr class="form-field">
		<th scope="row" valign="top">
			<label for="hoot_term_font"><?php esc_html_e( 'Label Font', 'magazine-lume' ); ?></label>
		</th>
		<td>
			<input type="input" id="hoot_term_font" class="hoot-color" name="hoot_term_font" value="<?php echo sanitize_hex_color( $font ); ?>" />
			<p class="description" style="margin:0"><?php _e( 'Leave empty for automatic color selection', 'magazine-lume' ) ?></p>
		</td>
	</tr><?php
}

// @ref. https://developer.wordpress.org/reference/hooks/edit_term/
function maglume_term_update( $term_id, $tt_id = '', $taxonomy = '' ){
	if ( in_array( $taxonomy, apply_filters( 'maglume_taxonomy_fields_taxonomies', array( 'category' ) ) ) ) {
		if ( isset( $_POST['hoot_term_bg'] ) )
			update_term_meta( $term_id, 'hoot_term_bg', sanitize_hex_color( $_POST['hoot_term_bg'] ) );
		if ( isset( $_POST['hoot_term_font'] ) )
			update_term_meta( $term_id, 'hoot_term_font', sanitize_hex_color( $_POST['hoot_term_font'] ) );
	}
}


/***** Category Colors : 2. Display in Meta Info *****/


function maglume_display_meta_catblock( $blocks, $context, $display, $editlink ){

	// 1. Only apply to these contextx
	$dofor = apply_filters( 'maglume_display_meta_catblocks_context', array(

				'loop-meta-catsblock', // meta info shown in is_singular header title based on mod 'post_catblock_top'

				'archive-big', 'archive-medium', 'archive-small', 'archive-block2', 'archive-block3', 'mixedunit-big', 'mixedunit-medium', 'mixedunit-small', 'mixedunit-block2', 'mixedunit-block3', 'archive-mosaic2', 'archive-mosaic3', 'archive-mosaic4', // meta info shown in archove entry grid
				'customizer-archive', // meta info shown in archove entry grid using customizer SR

				'hk-gridunit',
				'post-listcarouselunit', 'content-post-block',
				'hk-listunit', 'posts-listunit' /* backward compatibility */

			), $blocks, $context, $display, $editlink );

	// 2. Dont rearrange to beginning
	//    This filter only makes sense where users have an option to rearrange order of meta blocks
	$norearrange = apply_filters( 'maglume_display_meta_catblocks_norearrange', array(

				'loop-meta',    // meta info shown in is_singular header metarray
				'post', 'page', // meta info shown in page/post footer metarray after content
				'customizer-post', 'customizer-page', // meta info shown in both header/footer metarray using customizer SR

				'archive-big', 'archive-medium', 'archive-small', 'archive-block2', 'archive-block3', 'mixedunit-big', 'mixedunit-medium', 'mixedunit-small', 'mixedunit-block2', 'mixedunit-block3', 'archive-mosaic2', 'archive-mosaic3', 'archive-mosaic4', // meta info shown in archove entry grid
				'customizer-archive', // meta info shown in archove entry grid using customizer SR

			), $blocks, $context, $display, $editlink, $dofor );

	// 3. When rearrange : keep it inline (else creates a seperate div.entry-byline)
	//    This filter only makes sense where context is NOT in $norearrange
	$rearrangeinline = apply_filters( 'maglume_display_meta_catblock_inline', array(

			), $blocks, $context, $display, $editlink, $dofor );

	// 1. skip this for default non colored catblocks
	if ( !empty( $blocks ) && !empty( $blocks['cats'] ) && in_array( $context, $dofor ) ) {
		$categories = get_the_category();
		$print = '';
		if ( !empty( $categories ) ) {
			foreach ( $categories as $category ) {
				$print .= '<span class="catblock catblock-' . $category->term_id . '"><a href="' . esc_url( get_category_link( $category->term_id ) ) . '" rel="category">' . esc_html( $category->name ) . '</a></span>';
			}
		}
		if ( !empty( $print ) ) {
			// 2. colored catblocks in sequence set by user
			if ( in_array( $context, $norearrange ) ) {
				$newblocks = array();
				foreach ( $blocks as $key => $block ) {
					if ( $key === 'cats' )
						$newblocks['catblock'] = array( 'label' => '', 'content' => $print );
					else
						$newblocks[ $key ] = $block;
				}
				$blocks = $newblocks;
			}
			// 3. colored catblcoks at start
			else {
				unset( $blocks['cats'] );
				// 3a. inline catblocks within entry-byline
				if ( in_array( $context, $rearrangeinline ) ) {
					$blocks = array_merge( array( 'catblock' => array( 'label' => '', 'content' => $print ) ), $blocks );
				}
				// 3b. catblocks as seperate div.entry-byline
				//     Used when mod 'post_catblock_top' is set (and may be used for others based on filters above)
				else {
					$blocks['byline-catblock'] = $print;
				}
			}
		}
	}

	return $blocks;
}


/***** Category Colors : 3. CSS *****/


add_action( 'hoot_dynamic_cssrules', 'maglume_dynamic_css_catblocks', 2 );
function maglume_dynamic_css_catblocks() {

	$categories = get_categories( array( 'orderby' => 'name', 'order' => 'ASC' ) );

	$colorset = apply_filters( 'unosmbl_catblocks_colorset', array(
		array( '#ffffff', '#fa6c04' ),
		array( '#ffffff', '#0ea7ef' ),
		array( '#ffffff', '#37be5a' ),
		array( '#ffffff', '#f7b528' ),
		array( '#ffffff', '#ff2d2d' ),
		) );

	$colorcount = 0;
	foreach ( $categories as $category ) { if ( !empty( $category->term_id ) ) {
		$property = array();
		$hoveproperty = array();
		$colorbg = get_term_meta( $category->term_id, 'hoot_term_bg', true );
		$colorfont = get_term_meta( $category->term_id, 'hoot_term_font', true );
		if ( !$colorbg && !$colorfont ) {
			$colorfont = $colorset[ $colorcount ][0];
			$colorbg = $colorset[ $colorcount ][1];
			$colorcount++; if ( $colorcount == count( $colorset ) ) $colorcount = 0; 
		}
		if ( $colorfont ) {
			$property['color'] = $colorfont;
			$hoveproperty['background'] = $colorfont;
		}
		if ( $colorbg ) {
			$property['background'] = $colorbg;
			$property['border-color'] = $colorbg;
			$hoveproperty['color'] = $colorbg;
		}
		if ( !empty( $property ) )
			hoot_add_css_rule( array(
						'selector'  => ".catblock-{$category->term_id}",
						'property'  => $property,
					) );
		if ( !empty( $hoveproperty ) && $colorbg && $colorfont ) // add hover only if both the colors are set
			hoot_add_css_rule( array(
						'selector'  => ".catblock-{$category->term_id}:hover",
						'property'  => $hoveproperty,
					) );
	} }

}

