<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package express-movers
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function express_movers_body_classes( $classes ) {
	// Adds a class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}

	// Adds a class of no-sidebar when there is no sidebar present.
	if ( ! is_active_sidebar( 'sidebar-1' ) ) {
		$classes[] = 'no-sidebar';
	}

	return $classes;
}
add_filter( 'body_class', 'express_movers_body_classes' );

/**
 * Add a pingback url auto-discovery header for single posts, pages, or attachments.
 */
function express_movers_pingback_header() {
	if ( is_singular() && pings_open() ) {
		printf( '<link rel="pingback" href="%s">', esc_url( get_bloginfo( 'pingback_url' ) ) );
	}
}
add_action( 'wp_head', 'express_movers_pingback_header' );

if(class_exists('WP_Customize_Control')){
	class Express_Movers_Toggle_Checkbox_Custom_control extends WP_Customize_Control{
		public $type = 'toogle_checkbox';
		public function enqueue(){
			// wp_enqueue_style( 'custom_controls_css', get_template_directory_uri().'/inc/customizer/css/custom_controls.css');
		}
		public function render_content(){
			?>
			<div class="checkbox_switch">
				<div class="onoffswitch">
					<input type="checkbox" id="<?php echo esc_attr($this->id); ?>" name="<?php echo esc_attr($this->id); ?>" class="onoffswitch-checkbox" value="<?php echo esc_attr( $this->value() ); ?>" <?php $this->link(); checked( $this->value() ); ?>>
					<label class="onoffswitch-label" for="<?php echo esc_attr($this->id); ?>"></label>
				</div>
				<span class="customize-control-title onoffswitch_label"><?php echo esc_html( $this->label ); ?></span>
				<p><?php echo wp_kses_post($this->description); ?></p>
			</div>
			<?php
		}
	}
}

if ( ! function_exists( 'express_movers_the_excerpt' ) ) :

	/**
	 * Generate excerpt.
	 *
	 * @since 1.0
	 *
	 * @param int     $length Excerpt length in words.
	 * @param WP_Post $post_obj WP_Post instance (Optional).
	 * @return string Excerpt.
	 */
	function express_movers_the_excerpt( $length = 0, $post_obj = null ) {

		global $post;

		if ( is_null( $post_obj ) ) {
			$post_obj = $post;
		}

		$length = absint( $length );

		if ( 0 === $length ) {
			return;
		}

		$source_content = $post_obj->post_content;

		if ( ! empty( $post_obj->post_excerpt ) ) {
			$source_content = $post_obj->post_excerpt;
		}

		$source_content = preg_replace( '`\[[^\]]*\]`', '', $source_content );
		$trimmed_content = wp_trim_words( $source_content, $length, '&hellip;' );
		return $trimmed_content;

	}

endif;

//  Customizer Control
if (class_exists('WP_Customize_Control') && ! class_exists( 'Express_Movers_Image_Radio_Control' ) ) {
	/**
 	* Customize sidebar layout control.
 	*/
	class Express_Movers_Image_Radio_Control extends WP_Customize_Control {

		public function render_content() {

			if (empty($this->choices))
				return;

			$name = '_customize-radio-' . $this->id;
			?>
			<span class="customize-control-title"><?php echo esc_html($this->label); ?></span>
			<ul class="controls" id='express_movers-img-container'>
				<?php
				foreach ($this->choices as $value => $label) :
					$class = ($this->value() == $value) ? 'express_movers-radio-img-selected express_movers-radio-img-img' : 'express_movers-radio-img-img';
					?>
					<li style="display: inline;">
						<label>
							<input <?php $this->link(); ?>style = 'display:none' type="radio" value="<?php echo esc_attr($value); ?>" name="<?php echo esc_attr($name); ?>" <?php
							  $this->link();
							  checked($this->value(), $value);
							  ?> />
							<img src='<?php echo esc_url($label); ?>' class='<?php echo esc_attr($class); ?>' />
						</label>
					</li>
					<?php
				endforeach;
				?>
			</ul>
			<?php
		}

	}
}

/**
 * Output a footer column list item from Customizer theme mods.
 *
 * @param string $label_mod      Setting key for the link label.
 * @param string $url_mod        Setting key for the URL.
 * @param string $default_label  Shown when the setting is not saved in the database yet.
 */
function express_movers_footer_link_li( $label_mod, $url_mod, $default_label = '' ) {
	$label = get_theme_mod( $label_mod, $default_label );
	$url   = get_theme_mod( $url_mod, '' );
	if ( ! is_string( $label ) || '' === trim( $label ) ) {
		return;
	}
	$href = ( is_string( $url ) && '' !== trim( $url ) ) ? $url : '#';
	printf(
		'<li><a href="%1$s">%2$s</a></li>',
		esc_url( $href ),
		esc_html( $label )
	);
}

// color
/**
 * Flag while sidebar-1 is rendering (for block markup filters).
 *
 * @param int|string $index Sidebar ID.
 */
function express_movers_sidebar_dynamic_sidebar_before( $index ) {
	if ( 'sidebar-1' === $index ) {
		$GLOBALS['express_movers_rendering_sidebar_1'] = true;
	}
}
add_action( 'dynamic_sidebar_before', 'express_movers_sidebar_dynamic_sidebar_before' );

/**
 * @param int|string $index Sidebar ID.
 */
function express_movers_sidebar_dynamic_sidebar_after( $index ) {
	if ( 'sidebar-1' === $index ) {
		unset( $GLOBALS['express_movers_rendering_sidebar_1'] );
	}
}
add_action( 'dynamic_sidebar_after', 'express_movers_sidebar_dynamic_sidebar_after' );

/**
 * Whether block output already includes a heading.
 *
 * @param string $html Block HTML.
 * @return bool
 */
function express_movers_block_has_theme_heading( $html ) {
	return (bool) preg_match( '/<h[1-6][^>]*>/', $html );
}

/**
 * Card title row matching sidebar.php fallback.
 *
 * @param string $icon_class Font Awesome classes.
 * @param string $title      Visible title.
 * @return string
 */
// function express_movers_sidebar_card_heading( $icon_class, $title ) {
// 	return sprintf(
// 		'<h2 class="widget-title sidebar-card__title"></h2>',
// 		esc_attr( $icon_class ),
// 		esc_html( $title )
// 	);
// }

/**
 * Categories list with bar + count badges (matches static sidebar).
 *
 * @return string
 */
function express_movers_sidebar_categories_list_html() {
	$post_counts = wp_count_posts( 'post' );
	$all_count   = 0;
	if ( ! empty( $post_counts ) && isset( $post_counts->publish ) ) {
		$all_count = (int) $post_counts->publish;
	}

	$categories = get_categories(
		array(
			'taxonomy'   => 'category',
			'hide_empty' => false,
			'orderby'    => 'name',
			'order'      => 'ASC',
		)
	);

	ob_start();
	echo '<ul class="wp-block-categories-list sidebar-categories-list">';
	echo '<li class="sidebar-cat-item"><a href="' . esc_url( home_url( '/' ) ) . '">' . esc_html__( 'All Posts', 'express-movers' ) . '</a><span class="sidebar-cat-count">' . esc_html( (string) $all_count ) . '</span></li>';
	foreach ( $categories as $cat ) {
		$count = (int) $cat->count;
		if ( $count <= 0 ) {
			continue;
		}
		echo '<li class="sidebar-cat-item"><a href="' . esc_url( get_category_link( $cat->term_id ) ) . '">' . esc_html( $cat->name ) . '</a><span class="sidebar-cat-count">' . esc_html( (string) $count ) . '</span></li>';
	}
	echo '</ul>';
	return ob_get_clean();
}

/**
 * Recent posts with thumbnails + dates for sidebar cards.
 *
 * @param array $attrs Latest Posts block attributes.
 * @return string
 */
function express_movers_sidebar_latest_posts_list_html( $attrs ) {
	$number = isset( $attrs['postsToShow'] ) ? absint( $attrs['postsToShow'] ) : 5;
	$number = min( max( $number, 1 ), 10 );

	$posts = get_posts(
		array(
			'posts_per_page' => $number,
			'post_status'    => 'publish',
			'orderby'        => 'date',
			'order'          => 'DESC',
			'no_found_rows'  => true,
		)
	);

	$placeholder = get_template_directory_uri() . '/assets/images/no-images.jpg';

	ob_start();
	echo '<ul class="sidebar-recent-posts-list wp-block-latest-posts__list wp-block-latest-posts">';
	foreach ( $posts as $post_obj ) {
		$pid   = $post_obj->ID;
		$thumb = get_the_post_thumbnail_url( $pid, 'thumbnail' );
		if ( empty( $thumb ) ) {
			$thumb = $placeholder;
		}
		$title = get_the_title( $pid );
		$link  = get_permalink( $pid );
		$date  = get_the_date( 'M j, Y', $pid );
		?>
		<li class="sidebar-recent-post-item">
			<a class="sidebar-recent-post-item__link" href="<?php echo esc_url( $link ); ?>">
				<img class="sidebar-recent-post-item__thumb" src="<?php echo esc_url( $thumb ); ?>" alt="<?php echo esc_attr( $title ); ?>" />
				<div class="sidebar-recent-post-item__body">
					<div class="sidebar-recent-post-item__title"><?php echo esc_html( $title ); ?></div>
					<div class="sidebar-recent-post-item__date">
						<i class="fas fa-calendar-alt" aria-hidden="true"></i>
						<?php echo esc_html( $date ); ?>
					</div>
				</div>
			</a>
		</li>
		<?php
	}
	echo '</ul>';
	return ob_get_clean();
}

/**
 * Align core sidebar blocks with the theme card layout (icons, thumbnails, category bars).
 *
 * @param string $block_content The block HTML.
 * @param array  $block         Block data.
 * @return string
 */
// function express_movers_render_sidebar_core_blocks( $block_content, $block ) {
// 	if ( empty( $GLOBALS['express_movers_rendering_sidebar_1'] ) || empty( $block['blockName'] ) ) {
// 		return $block_content;
// 	}

// 	$name = $block['blockName'];
// 	if ( express_movers_block_has_theme_heading( $block_content ) ) {
// 		return $block_content;
// 	}

// 	$attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array();

// 	switch ( $name ) {
// 		case 'core/search':
// 			return express_movers_sidebar_card_heading( 'fas fa-search', __( 'Search Blog', 'express-movers' ) ) . $block_content;
// 		case 'core/archives':
// 			return express_movers_sidebar_card_heading( 'fas fa-folder', __( 'Archives', 'express-movers' ) ) . $block_content;
// 		case 'core/categories':
// 			return express_movers_sidebar_card_heading( 'fas fa-tags', __( 'Categories', 'express-movers' ) ) . express_movers_sidebar_categories_list_html();
// 		case 'core/latest-posts':
// 			return express_movers_sidebar_card_heading( 'fas fa-bolt', __( 'Recent Posts', 'express-movers' ) ) . express_movers_sidebar_latest_posts_list_html( $attrs );
// 		default:
// 			return $block_content;
// 	}
// }
// add_filter( 'render_block', 'express_movers_render_sidebar_core_blocks', 10, 2 );

function express_movers_addColorPalatOption($wpCustomizer, $id, $section, $label="Choose Color", $color = '#ffffff'){
    $wpCustomizer->add_setting(
        $id,
        array(
            'default'           => $color,
            'sanitize_callback' => 'sanitize_hex_color',
            'priority' => 1
        )
    );
    $wpCustomizer->add_control(
        new WP_Customize_Color_Control(
            $wpCustomizer,
            $id,
            array(
                'settings'      => $id,
                'section'       => $section,
                'label' => $label,
            )
        )
    );
}
