<?php
class Log extends AppModel {

	var $name = 'Log';

	public $useTable = "log";

	public $hasMany = array(
		'LogDetails' => array(
			'className' => 'LogDetails'
		)
	);

	public $belongsTo = array(
		'Administrator');

	public $paginate = array(
		'order' => array(
			'Log.id' => 'DESC'
		)
	);

	public $order = array(
		'Log.id' => 'DESC'
	);

/**
 * Get log for one module item. Used in view.
 *
 * @param	modelClass
 *		Class of model.
 * @param	foreign_key
 *		Id of record in model table.
 * @return
 *		Array of all logs attached to model.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	public function getLogForItem($modelClass, $foreign_key) {
		return $this->find('all', array(
			'conditions' => array(
				'model' => $modelClass,
				'foreign_key' => $foreign_key),
		));
	}

/**
 * Filter log.
 *
 * @param	data
 *		Array with filter params.
 * @param	page
 *		Page to render, pagination.
 * @return
 *		Array of matching log.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	public function searchLog($data, $page) {

		# Conditions for query.
		$conditions = array();

		# Put filter params in conditions array
		if(!empty($data['Log']['type']))
			$conditions['Log.type'] = $data['Log']['type'];

		if(!empty($data['Log']['administrator']))
			$conditions['Log.administrator_id'] = $data['Log']['administrator'];

		if(!empty($data['Log']['model']))
			$conditions['Log.model'] = $data['Log']['model'];

		# Find all logs that match provided conditions
		$logs = $this->find('all', array(
			'contain' => array(
				'LogDetails', 'Administrator'),
			'conditions' => $conditions
		));

		# If there is keyword provided, filter remaining logs
		if(!empty($data['Log']['keyword'])) {

			# Get keyword
			$keyword = $data['Log']['keyword'];

			# Temporally array to store matching logs
			$filtered = array();

			# Check each log
			foreach($logs as $log) {
				# If username, or model name matches
				if(stristr($log['Administrator']['full_name'], $keyword) || stristr($log['Log']['model'], $keyword)) {
					$filtered[] = $log;
					continue;
				}

				# Check filter details
				if(!empty($log['LogDetails'])) {
					foreach($log['LogDetails'] as $details) {

						# Check if from, to and field name field matches
						if(stristr($details['from'], $keyword) || stristr($details['to'], $keyword) || stristr($details['field'], $keyword)) {
							$filtered[] = $log;
							continue;
						}
					}
				}

				# Check if display field of model matches
				$modelClass = $log['Log']['model'];
				$instance = ClassRegistry::init($modelClass);
				$dfValue = $instance->find('first', array(
					'conditions' => array(
						$instance->alias.'.id' => $log['Log']['foreign_key']),
					'fields' => array(
						$instance->displayField)));

				$dfValue = $dfValue[$instance->alias][$instance->displayField];

				if(stristr($dfValue, $keyword)) {
					$filtered[] = $log;
					continue;
				}
			}
			# Put filtered in logs
			$logs = $filtered;
		}

		# Get pages count and number of logs, for pagination
		$pagesCount = ceil(sizeof($logs)/10);
		$logSize = sizeof($logs);

		# Cut array, to get logs for one page
		$logs = array_slice($logs, ($page-1)*10, 10);

		# Set pagination values and return logs
		$logs['paging']['items'] = $logSize;
		$logs['paging']['pageCount'] = $pagesCount;

		return $logs;
	}


	public function beforeSave($options = array()) {

		# Mark module or not
		if(!empty($this->data['Log']['model'])) {
			$this->data['Log']['is_module'] = (int)(bool)ClassRegistry::init('Module')->hasAny(array(
				'Module.name' => $this->data['Log']['model']
			));
		}

		return true;
	}

/**
 * Get the latest changes, for dashboard.
 *
 * @return
 *		The list of latest events.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	public function getLatest() {
		return $this->find('all', array(
			'contain' =>  array(
				'Administrator'),
			'conditions' => array(
				'administrator_id IS NOT NULL',
				'is_module' => true),
			'limit' => Configure::read('Backend.dashboard_history')
		));
	}
}
