<?php

/**
 * <pre>
 * Invision Power Services
 * IP.CCS articles AJAX operations
 * Last Updated: $Date: 2009-09-08 18:08:49 -0400 (Tue, 08 Sep 2009) $
 * </pre>
 *
 * @author 		$Author: bfarber $
 * @copyright	(c) 2001 - 2009 Invision Power Services, Inc.
 * @license		http://www.invisionpower.com/community/board/license.html
 * @package		IP.Content
 * @since		19th Nov 2009
 * @version		$Revision: 75 $
 */

if ( ! defined( 'IN_ACP' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly.";
	exit();
}

class admin_ccs_ajax_articles extends ipsAjaxCommand
{
	/**
	 * Shortcut for url
	 *
	 * @access	private
	 * @var		string			URL shortcut
	 */
	private $form_code;
	
	/**
	 * Shortcut for url (javascript)
	 *
	 * @access	private
	 * @var		string			JS URL shortcut
	 */
	private $form_code_js;
	
	/**
	 * HTML library
	 *
	 * @access	public
	 * @var		object
	 */
	public $html;

	/**
	 * Database info
	 *
	 * @access	public
	 * @var		array 			DB info
	 */	
	public $database			= array();
	
	/**
	 * Fields array
	 *
	 * @access	public
	 * @var		array 			Fields
	 */	
	public $fields				= array();

	/**
	 * Main class entry point
	 *
	 * @access	public
	 * @param	object		ipsRegistry reference
	 * @return	void		[Outputs to screen]
	 */
	public function doExecute( ipsRegistry $registry ) 
	{
		//-----------------------------------------
		// Load Language & Skin
		//-----------------------------------------
		
		ipsRegistry::getClass('class_localization')->loadLanguageFile( array( 'admin_lang' ) );
		$this->html = $this->registry->output->loadTemplate( 'cp_skin_articles' );

		//-----------------------------------------
		// Set up stuff
		//-----------------------------------------
		
		$this->form_code	= $this->html->form_code	= 'module=articles&amp;section=articles';
		$this->form_code_js	= $this->html->form_code_js	= 'module=articles&section=articles';

		//-----------------------------------------
		// Get database
		//-----------------------------------------
		
		$this->database	= $this->DB->buildAndFetch( array( 'select' => '*', 'from' => 'ccs_databases', 'where' => 'database_is_articles=1' ) );
		
		if( !$this->database['database_id'] )
		{
			$this->returnJsonError( $this->lang->words['no_db_id_records'] );
		}
		
		//-----------------------------------------
		// Get all the fields for this DB
		//-----------------------------------------
		
		$this->DB->build( array( 'select' => '*', 'from' => 'ccs_database_fields', 'where' => "field_database_id=" . $this->database['database_id'], 'order' => 'field_position ASC' ) );
		$this->DB->execute();
		
		while( $r = $this->DB->fetch() )
		{
			$this->fields[ $r['field_id'] ]	= $r;
		}

		//-----------------------------------------
		// Fix language strings
		//-----------------------------------------
		
		$this->registry->ccsFunctions->fixStrings( $this->database['database_id'] );
		
		//-----------------------------------------
		// What to do?
		//-----------------------------------------
		
		switch( $this->request['do'] )
		{
			case 'sort':
			default:
				$this->_sortArticles();
			break;
			
			case 'toggle':
				$this->_toggleApproved();
			break;
		}
	}
	
	/**
	 * Toggle published/draft status
	 *
	 * @access	protected
	 * @return	void
	 */
	protected function _toggleApproved()
	{
		$id	= intval($this->request['id']);
		
		if( !$id )
		{
			$this->returnJsonError( $this->lang->words['noid_ajax_toggle'] );
		}
		
		$record	= $this->DB->buildAndFetch( array( 'select' => 'primary_id_field, record_approved', 'from' => $this->database['database_database'], 'where' => 'primary_id_field=' . $id ) );
		
		if( !$record['primary_id_field'] )
		{
			$this->returnJsonError( $this->lang->words['noid_ajax_toggle'] );
		}
		
		//-----------------------------------------
		// Already approved, change to draft
		//-----------------------------------------
		
		if( $record['record_approved'] )
		{
			$this->DB->update( $this->database['database_database'], array( 'record_approved' => 0 ), 'primary_id_field=' . $id );
			
			$this->returnHtml( $this->html->ajaxRecordDraft() );
		}
		
		//-----------------------------------------
		// Draft, approve it
		//-----------------------------------------
		
		else
		{
			$this->DB->update( $this->database['database_database'], array( 'record_approved' => 1 ), 'primary_id_field=' . $id );
			
			$this->returnHtml( $this->html->ajaxRecordApproved() );
		}
	}
	
	/**
	 * Get real column name
	 *
	 * @access	public
	 * @param	string		Friendly name
	 * @return	string		Database column
	 */
	public function getColumn( $column )
	{
		if( !$column )
		{
			return '';
		}
		
		switch( $column )
		{
			case 'id':
				return 'r.primary_id_field';
			break;
			
			case 'comments':
				return 'r.record_comments';
			break;

			case 'hits':
				return 'r.record_views';
			break;

			case 'status':
				return 'r.record_approved';
			break;

			case 'category':
				return 'c.category_name';
			break;

			case 'title':		// article_title
				foreach( $this->fields as $field )
				{
					if( $field['field_key'] == 'article_title' )
					{
						return 'r.field_' . $field['field_id'];
					}
				}
			break;
			
			case 'date':		// article_date
				foreach( $this->fields as $field )
				{
					if( $field['field_key'] == 'article_date' )
					{
						return 'r.field_' . $field['field_id'];
					}
				}
			break;
		}

		return '';
	}
	
	/**
	 * Get databases
	 *
	 * @access	protected
	 * @return	void
	 */
	protected function _sortArticles()
	{
		//-----------------------------------------
		// Get possible field types
		//-----------------------------------------
		
		require_once( IPSLib::getAppDir( 'ccs' ) . '/sources/databases/fields.php' );
		$fieldsClass	= new ccs_database_fields( $this->registry );
		$fieldsClass->getHandlers();
		
		//-----------------------------------------
		// Sorting and limiting
		//-----------------------------------------
		
		$perPage	= intval($this->request['per_page']) ? intval($this->request['per_page']) : $this->database['database_field_perpage'];
		$perPage	= intval($perPage) > 0 ? $perPage : 50;
		$start		= 0;
		
		$_col		= $this->getColumn( $this->request['sortBy'] );
		$_useCol	= $_col ? $_col : 'r.' . $this->database['database_field_sort'];
		$_numeric	= false;

		foreach( $this->fields as $_field )
		{
			if( $_useCol == 'field_' . $_field['field_id'] )
			{
				$_numeric	= $_field['field_is_numeric'];
			}
		}

		$_dir		= ( $this->request['order'] && in_array( $this->request['order'], array( 'asc', 'desc' ) ) ) ? $this->request['order'] : $this->database['database_field_direction'];
		
		$this->request['sort_col']		= $_useCol;
		$this->request['sort_order']	= $_dir;
		$this->request['per_page']		= $perPage;

		//-----------------------------------------
		// Get total
		//-----------------------------------------
		
		$count		= $this->DB->buildAndFetch( array( 'select' => 'COUNT(*) as total', 'from' => $this->database['database_database'] ) );
		
		//-----------------------------------------
		// Pagination
		//-----------------------------------------
		
		$_qs		= ( $_useCol != 'r.' . $this->database['database_field_sort'] ? '&amp;sort_col=' . str_replace( array( 'r.', 'c.' ), '', $_useCol ) : '' ) . '&amp;sort_order=' . $_dir . '&amp;per_page=' . $perPage;
		
		$pages = $this->registry->output->generatePagination( array( 
																	'totalItems'		=> $count['total'],
																	'itemsPerPage'		=> $perPage,
																	'currentStartValue'	=> $start,
																	'baseUrl'			=> $this->settings['base_url'] . $this->form_code . $_qs,
											 				)	);

		//-----------------------------------------
		// Categories for filtering
		//-----------------------------------------
		
		require_once( IPSLib::getAppDir('ccs') . '/sources/databases/categories.php' );
		$categories	= new ccs_categories( $this->registry );
		$categories->hide	= false;
		$categories->init( $this->database );

		//-----------------------------------------
		// Get records
		//-----------------------------------------
		
		$records	= array();
		
		$this->DB->build( array(
								'select'	=> 'r.*',
								'from'		=> array( $this->database['database_database'] => 'r' ), 
								'order'		=> ( $_numeric ? $_useCol . '+0' : $_useCol ) . ' ' . $_dir, 
								'limit'		=> array( $start, $perPage ),
								'add_join'	=> array(
													array(
														'from'	=> array( 'ccs_database_categories' => 'c' ),
														'where'	=> 'c.category_id=r.category_id',
														'type'	=> 'left',
														)
													)
						)		);
		$this->DB->execute();
		
		while( $r = $this->DB->fetch() )
		{
			$r['category_name']	= $categories->categories[ $r['category_id'] ]['category_name'];
			$records[]			= $r;
		}

		foreach( $records as $row )
		{
			$html	.= $this->html->articleRow( $row, $this->database, $this->fields, $fieldsClass );
		}

		$this->returnJsonArray( array( 'html' => $html, 'pages' => $pages ) );
	}
}