<?php
class MetaTaggedBehavior extends ModelBehavior {


# ~ Extract metatags after find- - - - - - - - - - - - - - - - - - - - - - - - #
	public function afterFind(Model $Model, $results, $primary = false) {

		foreach($results as $index => $result) {
			# Meta tags
			$results[$index]['Seo']['metatag'] = [];
			if($Model->schema('seo_metatags') && isset($result[$Model->alias]['seo_metatags'])) {
				$results[$index]['Seo']['metatag'] = ClassRegistry::init('Seo.MetaTag')->getForForm($result[$Model->alias]['seo_metatags']);
			}
			if($Model->schema('seo_generated_metatags') && isset($result[$Model->alias]['seo_generated_metatags'])) {
				$results[$index][$Model->alias]['seo_generated_metatags'] = @unserialize($results[$index][$Model->alias]['seo_generated_metatags']);
			}
		}
		return $results;
	}


# ~ Parse metatags before save - - - - - - - - - - - - - - - - - - - - - - - - #
	public function beforeSave(Model $Model, $options = []) {
		# Meta tags
		if($Model->isModule || (isset($Model->data['Page']) && isset($Model->data['Page']['type']) && in_array($Model->data['Page']['type'], [ 'Module', 'Page' ]))) {
			if(!empty($Model->data[$Model->alias]['custom_meta'])) {
				$Model->data[$Model->alias]['meta'] = '';
			} elseif (!empty($Model->data[$Model->alias]['generated_meta'])) {
				$Model->data[$Model->alias]['meta'] = $Model->data[$Model->alias]['generation'];
			} else {
				$Model->data[$Model->alias]['meta'] = null;
			}
			unset ($Model->data[$Model->alias]['custom_meta']);
			unset ($Model->data[$Model->alias]['generated_meta']);


			if(isset($Model->data['Seo']['metatag'])) {
				$Model->data[$Model->alias]['seo_metatags'] = ClassRegistry::init('Seo.MetaTag')->packTags($Model->data['Seo']['metatag']);
			} else {
				$Model->data[$Model->alias]['seo_metatags'] = serialize([]);
			}
		}
		return true;
	}

}
