<?php
class LastModBehavior extends ModelBehavior {


# ~ Handle last mod after save - - - - - - - - - - - - - - - - - - - - - - - - #
	function afterSave(Model $Model, $created, $options = []) {

		# Use custom function if provided
		if(method_exists($Model, 'handleLastMod')) {
			return $Model->handleLastMod();
		}

		# Handle module
		if($Model->isModule) {
			if($Model->schema('page_id') && isset($Model->data[$Model->alias]['page_id'])) {
				return $this->updateLastMod($Model->data[$Model->alias]['page_id']);
			}

			# Get module info
			$moduleInstance = ClassRegistry::init('Module');
			$moduleInstance->recursive = -1;
			$module = $moduleInstance->find('first', $Model->moduleId);

			# Update pages attached to module
			if(!empty($module[$moduleInstance->alias]['page_id'])) {
				return $this->updateLastMod($module[$moduleInstance->alias]['page_id']);
			}
		}

		# Handle page
		if($Model->name == 'Page') {
			return $this->updateLastMod($Model->id);
		}
		return true;
	}


# ~ Update last mod date to attached pages - - - - - - - - - - - - - - - - - - #
	private function updateLastMod($pageId) {
		# Get page with all parents
		$pageInstance = ClassRegistry::init('Page');
		$pageInstance->recursive = -1;
		$pages = $pageInstance->getPath($pageId, [ 'id' ], false);

		# Extract ids
		$updateIds = Set::extract('/Page/id', $pages);

		# Update all
		$pageInstance->updateAll(
			[ 'Page.seo_last_mod' => "'" . date('Y-m-d H:i:s') . "'" ],
			[ 'Page.id' => $updateIds ]
		);

		ClassRegistry::init('Seo.SitemapGenerator')->invalidateSitemap();
		return true;
	}
}
