<?php

namespace Tech360;

defined( 'ABSPATH' ) or die;

class Cpt {

	private $key;
	private $labels;
	private $args;
	private $textdomain;
	private $private;
	private $columns;
	private $column_fields;
	private $sortable_columns;
	private $shortcode_columns;

	/**
	 * Class constructor
	 * @param string	$key			Post type key / slug
	 * @param array		$labels			Array of post type labels
	 * @param array		$args			Array of arguments
	 * @param string	$textdomain		Theme text domain
	 * @param bool		$private		Specify if the post type should be publicly displayable or not
	 */
	function __construct( $key, $labels = null, $args = null, $textdomain = 'tech360', $private = true ) {

		$this->key = $key;
		$this->textdomain = $textdomain;
		$this->private = $private;
		$this->labels = $this->_labels( $labels );
		$this->args = $this->_args( $args );

		add_action( 'init', array( $this, '_register' ), 0 );

	}

	/**
	 * Construct labels array
	 * @param array		Labels array
	 * @return array	Complete labels array
	 */
	function _labels( $labels ) {

		$return = array();
		$s_name = empty( $labels[ 'singular_name' ] ) ? ucwords( str_replace( '_', ' ', $this->key ) ) : $labels[ 'singular_name' ];
		$p_name = empty( $labels[ 'name' ] ) ? ucwords( str_replace( '_', ' ', $this->key ) ) . 's' : $labels[ 'name' ];
		$td = $this->textdomain;

		$return[ 'name' ] = _x( $p_name, 'Post Type General Name', $td );
		$return[ 'singular_name' ] = _x( $s_name, 'Post Type Singular Name', $td );

		$return[ 'menu_name' ] = __( $p_name, $td );
		$return[ 'name_admin_bar' ] = __( $s_name, $td );
		$return[ 'archives' ] = __( $s_name . ' Archives', $td );
		$return[ 'parent_item_colon' ] = 'Parent item:';
		$return[ 'all_items' ] = __( 'All ' . $p_name, $td );
		$return[ 'add_new_item' ] = __( 'Add New ' . $s_name, $td );
		$return[ 'add_new' ] = 'Add new';
		$return[ 'new_item' ] = __( 'New ' . $s_name, $td );
		$return[ 'edit_item' ] = __( 'Edit ' . $s_name, $td );
		$return[ 'update' ] = __( 'Update ' . $s_name, $td );
		$return[ 'view_item' ] = __( 'View ' . $s_name, $td );
		$return[ 'view_items' ] = __( 'View ' . $p_name, $td );
		$return[ 'search_items' ] = __( 'Search ' . $p_name, $td );
		$return[ 'not_found' ] = __( 'No ' . $p_name . ' found', $td );
		$return[ 'not_found_in_trash' ] = __( 'No ' . $p_name . ' found in trash', $td );
		$return[ 'featured_image' ] = __( $s_name . ' featured image', $td );
		$return[ 'set_featured_image' ] = __( 'Set ' . $s_name . ' featured image', $td );
		$return[ 'remove_featured_image' ] = __( 'Remove ' . $s_name . ' featured image', $td );
		$return[ 'use_featured_image' ] = __( 'Use as ' . $s_name . ' featured image', $td );
		$return[ 'insert_into_item' ] = __( 'Insert into ' . $s_name, $td );
		$return[ 'uploaded_to_this_item' ] = __( 'Upload to this ' . $s_name, $td );
		$return[ 'items_list' ] = __( $p_name . ' list', $td );
		$return[ 'items_list_navigation' ] = __( $p_name . ' list navigation', $td );
		$return[ 'filter_items_list' ] = __( 'Filter ' . $p_name . ' list', $td );

		return $return;

	}

	/**
	 * Construct arguments array
	 * @param array		Params array
	 * @return array	Complete parameters
	 */
	function _args( $args ) {

		$return = array();
		$td = $this->textdomain;

		$return[ 'label' ] = __( $this->labels[ 'singular_name' ], $td );
		$return[ 'description' ] = empty( $args[ 'description' ] ) ? __( 'Description not provided', $td ) : __( $args[ 'description' ], $td );
		$return[ 'labels' ] = $this->labels;
		$return[ 'menu_icon' ] = empty( $args[ 'menu_icon' ] ) ? 'dashicons-format-aside' : $args[ 'menu_icon' ];
		$return[ 'menu_position' ] = empty( $args[ 'menu_position' ] ) ? 26 : $args[ 'menu_position' ];
		$return[ 'supports' ] = empty( $args[ 'supports' ] ) ? array( 'title', 'editor', 'thumbnail', 'page-attributes' ) : $args[ 'supports' ];
		$return[ 'taxonomies' ] = empty( $args[ 'taxonomies' ] ) ? array() : $args[ 'taxonomies' ];
		$return[ 'capability_type' ] = empty( $args[ 'capability_type' ] ) ? 'page' : $args[ 'capability_type' ];
		$return[ 'hierarchical' ] = empty( $args[ 'hierarchical' ] ) ? false : $args[ 'hierarchical' ];
		$return[ 'show_ui' ] = true;
		$return[ 'show_in_menu' ] = true;
		$return[ 'show_in_admin_bar' ] = true;

		if( $this->private ) {
			$return[ 'public' ] = false;
			$return[ 'show_in_nav_menus' ] = false;
			$return[ 'can_export' ] = false;
			$return[ 'has_archive' ] = false;
			$return[ 'exclude_from_search' ] = true;
			$return[ 'publicly_queryable' ] = false;
			$return[ 'show_in_rest' ] = false;
			$return[ 'rewrite' ] = false;
		} else {
			$return[ 'public' ] = true;
			$return[ 'show_in_nav_menus' ] = true;
			$return[ 'can_export' ] = true;
			$return[ 'has_archive' ] = true;
			$return[ 'exclude_from_search' ] = false;
			$return[ 'publicly_queryable' ] = true;
			$return[ 'show_in_rest' ] = true;
			if( $args[ 'rewrite' ] === false ) {
				$return[ 'rewrite' ] = false;
			} elseif( is_array( $args[ 'rewrite' ] ) ) {
				$return[ 'rewrite' ] = $args[ 'rewrite' ];
			}
		}

		return $return;

	}

	/**
	 * Custom columns
	 * @param array		$columns	Array of columns, column labels and fields
	 * @param bool		$image		True if featured image should be one of the columns. Default true
	 * @param bool		$date		True if post publish date should be displayed. Default false
	 */
	function columns( $columns, $image = true, $date = false ) {

		$this->columns = array(
			'cb' => '<input type="checkbox">',
			'title' => __( 'Title' )
		);

		if( $image )
			$this->columns[ 'image' ] = __( 'Image' );

		foreach( $columns as $key => $column ) {
			$this->columns[ $key ] = __( $column[ 'label' ], $this->textdomain );
			if( array_key_exists( 'field', $column ) ) {
				$this->column_fields[ $key ] = $column[ 'field' ];
			}
			if( array_key_exists( 'sortable', $column ) ) {
				$this->sortable_columns[] = $key;
			}
			if( 'shortcode' === $key ) {
				$this->shortcode_columns[ $key ] = $column[ 'content' ];
			}
		}

		if( $date )
			$this->columns[ 'date' ] = __( 'Date' );

		add_filter( 'manage_' . $this->key . '_posts_columns', [ $this, '_set_columns' ] );
		add_action( 'manage_' . $this->key . '_posts_custom_column', [ $this, '_populate_columns' ], 10, 2 );
		add_filter( 'manage_edit-' . $this->key . '_sortable_columns', [ $this, '_sort_columns' ] );
		add_action( 'pre_get_posts', [ $this, '_sort_columns_orderby' ] );

	}

	/**
	 * Set columns
	 */
	function _set_columns( $columns ) {
		$columns = $this->columns;
		return $columns;
	}

	/**
	 * Make columns sortable
	 */
	function _sort_columns( $columns ) {

		if( is_array( $this->sortable_columns ) ) {
			foreach( $this->sortable_columns as $column ) {
				if( 'menu_order' === $column )
					$columns[ 'menu_order' ] = 'menu_order';
				else
					$columns[ $column ] = $this->column_fields[ $column ];
			}
		}

		return $columns;

	}

	function _sort_columns_orderby( $query ) {
		if( ! is_admin() || ! $query->is_main_query() )
			return;
		if( ! is_array( $this->sortable_columns ) )
			return;
		foreach( $this->sortable_columns as $column ) {
			if( $this->column_fields[ $column ] === $query->get( 'orderby' ) ) {
				$query->set( 'orderby', 'meta_value' );
				$query->set( 'meta_key', $this->column_fields[ $column ] );

			}
		}
	}

	/**
	 * Populate columns
	 */
	function _populate_columns( $column, $post_id ) {

		$field = $this->column_fields[ $column ];

		if( 'menu_order' === $column ) {
			echo get_post( $post_id )->menu_order;
			return;
		}

		if( 'image' === $column ) {
			$thumb = get_the_post_thumbnail( $post_id, 'tiny-thumbnail' );
			echo empty( $thumb ) ? 'Not set' : $thumb;
			return;
		}

		if( 'gallery' === $column ) {
			$field = empty( $field ) ? 'vehicle_gallery' : $field;
			$gallery = acf_photo_gallery( $field, $post_id );
			if( empty( $gallery ) )
				echo 'Not set';
			else {
				foreach( $gallery as $img ) {
					$img_id = $img[ 'id' ];
					$img = wp_get_attachment_image_src( $img_id, 'micro-thumbnail-square' )[ 0 ];
					echo sprintf( '<img src="%s" style="margin: 0 5px 5px 0">', $img );
				}
			}
			return;
		}

		if( 'slides' === $column ) {
			$slides = get_field( $field, $post_id );
			if( empty( $slides ) )
				echo 'Not set';
			else {
			?>
				<ul>
					<style scoped>
						ul li img {
							vertical-align: middle;
							margin-right: 10px;
						}
					</style>
			<?php
				foreach( $slides as $slide ) {
					$image = get_the_post_thumbnail( $slide->ID, 'micro-thumbnail-square' );
					$title = $slide->post_title;
				?>
					<li>
						<?php echo empty( $image ) ? '' : $image; echo $title ?>
					</li>
				<?php
				}
			?>
				</ul>
			<?php
			}
			return;
		}

		if( 'shortcode' === $column ) {
		?>
			<style scoped>
				pre {
					background: #6c6c6c;
					color: #fff;
					border-radius: 2px;
					padding: .5em;
					margin: 0;
					display: inline-block;
				}
			</style>
		<?php
			echo '<pre onclick="selectText(this)">';
			echo sprintf( $this->shortcode_columns[ 'shortcode' ], $post_id );
			echo '</pre>';
		?>
			<script>
				function selectText( elm ) {
					if( document.selection ) {
						var range = document.body.createTextRange();
						range.moveToElementText( elm );
						range.select();
					} else if( window.getSelection ) {
						var range = document.createRange();
						range.selectNode( elm );
						window.getSelection().removeAllRanges();
						window.getSelection().addRange( range );
					}
				}
			</script>
		<?php
			return;
		}

		if( 'content_preview' === $column ) {
			$excerpt = tech360_excerpt( $post_id, 40, false, false );
			echo empty( $excerpt ) ? 'Not set' : $excerpt;
			return;
		}

		$field_value = get_field( $field, $post_id );
		if( is_array( $field_value ) ) {
			$multi = false;
			foreach( $field_value as $val ) {
				if( is_array( $val ) ) {
					$multi = true;
				}
			}
			if( $multi ) {
				$f_val = [];
				foreach( $field_value as $val ) {
					$f_val[] = $val[ 'label' ];
				}
				$field_value = implode( ', ', $f_val );
			} else {
				$field_value = $field_value[ 'label' ];
			}
		}
		echo empty( $field_value ) ? 'Not set' : $field_value;

	}

	/**
	 * Register post type
	 */
	function _register() {
		register_post_type( $this->key, $this->args );
	}

	/**
	 * Get all posts
	 * @param array			$args		Query arguments
	 * @return array		Array of posts
	 */
	function get_all( $args = null ) {

		if( empty( $args ) ) {
			$query_args = [
				'post_type' => $this->key,
				'posts_per_page' => -1,
				'orderby' => 'menu_order',
				'order' => 'ASC'
			];
		} else {
			$query_args = $args;
			$query_args[ 'post_type' ] = $this->key;
		}

		return get_posts( $query_args );

	}

	/**
	 * Get post by ID
	 * @param integer		$post_id	Custom post ID
	 * @return
	 */
	function get( $post_id ) {

		if( gettype( $post_id ) != 'integer' )
			return false;

		if( get_post_type( $post_id ) != $this->key )
			return false;

		return get_post( $post_id );

		// $args = [
		// 	'posts_per_page' => 1,
		// 	'post__in' => [ $post_id ]
		// ];
		//
		// $post = $this->get_all( $args );
		//
		// if( empty( $post ) )
		// 	return false;
		//
		// if( is_array( $post ) )
		// 	return $post[ 0 ];
		//
		// return false;

	}

}
