<?php

class RelationshipHelper extends Helper {

	/** @var array The list of default options for the helper. */
	private $defaults = [

		// Which HTML templates to use to show the related model
		'template' => [

			// The base for selected and add templates, defaults to "{$RelationshipName}RelationshipTemplate"
			'base'     => null,

			// Empty selection, defaults to "{$template['base']}-Empty"
			'empty'    => null,

			// The selected item, defaults to "{$template['base']}-Selected"
			'selected' => null,

			// Item in the add dialog, defaults to "{$template['base']}-Add"
			'add'      => null
		],

		// Selectors for the DOM elements
		'dom'      => [

			// Remove previously selected item
			'remove' => 'data-relationship-action=["remove"]',

			// Remove previously selected item
			'select' => 'data-relationship-action=["select"]',
		]
	];

	/**
	 * @param AppModel $master  The master model to use.
	 * @param int      $id      The id of the module to get the definition for.
	 * @param string   $name    The name of the relationship to show.
	 * @param array    $options Additional options to use, @see RelationshipHelper->defaults.
	 *
	 * @return string The element for the form.
	 */
	public function form($master, $id, $name, $options = []) {

		// Load options
		$options = $this->getOptions($name, $options);

		// Get the data
		$records = $master->getRelated($name, $id);

		// Load filter options
		$options['filter'] = [];
		$relationshipOptions = $master->getRelationship($name)->getOptions();
		if (key_exists('filter', $relationshipOptions)) {
			$options['filter'] = (array) $relationshipOptions['filter'];
		}

		return $this->_View->element('ModuleRelationships.relation', [
			'module'       => $master->name,
			'relationship' => $name,
			'records'      => $records,
			'options'      => $options
		]);
	}

	private function getOptions($name, $options = []) {
		$options = array_replace_recursive($this->defaults, $options);

		// Prepare variables
		$relationship = str_replace(' ', '', Inflector::humanize($name));

		// Default: templates
		if (empty($options['template']['base'])) {
			$options['template']['base'] = "{$relationship}RelationshipTemplate";
		}
		foreach ([ 'empty', 'selected', 'add' ] as $template) {
			if (empty($options['template'][$template])) {
				$options['template'][$template] = $options['template']['base'] . '-' . ucfirst($template);
			}
		}

		return $options;
	}

}