<?php


namespace IPS\chatbox\modules\admin\chatbox;

/* 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;
}

/**
 * tools
 */
class _tools extends \IPS\Dispatcher\Controller
{
	/**
	 * @brief	Has been CSRF-protected
	 */
	public static $csrfProtected = TRUE;
		
		
	/**
	 * Execute
	 *
	 * @return	void
	 */
	public function execute()
	{
		\IPS\Dispatcher::i()->checkAcpPermission( 'tools_manage' );
		parent::execute();
	}

	/**
	 * ...
	 *
	 * @return	void
	 */
	protected function manage()
	{
		\IPS\Output::i()->title = \IPS\Member::loggedIn()->language()->addToStack('menu__chatbox_chatbox_tools');
		\IPS\Output::i()->output = \IPS\Theme::i()->getTemplate('tools', 'chatbox', 'admin')->tools();
	}
	
	/**
	 * Delete room's messages
	 */
	protected function cleanRooms()
	{
		\IPS\Session::i()->csrfCheck();
		
		\IPS\Output::i()->title = \IPS\Member::loggedIn()->language()->addToStack('chatbox_cleaning_msg');
		
		$perGo = 30;
				
		$multiRedirectUrl = \IPS\Http\Url::internal( 'app=chatbox&module=chatbox&controller=tools&do=cleanRooms' )->csrf();
		if ( (int) \IPS\Request::i()->sys == 1 )
		{
			$where[] = array( 'chat_sys IS NOT NULL' );
			$multiRedirectUrl = $multiRedirectUrl->setQueryString( 'sys', 1 );
			$sys = true;
		}
		
		if ( (int) \IPS\Request::i()->fromDays > 0 )
		{
			$days = (int) \IPS\Request::i()->fromDays;
			$multiRedirectUrl = $multiRedirectUrl->setQueryString( 'fromDays', $days );
			$where[] = array(  'chat_time<?',  \IPS\DateTime::create()->sub( new \DateInterval( 'P' . $days . 'D' ) )->getTimestamp() );
		}
		
		$total = \IPS\Db::i()->select( 'COUNT(*)', 'chatbox_room_posts', $where )->first();
		
		if ( ! \IPS\Request::i()->totalMsg )
		{
			$multiRedirectUrl = $multiRedirectUrl->setQueryString( 'totalMsg', $total );
		}
		
		\IPS\Output::i()->output = new \IPS\Helpers\MultipleRedirect( $multiRedirectUrl, 
		
		function( $doneSoFar ) use( $perGo, $where, $sys )
		{		
			if ( ! \IPS\Request::i()->totalMsg )
			{
				return NULL;
			}
			
			if ( $sys )
			{
				\IPS\Db::i()->delete( 'chatbox_room_posts', $where, NULL, $perGo );
			}
			else
			{
				foreach( \IPS\Db::i()->select( '*', 'chatbox_room_posts', $where, NULL, $perGo ) as $chat )
				{
					\IPS\Application::load('chatbox')->deleteFilesFromMSG( 'room', $chat['chat_id'] );
					\IPS\File::unclaimAttachments( 'chatbox_roomMSG', $chat['chat_id'] );
					\IPS\Db::i()->delete( 'chatbox_room_posts', array( 'chat_id=?', $chat['chat_id'] ) );	
				}
			}
			
			$doneSoFar += $perGo;
			
			if ( $doneSoFar - $perGo >= \IPS\Request::i()->totalMsg )
			{
				return NULL;
			}
	
			return array( $doneSoFar, \IPS\Member::loggedIn()->language()->addToStack( 'chatbox_cleaning_msg_txt' , FALSE, array( 'sprintf' => $doneSoFar > \IPS\Request::i()->totalMsg ? \IPS\Request::i()->totalMsg : $doneSoFar . '/' . \IPS\Request::i()->totalMsg ) ), ( 100 * $doneSoFar ) / \IPS\Request::i()->totalMsg );
		}, 
		function()
		{
			\IPS\Output::i()->redirect( \IPS\Http\Url::internal( 'app=chatbox&module=chatbox&controller=tools' ), 'completed' );			
		} );	
	}

	/**
	 * Delete member's messages
	 */
	protected function cleanCons()
	{
		\IPS\Session::i()->csrfCheck();
		
		\IPS\Output::i()->title = \IPS\Member::loggedIn()->language()->addToStack('chatbox_cleaning_msg');
		
		$perGo = 20;
				
		$multiRedirectUrl = \IPS\Http\Url::internal( 'app=chatbox&module=chatbox&controller=tools&do=cleanCons' )->csrf();

		if ( (int) \IPS\Request::i()->fromDays > 0 )
		{
			$days = (int) \IPS\Request::i()->fromDays;
			$multiRedirectUrl = $multiRedirectUrl->setQueryString( 'fromDays', $days );
			$where[] = array(  'chat_time<?',  \IPS\DateTime::create()->sub( new \DateInterval( 'P' . $days . 'D' ) )->getTimestamp() );
		}
		
		$total = \IPS\Db::i()->select( 'COUNT(*)', 'chatbox_conversations_posts', $where )->first();
		
		if ( ! \IPS\Request::i()->totalMsg )
		{
			$multiRedirectUrl = $multiRedirectUrl->setQueryString( 'totalMsg', $total );
		}
		
		\IPS\Output::i()->output = new \IPS\Helpers\MultipleRedirect( $multiRedirectUrl, 
		function( $doneSoFar ) use( $perGo, $where )
		{		
			if ( ! \IPS\Request::i()->totalMsg )
			{
				return NULL;
			}
			
			foreach( \IPS\Db::i()->select( '*', 'chatbox_conversations_posts', $where, NULL, $perGo ) as $chat )
			{
				\IPS\Application::load('chatbox')->deleteFilesFromMSG( 'con', $chat['chat_id'] );
				\IPS\File::unclaimAttachments( 'chatbox_conMSG', $chat['chat_id'] );
				\IPS\Db::i()->delete( 'chatbox_conversations_posts', array( 'chat_id=?', $chat['chat_id'] ) );
			}
			
			$doneSoFar += $perGo;
			
			if ( $doneSoFar - $perGo >= \IPS\Request::i()->totalMsg )
			{
				return NULL;
			}
	
			return array( $doneSoFar, \IPS\Member::loggedIn()->language()->addToStack( 'chatbox_cleaning_msg_txt' , FALSE, array( 'sprintf' => $doneSoFar > \IPS\Request::i()->totalMsg ? \IPS\Request::i()->totalMsg : $doneSoFar . '/' . \IPS\Request::i()->totalMsg ) ), ( 100 * $doneSoFar ) / \IPS\Request::i()->totalMsg );
		}, 
		function()
		{
			if ( ! \IPS\Request::i()->fromDays )
			{
				\IPS\Db::i()->delete( 'chatbox_conversations' );
				\IPS\Db::i()->delete( 'chatbox_conversations_user_map' );	
			}
			
			\IPS\Output::i()->redirect( \IPS\Http\Url::internal( 'app=chatbox&module=chatbox&controller=tools' ), 'completed' );			
		} );	
	}

	/**
	 * Import all messages from Chatbox Free
	 */
	protected function importFromFree()
	{
		\IPS\Session::i()->csrfCheck();
		
		\IPS\Output::i()->title = \IPS\Member::loggedIn()->language()->addToStack('chatbox_importing_msg');
		
		if ( ! \IPS\Db::i()->checkForTable('bimchatbox_chat') )
		{
			\IPS\Output::i()->error( 'chatbox_error_import_no_free', '2CHATBOX105/2', 404 );
		}
		
		$roomID = (int) \IPS\Request::i()->roomID;
		$multiRedirectUrl = \IPS\Http\Url::internal( 'app=chatbox&module=chatbox&controller=tools&do=importFromFree' )->csrf();
		
		try
		{
			$room = \IPS\chatbox\Rooms\Room::load( $roomID );
			$multiRedirectUrl = $multiRedirectUrl->setQueryString( 'roomID', $room->id );
		}
		catch ( \OutOfRangeException $e )
		{
			\IPS\Output::i()->error( 'chatbox_error_import_no_room', '2CHATBOX105/3', 404 );
		}
		
		$perGo = 100;

		\IPS\Output::i()->output = new \IPS\Helpers\MultipleRedirect( $multiRedirectUrl, 
		function( $doneSoFar ) use( $perGo )
		{
			$select = \IPS\Db::i()->select( '*', 'bimchatbox_chat', NULL, 'time ASC', array( $doneSoFar, $perGo ) );
			$total = (int) \IPS\Db::i()->select( 'COUNT(*)', 'bimchatbox_chat', NULL )->first();

			if ( $total == 0 )
			{
				return NULL;
			}
						
			foreach ( $select as $row )
			{
				$title = \IPS\Application::load('chatbox')->autoTitle( $row['chat'] );
				$title_furl = \IPS\Http\Url\Friendly::seoTitle( $title );				
				\IPS\Db::i()->insert( 'chatbox_room_posts', array(
					'chat_room'				=> (int) \IPS\Request::i()->roomID,
					'chat_member_id'		=> $row['user'],
					'chat_content'			=> $row['chat'],
					'chat_title'			=> $title,
					'chat_title_furl'		=> $title_furl,
					'chat_time'				=> $row['time'],
				) );
			}
			
			$doneSoFar += $perGo;	
				
			return array( $doneSoFar, \IPS\Member::loggedIn()->language()->addToStack( 'chatbox_importing_msg_txt' , FALSE, array( 'sprintf' => $doneSoFar > $total ? $total : $doneSoFar . '/' . $total ) ), ( 100 * $doneSoFar ) / $total );
		}, 
		function()
		{
			\IPS\Output::i()->redirect( \IPS\Http\Url::internal( 'app=chatbox&module=chatbox&controller=tools' ), 'completed' );			
		} );	
	}






	 
}