<?php
namespace SabaiApps\Directories\Component\FrontendSubmit\Controller;

use SabaiApps\Directories\Context;
use SabaiApps\Directories\Component\Form;
use SabaiApps\Directories\Component\Entity\Model\Bundle;

class AddChildEntity extends AbstractAddEntity {

	protected function _getSteps( Context $context, array &$formStorage ) {
		$context->setErrorUrl( $this->Entity_PermalinkUrl( $context->entity ) );

		if ( $this->getUser()->isAnonymous() ) {
			if ( ! $this->Entity_IsRoutable( $context->child_bundle, 'add', $context->entity )
				|| $this->callHelper( 'FrontendSubmit_Submission_isGuestRedirectRequired', array( $context->child_bundle->type, $context, &$formStorage ) )
			) {
				return $this->_redirectGuest( $context, $formStorage, $context->child_bundle );
			}
		} elseif ( ! $this->Entity_IsRoutable( $context->child_bundle, 'add', $context->entity ) ) {
				return array();
		}

		return parent::_getSteps( $context, $formStorage );
	}

	public function _getFormForStepAdd( Context $context, array &$formStorage ) {
		$this->_cancelUrl = $this->Entity_PermalinkUrl( $context->entity );
		$form             = parent::_getFormForStepAdd( $context, $formStorage );
		$form['#action']  = $this->_getAddEntityUrl( $context );

		return $form;
	}

	protected function _getAddEntityUrl( Context $context, array $params = array() ) {
		return $this->Url( $context->child_bundle->getPath( false ) . '/add', array( 'entity_id' => $context->entity->getId() ) + $params );
	}

	protected function _getBundle( Context $context, array $formStorage ) {
		return $context->child_bundle;
	}

	protected function _getEntityValues( Context $context, Form\Form $form, Bundle $bundle ) {
		$values = parent::_getEntityValues( $context, $form, $bundle );
		unset( $values['slug'] ); // this comes from the URL path
		if ( empty( $context->child_bundle->info['parent_field'] ) ) {
			$values['parent'] = $context->entity->getId();
		} else {
			$values['entity_parent'] = array(
				'parent_entity_id'   => $context->entity->getId(),
				'parent_entity_type' => $context->entity->getType(),
			);
		}

		return $values;
	}

	protected function _getParentEntity( Context $context, array $formStorage ) {
		return $context->entity;
	}
}
