<?php
/**
 * Blog layout section.
 *
 * Author:          Andrei Baicus <andrei@themeisle.com>
 * Created on:      20/08/2018
 *
 * @package Neve\Customizer\Options
 */

namespace Neve\Customizer\Options;

use Neve\Customizer\Base_Customizer;
use Neve\Customizer\Types\Control;
use Neve\Customizer\Types\Section;

/**
 * Class Layout_Blog
 *
 * @package Neve\Customizer\Options
 */
class Layout_Blog extends Base_Customizer {
	/**
	 * Function that should be extended to add customizer controls.
	 *
	 * @return void
	 */
	public function add_controls() {
		$this->section_blog();
		$this->add_layout_controls();
		$this->add_content_ordering_controls();
		$this->add_post_meta_controls();
		$this->add_typography_shortcut();

		add_action( 'customize_register', [ $this, 'adapt_old_pro' ], PHP_INT_MAX );
	}

	/**
	 * Adapting old pro versions to make them still usable with the old theme version.
	 */
	public function adapt_old_pro() {
		if ( ! defined( 'NEVE_PRO_VERSION' ) ) {
			return;
		}

		if ( version_compare( NEVE_PRO_VERSION, '1.2.8', '>' ) ) {
			return;
		}

		$changes = [
			'neve_posts_order'                   => [ 'priority' => 51 ],
			'neve_post_content_ordering'         => [ 'active_callback' => '__return_true' ],
			'neve_blog_ordering_content_heading' => [ 'controls_to_wrap' => 6 ],
			'neve_blog_post_meta_heading'        => [ 'controls_to_wrap' => 3 ],
			'neve_read_more_options'             => [
				'accordion' => true,
				'expanded'  => false,
				'class'     => 'read-more-options-accordion',
			],
		];

		foreach ( $changes as $control_slug => $props ) {
			foreach ( $props as $prop => $new_value ) {
				$this->change_customizer_object( 'control', $control_slug, $prop, $new_value );
			}
		}

		$this->wpc->remove_control( 'neve_metadata_options' );
	}

	/**
	 * Add customize section
	 */
	private function section_blog() {
		$this->add_section(
			new Section(
				'neve_blog_archive_layout',
				array(
					'priority' => 35,
					'title'    => esc_html__( 'Blog / Archive', 'neve' ),
					'panel'    => 'neve_layout',
				)
			)
		);
	}

	/**
	 * Add blog layout controls.
	 */
	private function add_layout_controls() {
		$this->add_control(
			new Control(
				'neve_blog_layout_heading',
				array(
					'sanitize_callback' => 'sanitize_text_field',
				),
				array(
					'label'            => esc_html__( 'Blog Layout', 'neve' ),
					'section'          => 'neve_blog_archive_layout',
					'priority'         => 10,
					'class'            => 'blog-layout-accordion',
					'accordion'        => true,
					'controls_to_wrap' => 5,
				),
				'Neve\Customizer\Controls\Heading'
			)
		);

		$this->add_control(
			new Control(
				'neve_blog_archive_layout',
				[
					'default'           => 'grid',
					'sanitize_callback' => [ $this, 'sanitize_blog_layout' ],
				],
				[
					'section'  => 'neve_blog_archive_layout',
					'priority' => 11,
					'choices'  => [
						'default' => [
							'name'  => __( 'List', 'neve' ),
							'image' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF4AAAB5CAYAAACwe5bgAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AkBDC0qBiacfQAABqdJREFUeNrtXU1T40YQfT2WLS/s4kqR5UAK36jiAKdQ+/8vnOKcIIeEG6RSKZZDcIqwXmA6B0nWSOZjbI00Gqn7YooCWXp601/zZoaYmSHWuCmBQIAX4MUEeAFeTIAX4MUEeAFerAngnde8Or90wwV109+nKoFN7m8nuzwRdZrxkc0ffX8Ebh+AhBS8BCZhSXWAfvwIxIOa3qUl25t+0ZHN8F88Kfw5Z4ApgYY4xZ8cPDTwaZwAvwIAN/MmfIyuyGb4L1mRosCaQIT0BVDFh84cDIGIcHd3B4IGQ7m4/GagRBG2t7f9u5oEfoJmgKAB5RYNbdD64uLCAFx7SbwmkwmOj4/9A68JYKQsT5nodqgXH9q3f9/a2qrd90fwbMxZ0E6sbqa1xfcr/w/XjfRw3TpAKldPo6MVrsa08/Nzb4x15VqGwyGOjo7aDXzZ5vO5N8a6ahvEcdx+xpetTcF105ESRVH7gS+P7qbTSV9mFVwVv1j1OLwJXg5znfaCOCDG11pAgThvFWSvzFFNr5Ff93HxvROMHo1GbwbryO6NUu4WTLAdNVKI89bAL7/OlpWxj65hlVQyY38cxzg9Pa3G+OSiGqxVAjzTMg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xVwQAUDg8PC76yq1XsxkqyJqR2HdierEpWo1/oEOj69q5Jr48Og16J8RC2W6WWr7lKK8Z7YUQXWP1GfLIAvrSFCZc+a3M3UrkWmU+6dkr2oUvcan18z7Oa13oQ9fv+LjNfWdGuHCh4TS8VqH+v0xlYLz57eDZbuIkTcLWb9ocRMKR2+JamBE5WLYP7R+CPr+aaVrc3drQHDON2+JamWhT2Pj47x5UYrkegeThLX2wtXQ2MPQeYkpXdlc9zLcWQs7OzdMg/p7/r8bGiMDDPkCLkG0tU8qmUdH7K7p3Iv3y4Tn9vFVzvvgG/f63vAY/2gJ24V55G5lwF+Iby5+CCa1OW6+MDBjWKsL+/HxbwbdDHbxqAs8/RaNR+4MtepQ36+E0Lr8xFBnms6HQ6leAq1gbg08KJOV8TtbIYbUNXo9C/LXPWFjTBPFrUAfDmiZmA6ONXmakpb9s6Ps/VNNHHG6YJUMRgIxI62fowdTVmTz80fXytwI+HwP5OcQc+p0MzKg5T45UHG/+D3gwuhMnuTh1VwdkDBVI41ZpOZprGJoYHITyV8LqOQ/adlMpVgBcT4AV4MQFegBcT4AV4MUv7H5eyq+Oq1/5lAAAAAElFTkSuQmCC',
						],
						'covers'  => [
							'name'  => __( 'Covers', 'neve' ),
							'image' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF4AAAB5CAYAAACwe5bgAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAMvSURBVHgB7d1PTxNBGMfxp1JTLH8ExXAg8eDNd+Xr9eaNg8FEQxSpgIVSKBTccdMEaElnO535PYfvJ9lLQ8j0y3ZKuzu7rfuKobgXBgnCixBehPAihBchvAjhRQgvQngRwosQXqQd80PXt2a9gbmws27WWXn82O2d2dG5ubDdNeu+nP9z0eEP++bC5up0+PGdn/F12nHhmWpECC9CeBHCixBehPAihBchvAjhRQgvQngRwosQXoTwIoQXIbwI4UWijkA9tLNWbV3LZv/Ykmx0zPY2LZtvp/URuVSNw4fDbuHwm1fexzfROPxxddD7/Nrc6ldj2/9t2Sxjbw8ahx+N680r7+ObaBx++1W9LSr3KybM8e/WbGGnw3rLrXH4cOrCTsIT619V4S2fMMenjC9MJS7DnwzT5rl+5veH8PsP/tjCBjdWROPww5t68yrM771Lc48PUCKt2HWuy/o3KtVKNYe3W9OPex/fUy0WGGsw1YgQXoTwItHnx3v5fmarO/3mFRYmnBX40BMjfHLuRFSNDn9wYi58bNdP7qGwMMHL+D68iQvPVCNCeBHCixBehPAihBchvAjhRQgvQngRwosQXoTwIoQXIbwI4UUIL0J4kcan8LWrP9VKxj9X6olJ3sc30Tj87rrZ3mvL5vMPS7K1Wh33fGvZfPkpWooTjuh7OV1ulvG97/FNNA5/dFFvXpVaWJCKN1eRxnt8WMqYMseHRQM5z18PS0FT5vjDv2UuHsoeL9J4jw97g5fLyc4SXk2sCMGzovb48IHk6fmKKs99OPIyvk7kHMKKEBGmGhHCixBehPAiUe/BlyOz72fmwvvt6VtBhC/uvvbMhd2NuItsRIUPT6zvZA1UWHYz6zEv44u9gAVTjQjhRQgvQngRwosQXoTwIoQXIbwI4UUIL0J4EcKLEF6E8CKEFyG8SPGTVudJXZiQetLqPMtamMAeL8JJqyLs8SLF7wP16yLvVVFT7wP1/xUzsOyK3wcq95NKHV+pS/kWvw/UYGRZpd4H6qrQikHuAyXCm6sICxNE2ONFCC9CeBHCixBehPAihBchvAjhRQgvQniR8O3kJ0Nx/wAXONq4kNEpFQAAAABJRU5ErkJggg==',
						],
						'grid'    => [
							'name'  => __( 'Grid', 'neve' ),
							'image' => 'data:image/jpeg;base64, ',
						],
					],
				],
				'\Neve\Customizer\Controls\React\Radio_Image'
			)
		);

		$this->add_control(
			new Control(
				'neve_grid_layout',
				array(
					'sanitize_callback' => 'neve_sanitize_range_value',
					'default'           => wp_json_encode(
						array(
							'desktop' => 1,
							'tablet'  => 1,
							'mobile'  => 1,
						)
					),
				),
				array(
					'label'           => esc_html__( 'Columns', 'neve' ),
					'section'         => 'neve_blog_archive_layout',
					'units'           => array(
						'items',
					),
					'input_attrs'     => [
						'step'       => 1,
						'min'        => 1,
						'max'        => 4,
						'defaultVal' => [
							'mobile'  => 1,
							'tablet'  => 1,
							'desktop' => 1,
						],
					],
					'priority'        => 11,
					'active_callback' => array( $this, 'is_column_layout' ),
				),
				'Neve\Customizer\Controls\React\Responsive_Range'
			)
		);

		$this->add_control(
			new Control(
				'neve_blog_covers_text_color',
				array(
					'sanitize_callback' => 'neve_sanitize_colors',
					'default'           => '#ffffff',
					'transport'         => 'postMessage',
				),
				array(
					'label'                 => esc_html__( 'Text Color', 'neve' ),
					'section'               => 'neve_blog_archive_layout',
					'priority'              => 15,
					'default'               => '#ffffff',
					'active_callback'       => function () {
						return get_theme_mod( 'neve_blog_archive_layout' ) === 'covers';
					},
					'live_refresh_selector' => true,
					'live_refresh_css_prop' => [
						'template' =>
							'.cover-post .inner, .cover-post .inner a:not(.button), .cover-post .inner a:not(.button):hover, .cover-post .inner a:not(.button):focus, .cover-post .inner li {
							color: {{value}};
						}',
					],
				),
				'Neve\Customizer\Controls\React\Color'
			)
		);

		$this->add_control(
			new Control(
				'neve_blog_list_alternative_layout',
				array(
					'sanitize_callback' => 'neve_sanitize_checkbox',
					'default'           => false,
				),
				array(
					'type'            => 'neve_toggle_control',
					'priority'        => 17,
					'section'         => 'neve_blog_archive_layout',
					'label'           => esc_html__( 'Alternating layout', 'neve' ),
					'active_callback' => function () {
						return get_theme_mod( 'neve_blog_archive_layout' ) === 'default';
					},
				)
			)
		);

		$this->add_control(
			new Control(
				'neve_enable_masonry',
				array(
					'sanitize_callback' => 'neve_sanitize_checkbox',
					'default'           => false,
				),
				array(
					'type'            => 'neve_toggle_control',
					'priority'        => 35,
					'section'         => 'neve_blog_archive_layout',
					'label'           => esc_html__( 'Enable Masonry', 'neve' ),
					'active_callback' => array( $this, 'should_show_masonry' ),
				)
			)
		);
	}

	/**
	 * Add content ordering and controls.
	 */
	private function add_content_ordering_controls() {
		$this->add_control(
			new Control(
				'neve_blog_ordering_content_heading',
				array(
					'sanitize_callback' => 'sanitize_text_field',
				),
				array(
					'label'            => esc_html__( 'Ordering and Content', 'neve' ),
					'section'          => 'neve_blog_archive_layout',
					'priority'         => 50,
					'class'            => 'blog-layout-ordering-content-accordion',
					'accordion'        => true,
					'expanded'         => false,
					'controls_to_wrap' => 4,
				),
				'Neve\Customizer\Controls\Heading'
			)
		);

		$this->add_control(
			new Control(
				'neve_pagination_type',
				array(
					'default'           => 'number',
					'sanitize_callback' => array( $this, 'sanitize_pagination_type' ),
				),
				array(
					'label'    => esc_html__( 'Post Pagination', 'neve' ),
					'section'  => 'neve_blog_archive_layout',
					'priority' => 53,
					'type'     => 'select',
					'choices'  => array(
						'number'   => esc_html__( 'Number', 'neve' ),
						'infinite' => esc_html__( 'Infinite Scroll', 'neve' ),
					),
				)
			)
		);

		$order_default_components = array(
			'thumbnail',
			'title-meta',
			'excerpt',
		);

		$components = array(
			'thumbnail'  => __( 'Thumbnail', 'neve' ),
			'title-meta' => __( 'Title & Meta', 'neve' ),
			'excerpt'    => __( 'Excerpt', 'neve' ),
		);

		$this->add_control(
			new Control(
				'neve_post_content_ordering',
				array(
					'sanitize_callback' => array( $this, 'sanitize_post_content_ordering' ),
					'default'           => wp_json_encode( $order_default_components ),
				),
				array(
					'label'      => esc_html__( 'Post Content Order', 'neve' ),
					'section'    => 'neve_blog_archive_layout',
					'components' => $components,
					'priority'   => 55,
				),
				'Neve\Customizer\Controls\React\Ordering'
			)
		);

		$this->add_control(
			new Control(
				'neve_post_excerpt_length',
				array(
					'sanitize_callback' => 'neve_sanitize_range_value',
					'default'           => 25,
				),
				array(
					'label'       => esc_html__( 'Excerpt Length', 'neve' ),
					'section'     => 'neve_blog_archive_layout',
					'type'        => 'neve_range_control',
					'input_attrs' => [
						'min'        => 5,
						'max'        => 300,
						'defaultVal' => 25,
						'step'       => 5,
					],
					'priority'    => 58,
				),
				'Neve\Customizer\Controls\React\Range'
			)
		);

		$this->add_control(
			new Control(
				'neve_post_thumbnail_box_shadow',
				array(
					'sanitize_callback' => 'absint',
					'default'           => 0,
				),
				array(
					'label'       => esc_html__( 'Thumbnail Shadow', 'neve' ),
					'section'     => 'neve_blog_archive_layout',
					'type'        => 'neve_range_control',
					'step'        => 1,
					'input_attrs' => [
						'min'        => 0,
						'max'        => 5,
						'defaultVal' => 0,
					],
					'priority'    => 59,
				),
				'Neve\Customizer\Controls\React\Range'
			)
		);
	}

	/**
	 * Add controls for post meta.
	 */
	private function add_post_meta_controls() {
		$this->add_control(
			new Control(
				'neve_blog_post_meta_heading',
				array(
					'sanitize_callback' => 'sanitize_text_field',
				),
				array(
					'label'            => esc_html__( 'Post Meta', 'neve' ),
					'section'          => 'neve_blog_archive_layout',
					'priority'         => 70,
					'class'            => 'blog-layout-post-meta-accordion',
					'accordion'        => true,
					'controls_to_wrap' => 2,
					'expanded'         => false,
				),
				'Neve\Customizer\Controls\Heading'
			)
		);

		$order_default_components = array(
			'author',
			'date',
			'comments',
		);

		$components = apply_filters(
			'neve_meta_filter',
			array(
				'author'   => __( 'Author', 'neve' ),
				'category' => __( 'Category', 'neve' ),
				'date'     => __( 'Date', 'neve' ),
				'comments' => __( 'Comments', 'neve' ),
			)
		);

		$this->add_control(
			new Control(
				'neve_post_meta_ordering',
				array(
					'sanitize_callback' => array( $this, 'sanitize_meta_ordering' ),
					'default'           => wp_json_encode( $order_default_components ),
				),
				array(
					'label'           => esc_html__( 'Meta Order', 'neve' ),
					'section'         => 'neve_blog_archive_layout',
					'components'      => $components,
					'priority'        => 75,
					'active_callback' => array( $this, 'should_show_meta_order' ),
				),
				'Neve\Customizer\Controls\React\Ordering'
			)
		);

		$this->add_control(
			new Control(
				'neve_author_avatar',
				array(
					'sanitize_callback' => 'neve_sanitize_checkbox',
					'default'           => false,
				),
				array(
					'label'    => esc_html__( 'Show Author Avatar', 'neve' ),
					'section'  => 'neve_blog_archive_layout',
					'type'     => 'neve_toggle_control',
					'priority' => 80,
				)
			)
		);

	}

	/**
	 * Sanitize the container layout value
	 *
	 * @param string $value value from the control.
	 *
	 * @return bool
	 */
	public function sanitize_blog_layout( $value ) {
		$allowed_values = array( 'default', 'covers', 'grid' );
		if ( ! in_array( $value, $allowed_values, true ) ) {
			return 'grid';
		}

		return sanitize_text_field( $value );
	}

	/**
	 * Sanitize the pagination type
	 *
	 * @param string $value value from the control.
	 *
	 * @return bool
	 */
	public function sanitize_pagination_type( $value ) {
		$allowed_values = array( 'number', 'infinite' );
		if ( ! in_array( $value, $allowed_values, true ) ) {
			return 'number';
		}

		return esc_html( $value );
	}

	/**
	 * Sanitize meta order control.
	 */
	public function sanitize_meta_ordering( $value ) {
		$allowed = array(
			'author',
			'category',
			'date',
			'comments',
			'reading',
		);

		if ( empty( $value ) ) {
			return $allowed;
		}

		$decoded = json_decode( $value, true );

		foreach ( $decoded as $val ) {
			if ( ! in_array( $val, $allowed, true ) ) {
				return $allowed;
			}
		}

		return $value;
	}

	/**
	 * Sanitize content order control.
	 */
	public function sanitize_post_content_ordering( $value ) {
		$allowed = array(
			'thumbnail',
			'title-meta',
			'excerpt',
		);

		if ( empty( $value ) ) {
			return $allowed;
		}

		$decoded = json_decode( $value, true );

		foreach ( $decoded as $val ) {
			if ( ! in_array( $val, $allowed, true ) ) {
				return $allowed;
			}
		}

		return $value;
	}

	/**
	 * Callback to show the meta order control.
	 *
	 * @return bool
	 */
	public function should_show_meta_order() {
		$default       = array(
			'thumbnail',
			'title-meta',
			'excerpt',
		);
		$content_order = get_theme_mod( 'neve_post_content_ordering', wp_json_encode( $default ) );
		$content_order = json_decode( $content_order, true );
		if ( ! in_array( 'title-meta', $content_order, true ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Callback to show grid columns control.
	 *
	 * @return bool
	 */
	public function is_column_layout() {
		$blog_layout = get_theme_mod( 'neve_blog_archive_layout', 'grid' );

		return in_array( $blog_layout, [ 'grid', 'covers' ], true );
	}

	/**
	 * Callback to show masonry control.
	 *
	 * @return bool
	 */
	public function should_show_masonry() {
		if ( ! $this->is_column_layout() ) {
			return false;
		}

		$columns = json_decode( get_theme_mod( 'neve_grid_layout', '{"desktop":1,"tablet":1,"mobile":1}' ), true );
		$columns = array_filter(
			array_values( $columns ),
			function ( $value ) {
				return $value > 1;
			}
		);

		if ( empty( $columns ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Add typography shortcut.
	 */
	private function add_typography_shortcut() {
		$this->add_control(
			new Control(
				'neve_blog_typography_shortcut',
				array(
					'sanitize_callback' => 'neve_sanitize_text_field',
				),
				array(
					'button_class'     => 'nv-top-bar-menu-shortcut',
					'text_before'      => __( 'Customize Typography for the Archive page', 'neve' ),
					'text_after'       => '.',
					'button_text'      => __( 'here', 'neve' ),
					'is_button'        => false,
					'control_to_focus' => 'neve_archive_typography_post_title_accordion_wrap',
					'shortcut'         => true,
					'section'          => 'neve_blog_archive_layout',
					'priority'         => 1000,
				),
				'\Neve\Customizer\Controls\Button'
			)
		);
	}
}
