<?php
class ModuleField extends AppModel {

	var $belongsTo = array(
		'Module'
	);

	var $hasMany = array(
		'ModuleFieldRules' => array(
			'className' => 'ModuleFieldRule')
	);

# ~ Get module fields and validation errors- - - - - - - - - - - - - - - - - - #
	public function getModuleFields($moduleId) {
		$fields = $this->find('all', array(
			'contain' => array('ModuleFieldRules'),
			'conditions' => array(
				$this->alias . '.module_id' => $moduleId
			)
		));

		# Format field and validation rules
		foreach($fields as $index => $field) {
			foreach($field['ModuleFieldRules'] as $ruleId => $rule) {
				$additionalData = $fields[$index]['ModuleFieldRules'][$ruleId]['additional_data'];

				$additionalData = @unserialize($additionalData);
				if(!is_array($additionalData)) continue;

				$fields[$index]['ModuleFieldRules'][$ruleId]['additional_data'] = $additionalData;
				$fields[$index]['ModuleFieldRules'][$ruleId] = array_merge($fields[$index]['ModuleFieldRules'][$ruleId], $additionalData);
			}
		}

		return $fields;
	}


# ~ Get translatable strings for this table- - - - - - - - - - - - - - - - - - #
	public function getTranslatableStrings() {
		$helpTexts = $this->find('list', array(
			'recursive' => -1,
			'fields' => array('id', 'field_help_text')
		));
		return array_filter($helpTexts);
	}


# ~ Generate validation array for dynamic model- - - - - - - - - - - - - - - - #
	public function generateValidation($module) {
		$validation = array();

		# Cache validation rules (Move to cache?)
		$validationRules = ClassRegistry::init('ValidationRule')->find('list', array(
			'fields' => array('id', 'rule')
		));

		# Build array
		foreach($module['ModuleFields'] as $field) {

			# Handle the required fields
			if(!empty($field['required'])) {
				$validation[$field['field_name']]['notBlank'] = array(
					'rule' => 'notBlank',
					'message' => __('Please fill out this field')
				);
			}

			# Set the rules
			foreach($field['ModuleFieldRules'] as $validationRule) {
				$additionalData = @unserialize($validationRule['additional_data']);

				$rule = $validationRules[$validationRule['rule_id']];

				if(is_array($additionalData) && !empty($additionalData)) {
					$rule = array($rule);
					foreach($additionalData as $additionalField => $additionalValue) {
						$rule[] = $additionalValue;
					}
				}

				$validation[$field['field_name']][$validationRules[$validationRule['rule_id']]] = array(
					'rule' => $rule,
					'message' => !empty($validationRule['validation_message']) ? $validationRule['validation_message'] : __('The supplied value is not valid')
				);

				if(!empty($field['required'])) {
					$validation[$field['field_name']][$validationRules[$validationRule['rule_id']]]['required'] = $field['required'];
				}
			}
		}

		return $validation;
	}

}
