<?php
namespace SabaiApps\Directories\Component\Display\Controller\Admin;

use SabaiApps\Directories\Context;
use SabaiApps\Directories\Component\Form;

class AddElement extends Form\Controller {

	protected function _doGetFormSettings( Context $context, array &$formStorage ) {
		if ( ! $element_name = $context->getRequest()->asStr( 'element' ) ) {
			$context->setError();
			return;
		}

		// Set options
		$this->_submitButtons         = array(
			array(
				'#btn_label' => __( 'Add Element', 'directories-pro' ),
				'#btn_color' => 'success',
				'#btn_size'  => 'lg',
				'#weight'    => 5,
			),
		);
		$this->_ajaxCancelType        = 'hide';
		$this->_ajaxOnCancel          = 'function(target){ target.empty().closest(".drts-display-element").removeClass("drts-display-element-editing-inline"); }';
		$this->_ajaxOnSuccess         = 'function(result, target, trigger) {
            $(DRTS).trigger("display_element_created.sabai", {trigger: trigger, result: result, target: target});
        }';
		$this->_ajaxOnSuccessRedirect = $this->_ajaxOnErrorRedirect = false;
		$this->_ajaxModalHideOnSend   = true;

		return $this->Display_ElementForm(
			$context->display,
			$element_name,
			$context->getRoute(),
			$this->_getSubimttedValues( $context, $formStorage ),
			isset( $context->alt_display ) ? $context->alt_display : null
		);
	}

	public function submitForm( Form\Form $form, Context $context ) {
		$display = $context->alt_display ?: $context->display;
		$result  = $this->Display_AdminElement_create(
			$display,
			$form->values['element'],
			(int) @$form->values['parent_id'],
			$form->values
		);
		if ( $context->alt_display ) {
			$result['display_id']     = $context->display->id;
			$result['alt_display_id'] = $context->alt_display->id;
		}
		$context->setSuccess( $this->_getSuccessUrl( $context ), $this->Filter( 'display_admin_add_element_results', $result, array( $display ) ) );

		// Clear display and elements cache
		$this->Display_Display_clearCache( $display );
		$this->getPlatform()->deleteCache( 'display_elements_' . $display->bundle_name );
	}

	protected function _getSuccessUrl( Context $context ) {
		return dirname( $context->getRoute() );
	}
}
