<?php
class SlugLog extends SeoAppModel {

	var $useTable = 'slug_logs';


	public function saveNew($data) {
		return $this->save($data);
	}


# ~ Get latest page slug - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function getPageSlug($slug, $page) {
		# Initial conditions
		$conditions = array(
			'type' => 'Page',
			'from_slug' => $slug
		);

		# TODO: Check if this should be merged with condition below
		if(isset($page['Page'])) {
			$conditions['parent_page_id'] = $page['Page']['id'];
		}

		# Compare by parent id, if provided
		if(isset($page['parent_id'])) {
			$conditions['parent_page_id'] = $page['parent_id'];
		}

		# Find first one
		$log = $this->find('first', compact('conditions'));

		# If empty, give up
		if(empty($log)) return null;

		# Iterate through logs and find latest
		$lastLog = $log;
		$parentLog = $log;
		do {
			$lastLog = $parentLog;
			$parentLog = $this->find('first', array(
				'conditions' => array(
					'type' => 'Page',
					'from_slug' => $parentLog['SlugLog']['to_slug'],
					"to_slug <> ''",
					"to_slug IS NOT NULL",
					'created >' => $parentLog['SlugLog']['created']
				),
				'order' => array('created' => 'asc')
			));
		} while (!empty($parentLog));

		# Return latest log
		return $lastLog['SlugLog'];
	}


# ~ Get latest module slug - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function getModuleSlug($slug, $Model, $pageId = null) {
		# Initial conditions
		$conditions = array(
			'type' => 'Module',
			'model' => $Model->name,
			'from_slug' => $slug
		);

		# If provided pate id, use it for conditions
		if(!empty($pageId)) {
			$conditions['page_id'] = $pageId;
		}

		# Default order
		$order = 'created DESC';

		# Get first log
		$log = $this->find('first', compact('conditions', 'order'));

		# If empty give up
		if(empty($log)) return null;


		# Iterate through logs and find latest
		$lastLog = $log;
		$parentLog = $log;
		do {
			$lastLog = $parentLog;
			$parentLog = $this->find('first', array(
				'conditions' => array(
					'type' => 'Module',
					'model' => $Model->name,
					'from_slug' => $parentLog['SlugLog']['to_slug'],
					"to_slug <> ''",
					"to_slug IS NOT NULL",
					'created >' => $parentLog['SlugLog']['created']
				),
				'order' => array('created' => 'asc')
			));
		} while (!empty($parentLog));

		# Return latest log
		return $lastLog['SlugLog'];
	}
}
