<?php

namespace Tech360;

defined( 'ABSPATH' ) or die;

class Builder {

	private $post;
	private $post_type;
	private $row_types = [
		'1' => [
			'title' => 'One column',
			'columns' => 1,
			'type' => '1_column'
		],
		'2' => [
			'title' => 'Two columns',
			'columns' => 2,
			'type' => '2_columns'
		],
		'3' => [
			'title' => 'Three columns',
			'columns' => 3,
			'type' => '3_columns'
		],
		'4' => [
			'title' => 'Four columns',
			'columns' => 4,
			'type' => '4_columns'
		],
		'1-2' => [
			'title' => 'One third - Two thirds',
			'columns' => 2,
			'type' => '1_2_thirds'
		],
		'2-1' => [
			'title' => 'Two thirds - One third',
			'columns' => 2,
			'type' => '2_1_thirds'
		],
		'1-3' => [
			'title' => 'One quarter - Three quarters',
			'columns' => 2,
			'type' => '1_3_quarters'
		],
		'3-1' => [
			'title' => 'Three quarters - One quarter',
			'columns' => 2,
			'type' => '3_1_quarters'
		]
	];
	private $settings = [];
	public static $column_classes = [
		'1_column' => [
			'col'
		],
		'2_columns' => [
			'col-md-6',
			'col-md-6 mt-4 mt-md-0'
		],
		'3_columns' => [
			'col-md-4',
			'col-md-4 mt-4 mt-md-0',
			'col-md-4 mt-4 mt-md-0'
		],
		'4_columns' => [
			'col-sm-6 col-lg-3',
			'col-sm-6 col-lg-3 mt-4 mt-sm-0',
			'col-sm-6 col-lg-3 mt-4 mt-lg-0',
			'col-sm-6 col-lg-3 mt-4 mt-lg-0'
		],
		'1_2_thirds' => [
			'col-md-4',
			'col-md-8 mt-4 mt-md-0'
		],
		'2_1_thirds' => [
			'col-md-8',
			'col-md-4 mt-4 mt-md-0'
		],
		'1_3_quarters' => [
			'col-md-3',
			'col-md-9 mt-4 mt-md-0'
		],
		'3_1_quarters' => [
			'col-md-9',
			'col-md-3 mt-4 mt-md-0'
		]
	];

	/**
	 * Class constructor
	 * @param string	$post_type		Post type slug
	 */
	function __construct( $post_type, $settings = null ) {

		$this->post_type = $post_type;

		if( is_array( $settings ) ) {
			$this->settings = $settings;
		}

		add_action( 'admin_enqueue_scripts', [ &$this, 'load_assets' ] );
		add_action( 'edit_form_after_editor', [ &$this, 'render_builder' ] );
		add_action( 'save_post', [ &$this, 'save' ], 10, 2 );

	}

	/**
	 * Load builder assets
	 * @param string	$hook_suffix
	 */
	function load_assets( $hook_suffix ) {

		global $post_type;

		if( $this->post_type == $post_type && in_array( $hook_suffix, [ 'post.php', 'post-new.php' ] ) ) {
			wp_enqueue_media();
			wp_enqueue_editor();
			wp_enqueue_style( 't360-builder-admin', CODE_URI . 'assets/builder/t360_builder.css' );
			wp_enqueue_script( 't360-builder-admin', CODE_URI . 'assets/builder/t360_builder.js', [ 'jquery', 'jquery-ui-sortable', 'wp-tinymce' ], 1.0, true );
		}

	}

	/**
	 * Render function
	 */
	function render_builder( $post ) {

		$this->post = $post;

		if( $this->post_type !== $post->post_type ) return;

		$this->_render_builder();

	}

	/**
	 * Render builder
	 */
	private function _render_builder() {
	?>
		<div id="t360-builder" class="t360-builder">
			<span class="t360-loader">Loading builder...</span>
	<?php
		wp_nonce_field( 't360_nonce_action', 't360_nonce' );
		$this->_render_rows();
		$this->_render_actions();
		$this->_render_templates();
	?>
		</div>
	<?php
	}

	/**
	 * Render rows
	 */
	private function _render_rows() {
		$this->rows = $this->_sanitize( get_post_meta( $this->post->ID, 't360', true ) );
	?>
		<div class="t360-builder-rows">
	<?php
		if( ! $this->rows ) {
	?>
			<p class="t360-builder-msg">Add rows using the buttons below.</p>
		</div><!-- /.t360-builder-rows -->
	<?php
			return;
		} else {
	?>
			<p class="t360-builder-msg" style="display: none">Add rows using the buttons below.</p>
	<?php
		}
		foreach( $this->rows as $order => $row ) {
			$order = intval( $order );
			$this->_render_row( $order, $row );
		}
	?>
		</div><!-- /.t360-builder-rows -->
	<?php
	}

	/**
	 * Render individual row
	 */
	private function _render_row( $order, $row ) {

		$row_class = '';
		$row_title = '';
		$row_columns = '';
		$row_type = '';

		foreach( $this->row_types as $index => $row_data ) {
			if( $row[ 'type' ] == $row_data[ 'type' ] ) {
				$row_class = $index;
				$row_title = $row_data[ 'title' ];
				$row_columns = $row_data[ 'columns' ];
				$row_type = $row_data[ 'type' ];
				break;
			}
		}

	?>
		<div class="t360-row t360-<?php echo $row_class ?>">
			<div class="t360-row-title t360-row-move">
				<span class="t360-row-index"><?php echo $order + 1 ?></span>
				<h4 class="t360-row-title-text"><?php echo $row_title ?></h4>
				<span class="t360-row-remove dashicons dashicons-trash"></span>
			</div>
			<div class="t360-row-fields">
			<?php
				foreach( $row[ 'content' ] as $i => $content ) {
					$input_id = sprintf( 't360-editor-%s-%s', $order, $i + 1 );
					// $input_id = 't360-editor-' . $order . '-' . ( $i + 1 );
					$input_name = sprintf( 't360[%s][content][]', $order );
					// $input_name = 't360[' . $order . '][content][]';
			?>
				<div class="t360-col">
					<textarea id="<?php echo $input_id ?>" name="<?php echo $input_name ?>" class="t360-row-content wp-editor" data-field="content_<?php echo $i ?>"><?php echo $content ?></textarea>
				</div>
			<?php
				}
			?>
				<input name="t360[<?php echo $order ?>][type]" class="t360-row-type" type="hidden" data-field="type" value="<?php echo $row_type ?>">
			</div>
			<?php $this->_render_settings( $order, $row ) ?>
		</div>
	<?php
	}

	/**
	 * Render actions
	 */
	private function _render_actions() {
	?>
		<div class="t360-builder-actions">
			<h4>Click the appropriate button to add one row with the desired column layout.</h4>
			<div class="t360-buttons-group">
				<a href="#" class="t360-add-section" data-template="t360-1" title="Add one column">
					1 Column
					<span class="btn-columns">
						<span></span>
					</span>
				</a>
				<a href="#" class="t360-add-section" data-template="t360-2" title="Add two equal columns">
					2 Columns
					<span class="btn-columns">
						<span></span>
						<span></span>
					</span>
				</a>
				<a href="#" class="t360-add-section" data-template="t360-3" title="Add three equal columns">
					3 Columns
					<span class="btn-columns">
						<span></span>
						<span></span>
						<span></span>
					</span>
				</a>
				<a href="#" class="t360-add-section" data-template="t360-4" title="Add four equal columns">
					4 Columns
					<span class="btn-columns">
						<span></span>
						<span></span>
						<span></span>
						<span></span>
					</span>
				</a>
				<a href="#" class="t360-add-section" data-template="t360-1-2" title="Add two columns: 1 third, 2 thirds">
					1/3 - 2/3
					<span class="btn-columns col-1-2">
						<span></span>
						<span></span>
					</span>
				</a>
				<a href="#" class="t360-add-section" data-template="t360-2-1" title="Add two columns: 2 thirds, 1 third">
					2/3 - 1/3
					<span class="btn-columns col-2-1">
						<span></span>
						<span></span>
					</span>
				</a>
				<a href="#" class="t360-add-section" data-template="t360-1-3" title="Add two columns: 1 quarter, 3 quarters">
					1/4 - 3/4
					<span class="btn-columns col-1-3">
						<span></span>
						<span></span>
					</span>
				</a>
				<a href="#" class="t360-add-section" data-template="t360-3-1" title="Add two columns: 3 quarters, 1 quarter">
					3/4 - 1/4
					<span class="btn-columns col-3-1">
						<span></span>
						<span></span>
					</span>
				</a>
			</div>
		</div><!-- /.t360-builder-actions -->
	<?php
	}

	/**
	 * Render templates
	 */
	private function _render_templates() {
	?>
		<div class="t360-builder-templates">
		<?php
			foreach( $this->row_types as $row_type => $row_data ) {
		?>
			<div class="t360-row t360-<?php echo $row_type ?>">
				<div class="t360-row-title t360-row-move">
					<span class="t360-row-index">0</span>
					<h4 class="t360-row-title-text"><?php echo $row_data[ 'title' ] ?></h4>
					<span class="t360-row-remove dashicons dashicons-trash"></span>
				</div>
				<div class="t360-row-fields">
				<?php
					for( $i = 0; $i < $row_data[ 'columns' ]; $i++ ) {
				?>
					<div class="t360-col">
						<textarea id="" name="" class="t360-row-content wp-editor" data-field="content_<?php echo $i ?>"></textarea>
					</div>
				<?php
					}
				?>
					<input name="" class="t360-row-type" type="hidden" data-field="type" value="<?php echo $row_data[ 'type' ] ?>">
				</div>
				<?php $this->_render_settings() ?>
			</div>
		<?php
			}
		?>
		</div><!-- /.t360-builder-templates -->
	<?php
	}

	/**
	 * Render settings
	 */
	private function _render_settings( $order = false, $row = false ) {
	?>
		<div class="t360-row-settings">
			<div class="t360-row-title no-border">
				<h4>Settings (<?php echo $this->_count_settings( $row[ 'settings' ] ) ?>)</h4>
				<span class="t360-row-expand dashicons dashicons-arrow-down"></span>
			</div>
			<div class="t360-row-settings-inner">
			<?php
				$i = 0;
				foreach( $this->settings as $setting => $setting_data ) {
					$setting_id = '';
					$setting_name = '';
					$setting_value = '';
					if( $order !== false && is_array( $row ) ) {
						$setting_id = sprintf( 't360-setting-%s-%s', $order, $i );
						$setting_name = sprintf( 't360[%s][settings][%s]', $order, $setting );
						$setting_value = $row[ 'settings' ][ $setting ];
					}
			?>
				<div class="t360-row-setting">
					<label class="t360-setting-label" for="<?php echo $setting_id ?>">
						<strong><?php echo $setting_data[ 'label' ] ?></strong>
					<?php
						if( is_string( $setting_data[ 'helper' ] ) ) {
					?>
						<p class="helper"><?php echo $setting_data[ 'helper' ] ?></p>
					<?php
						} elseif( is_array( $setting_data[ 'helper' ] ) ) {
					?>
						<div>
					<?php
							foreach( $setting_data[ 'helper' ] as $index => $helper ) {
					?>
							<p class="helper"><?php echo $helper ?></p>
					<?php
							}
					?>
						</div>
					<?php
						}
					?>
					</label>
					<div class="t360-setting-value">
					<?php
						if( is_array( $setting_data[ 'select' ] ) ) {
					?>
						<select id="<?php echo $setting_id ?>" name="<?php echo $setting_name ?>" class="t360-setting" data-setting="<?php echo $setting ?>">
						<?php
							foreach( $setting_data[ 'select' ] as $value => $label ) {
						?>
							<option value="<?php echo $value ?>"<?php echo $value == $setting_value ? ' selected' : '' ?>><?php echo $label ?></option>
						<?php
							}
						?>
						</select>
					<?php
						} else {
					?>
						<input id="<?php echo $setting_id ?>" name="<?php echo $setting_name ?>" class="t360-setting" type="text" value="<?php echo $setting_value ?>" data-setting="<?php echo $setting ?>">
					<?php
						}
					?>
					</div>
				</div>
			<?php
				$i++;
				}
			?>
			</div>
		</div>
	<?php
	}

	/**
	 * Check empty settings
	 */
	private function _count_settings( $data ) {

		if( ! is_array( $data ) )
			return 0;

		$r = 0;

		foreach( $data as $val ) {
			if( ! empty( $val ) )
				$r++;
		}

		return $r;

	}

	/**
	 * Sanitization function
	 * @param array		$input		Data to be sanitized
	 * @return array	$output		Sanitized data
	 */
	private function _sanitize( $input ) {

		if( ! is_array( $input ) )
			return null;

		$output = [];

		foreach( $input as $index => $data ) {

			if( isset( $data[ 'type' ] ) && ! empty( $data[ 'type' ] ) ) {

				// Sanitize content
				if( is_array( $data[ 'content' ] ) ) {
					foreach( $data[ 'content' ] as $content ) {
						$output[ $index ][ 'content' ][] = wp_kses_post( $content );
					}
				} else {
					$output[ $index ][ 'content' ] = [];
				}

				// Sanitize type
				$output[ $index ][ 'type' ] = esc_attr( $data[ 'type' ] );

				// Sanitize settings
				if( is_array( $data[ 'settings' ] ) ) {
					foreach( $data[ 'settings' ] as $setting => $value ) {
						$output[ $index ][ 'settings' ][ $setting ] = esc_attr( $value );
					}
				}

			}

		}

		return $output;

	}

	/**
	 * Save data
	 */
	function save() {

		global $post;
		$post_id = $post->ID;

		$request = stripslashes_deep( $_POST );

		if( !isset( $request[ 't360_nonce' ] ) || ! wp_verify_nonce( $request[ 't360_nonce' ], 't360_nonce_action' ) ) {
			return $post_id;
		}

		if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return $post_id;
		}

		$post_type = get_post_type_object( $post->post_type );

	    if( $this->post_type != $post->post_type || ! current_user_can( $post_type->cap->edit_post, $post_id ) ) {
	        return $post_id;
	    }

		$saved_data = get_post_meta( $post_id, 't360', true );
		$submitted_data = isset( $request[ 't360' ] ) ? $this->_sanitize( $request[ 't360' ] ) : null;

		if( $submitted_data && empty( $saved_data ) ) {
			add_post_meta( $post_id, 't360', $submitted_data, true );
		} elseif( $submitted_data && ( $submitted_data != $saved_data ) ) {
			update_post_meta( $post_id, 't360', $submitted_data );
		} elseif( empty( $submitted_data ) && $saved_data ) {
			delete_post_meta( $post_id, 't360' );
		}

	}

	/**
	 * Retrieve data
	 * @param integer
	 * @return array
	 */
	static function content( $post_id = null ) {

		if( $post_id === null ) {
			global $post;
			$post_id = $post->ID;
		}

		return get_post_meta( $post_id, 't360', true );

	}

}
