<?php
/**
 * @version    $Id$
* @package    IT_Theme_Framework
* @author     InnoThemes Team <support@innothemes.com>
* @copyright  Copyright (C) 2012 InnoThemes.com. All Rights Reserved.
* @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*
* Websites: http://www.innothemes.com
*/

/**
 * Post selector field renderer.
*
* @package  IT_Theme_Framework
* @since    1.0.0
*/
class IT_Form_Field_Post_Selector extends IT_Form_Field_Select {
	/**
	 * Field type.
	 *
	 * @var  string
	 */
	protected $type = 'post-selector';

	/**
	 * Post type to retrieve post for.
	 *
	 * @var  string
	 */
	protected $post_type = 'post';

	/**
	 * Number of post to retrieve per request.
	 *
	 * @var  integer
	 */
	protected $posts_per_page = 10;

	/**
	 * Offset to start retrieve post.
	 *
	 * @var  integer
	 */
	protected $offset = 0;

	/**
	 * Category to retrieve post from.
	 *
	 * @var  string
	 */
	protected $category = '';

	/**
	 * Order post by.
	 *
	 * @var  string
	 */
	protected $orderby = 'post_date';

	/**
	 * Order direction.
	 *
	 * @var  string
	 */
	protected $order = 'DESC';

	/**
	 * Post status.
	 *
	 * @var  string
	 */
	protected $post_status = 'publish';

	/**
	 * Whether to apply filters or not?
	 *
	 * @var  string
	 */
	protected $suppress_filters = true;

	/**
	 * Constructor.
	 *
	 * @param   array  $config  Field declaration.
	 *
	 * @return  void
	 */
	public function __construct( $config ) {
		parent::__construct( $config );

		// Get post matching specified condition
		$posts = get_posts(
			array(
				'posts_per_page'   => $this->posts_per_page,
				'offset'           => $this->offset,
				'category'         => $this->category,
				'orderby'          => $this->orderby,
				'order'            => $this->order,
				'post_type'        => $this->post_type,
				'post_status'      => $this->post_status,
				'suppress_filters' => $this->suppress_filters,
			)
		);

		foreach ( $posts as $post ) {
			$truncated_name = wp_html_excerpt( $post->post_title, 40 );

			$this->choices[ $post->ID ] = ( $truncated_name == $post->post_title ) ? $post->post_title : trim( $truncated_name ) . '&hellip;';
		}

		// Reset field type to select
		$this->type = 'select';
	}
}
