<?php

namespace IPS\chatbox\Rooms;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Package Item Model
 */
class _Chat extends \IPS\Content\Item
{
	use \IPS\Content\Reportable;
	
	/**
	 * @brief	Application
	 */
	public static $application = 'chatbox';
	
	/**
	 * @brief	Module
	 */
	public static $module = 'chatbox';
	
	/**
	 * @brief	Database Table
	 */
	public static $databaseTable = 'chatbox_room_posts';
	
	/**
	 * @brief	Database Prefix
	 */
	public static $databasePrefix = 'chat_';
	
	/**
	 * @brief	Node Class
	 */
	public static $containerNodeClass = 'IPS\chatbox\Rooms\Room';
	
	/**
	 * @brief	Multiton Store
	 */
	protected static $multitons;
	
	/**
	 * @brief	[ActiveRecord] ID Database Column
	 */
	public static $databaseColumnId = 'id';
	
	/**
	 * @brief	Language prefix for forms
	 */
	public static $formLangPrefix = 'chatbox_';
	
	/**
	 * @brief	Title
	 */
	public static $title = 'chatbox_msg';
	
	/**
	 * @brief	Icon
	 */
	public static $icon = 'comment';

	/**
	 * @brief	Database Column Map
	 */
	public static $databaseColumnMap = array(
		'container'				=> 'room',
		'author'				=> 'member_id',
		'date'					=> 'time',
		'title'					=> 'title',
		'content'				=> 'content',
	);	
	
	/**
	 * @brief	Cached URLs
	 */
	protected $_url	= array();
	
	/**
	 * @brief	URL Base
	 */
	public static $urlBase = 'app=chatbox&module=chatbox&controller=msg&id=';
	
	/**
	 * @brief	URL Template
	 */
	public static $urlTemplate = '';
	
	/**
	 * @brief	SEO Title Column
	 */
	public static $seoTitleColumn = '';
	
	/**
	 * @brief	[Content\Item]	Include the ability to search this content item in global site searches
	 */
	public static $includeInSiteSearch = FALSE;	
	
	/**
	 * Can move?
	 *
	 * @param	\IPS\Member|NULL	$member	The member to check for (NULL for currently logged in member)
	 * @return	bool
	 */
	public function canMove( $member=NULL )
	{
		return FALSE;
	}
	
	/**
	 * Get items with permisison check
	 *
	 * @param	array		$where				Where clause
	 * @param	string		$order				MySQL ORDER BY clause (NULL to order by date)
	 * @param	int|array	$limit				Limit clause
	 * @param	string		$permissionKey		A key which has a value in the permission map (either of the container or of this class) matching a column ID in core_permission_index
	 * @param	bool|NULL	$includeHiddenItems	Include hidden files? Boolean or NULL to detect if currently logged member has permission
	 * @param	int			$queryFlags			Select bitwise flags
	 * @param	\IPS\Member	$member				The member (NULL to use currently logged in member)
	 * @param	bool		$joinContainer		If true, will join container data (set to TRUE if your $where clause depends on this data)
	 * @param	bool		$joinComments		If true, will join comment data (set to TRUE if your $where clause depends on this data)
	 * @param	bool		$joinReviews		If true, will join review data (set to TRUE if your $where clause depends on this data)
	 * @return	\IPS\Patterns\ActiveRecordIterator|int
	 */
	public static function getItemsWithPermission( $where=array(), $order=NULL, $limit=10, $permissionKey='read', $includeHiddenItems=\IPS\Content\Hideable::FILTER_AUTOMATIC, $queryFlags=0, \IPS\Member $member=NULL, $joinContainer=FALSE, $joinComments=FALSE, $joinReviews=FALSE, $countOnly=FALSE, $joins=NULL, $skipPermission=FALSE, $joinTags=TRUE, $joinAuthor=TRUE, $joinLastCommenter=TRUE, $showMovedLinks=FALSE )
	{
		$joins[] = array(
			'from'		=> array( "chatbox_files", "file" ),
			'where'		=> "file.file_from='room' AND file.file_msg_id=chatbox_room_posts.chat_id",
		);

		return parent::getItemsWithPermission( $where, $order, $limit, $permissionKey, $includeHiddenItems, $queryFlags, $member, $joinContainer, $joinComments, $joinReviews, $countOnly, $joins, $skipPermission, $joinTags, $joinAuthor, $joinLastCommenter, $showMovedLinks );
	}
	
	/**
	 * Construct Load Query
	 *
	 * @param	int|string	$id					ID
	 * @param	string		$idField			The database column that the $id parameter pertains to
	 * @param	mixed		$extraWhereClause	Additional where clause(s)
	 * @return	\IPS\Db\Select
	 */
	protected static function constructLoadQuery( $id, $idField, $extraWhereClause )
	{
		$parent = parent::constructLoadQuery( $id, $idField, $extraWhereClause );

		$parent->join( array( "chatbox_files", "file" ), "file.file_from='room' AND file.file_msg_id=chatbox_room_posts.chat_id" );
	
		return $parent;
	}
	
	/**
	 * Get elements for add/edit form
	 *
	 * @param	\IPS\Content\Item|NULL	$item				The current item if editing or NULL if creating
	 * @param	\IPS\Node\Model|NULL	$container			Container (e.g. forum), if appropriate
	 * @param	bool 					$fromCreateMenu		false to deactivate the minimize feature
	 * @return	array
	 */
	public static function formElements( $item=NULL, \IPS\Node\Model $container=NULL , $fromCreateMenu=FALSE)
	{
		$opts = $container->options();
		
		// $formElements = parent::formElements( $item, $container );

		// unset( $formElements['title'] );
		// unset( $formElements['captcha'] );
		
		$editorName = 'chatMSG_' . $container->id;
		
		if( $item !== NULL )
		{
			$editorName .= '_' . $item->id;
		}
			
		if ( $opts['use_editor'] )
		{
			$formElements['chatbox_content'] = new \IPS\Helpers\Form\Editor( $editorName, ( $item ) ? $item->content : NULL, TRUE, array(
				'app'			=> 'chatbox',
				'key'			=> 'roomMSG',
				'autoSaveKey' 	=> 'room_msg' . ( ( $item !== NULL ) ? '_' . $item->id : '' ),
				'minimize'		=> NULL,
				'attachIds'		=> ( $item === NULL ) ? NULL : array( $item->id, NULL, $item->member_id ),
				'autoGrow'		=> TRUE,
				'maxLength'		=> $opts['length'] > 0 ? $opts['length'] : NULL,
			) );
		}
		else
		{
			$formElements['chatbox_content'] = new \IPS\Helpers\Form\TextArea( $editorName, ( $item ) ? $item->content : NULL, FALSE, array( 
				'rows' 			=> 1,
				'class'			=> 'chatInput',
				'placeholder'	=> \IPS\Member::loggedIn()->language()->addToStack('chatbox_input_pl'),
			) );
			
			if ( $container->canUpload() )
			{
				$formElements['chatbox_file'] = \IPS\Application::load('chatbox')->uploader( 'file_room_' . $container->id, $item );
			}
		}
		
		return $formElements;
	}
	
	/**
	 * Create from form
	 *
	 * @param	array					$values				Values from form
	 * @param	\IPS\Node\Model|NULL	$container			Container (e.g. forum), if appropriate
	 * @param	bool					$sendNotification	TRUE to automatically send new content notifications (useful for items that may be uploaded in bulk)
	 * @return	\IPS\Content\Item
	 */
	public static function createFromForm( $values, \IPS\Node\Model $container = NULL, $sendNotification = FALSE )
	{
		$opts = $container->options();
		
		/* Create */
		$chat = parent::createFromForm( $values, $container, $sendNotification );
		
		/* Attachment */
		if ( $opts['use_editor'] )
		{
			\IPS\File::claimAttachments( 'room_msg', $chat->id, NULL, NULL );
		}
		
		/* Return */
		return $chat;
	}
	
	/**
	 * Process create/edit form
	 *
	 * @param	array				$values	Values from form
	 * @return	void
	 */
	public function processForm( $values )
	{
		parent::processForm( $values );

		if ( $this->_new )
		{
			$this->room = $values['chatbox_room'];
			$this->member_id = \IPS\Member::loggedIn()->member_id;
			$this->guestName = \IPS\Member::loggedIn()->member_id > 0 ? \IPS\Member::loggedIn()->member_id : \IPS\Request::i()->cookie['chatbox_guestName'];
			$this->time = time();
		}
		
		if ( \IPS\Request::i()->_report > 0 )
		{
			$content = $values[ 'chatbox_content_' . $this->id ];
		}
		else 
		{
			$content = $values[ 'chatMSG_' . $this->container()->id ];
		}
		
		$this->content = $content;
		$this->title = \IPS\Application::load('chatbox')->autoTitle( $content ? $content : \IPS\Member::loggedIn()->language()->get('chatbox_txt_img') );
		$this->title_furl = \IPS\Http\Url\Friendly::seoTitle( $this->title );	
		
		$this->save();
	}	
	
	/**
	 * Should posting this increment the poster's post count?
	 *
	 * @param	\IPS\Node\Model|NULL	$container	Container
	 * @return	void
	 */
	public static function incrementPostCount( \IPS\Node\Model $container = NULL )
	{
		return FALSE;
	}
	
	/**
	 * Do not add sitemap
	 *
	 * @return	array
	 */
	public static function sitemapWhere()
	{
		return array( array( 'chatbox_room_posts.chat_id=?', 0 ) );
	}
	
	/**
	 * Can delete?
	 *
	 * @param	\IPS\Member|NULL	$member	The member to check for (NULL for currently logged in member)
	 * @return	bool
	 */
	public function canDelete( $member=NULL )
	{
		$member = $member ?: \IPS\Member::loggedIn();
		return $this->container()->_canDelete( $member->member_id );
	}	
	
	/**
	 * Can edit?
	 *
	 * @param	\IPS\Member|NULL	$member	The member to check for (NULL for currently logged in member)
	 * @return	bool
	 */
	public function canEdit( $member=NULL )
	{
		$member = $member ?: \IPS\Member::loggedIn();
		return $this->container()->canEditMsg( $this );
	}	

	/**
	 * @brief	Cache of normal images
	 */
	protected $_imagesNormal = NULL;

	/**
	 * @brief	Cache of thumbnails
	 */
	protected $_imagesThumbs = NULL;

	/**
	 * Get images
	 * @return	\IPS\File\Iterator
	 */
	public function images( $type=0 )
	{
		switch ( $type )
		{
			case 0:
				if( $this->_imagesNormal !== NULL )
				{
					return $this->_imagesNormal;
				}
				$valueField = 'file_location';
				$property	= "_imagesNormal";
				break;
			case 1:
				if( $this->_imagesThumbs !== NULL )
				{
					return $this->_imagesThumbs;
				}
				$valueField = 'file_thumb';
				$property	= "_imagesThumbs";
				break;
			default:
				throw new \InvalidArgumentException;
		}
		
		$where = array( array( 'file_from=? AND file_msg_id=?', 'room', $this->id ) );

		$iterator = \IPS\Db::i()->select( '*', 'chatbox_files', $where )->setKeyField( 'file_id' );
		$iterator = new \IPS\File\Iterator( $iterator, 'chatbox_File', $valueField, FALSE, 'file_realname' );
		$iterator = new \CachingIterator( $iterator, \CachingIterator::FULL_CACHE );

		$this->$property = $iterator;
		return $this->$property;
	}
	
	/**
	 * Delete Record
	 *
	 * @return	void
	 */
	public function delete()
	{
		parent::delete();
		\IPS\Application::load('chatbox')->deleteFilesFromMSG( 'room', $this->id );
	}	


}