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

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

class EditElement extends Form\Controller {

	protected $_element;

	protected function _doGetFormSettings( Context $context, array &$formStorage ) {
		if ( ( ! $element_id = $context->getRequest()->asStr( 'element_id' ) )
			|| ( ! $this->_element = $this->getModel( 'Element', 'Display' )->fetchById( $element_id ) )
		) {
			$context->setError();
			return;
		}

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

		return $this->Display_ElementForm(
			$context->display,
			$this->_element,
			$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_update(
			$display,
			$this->_element,
			$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_edit_element_results', $result, array( $display, $this->_element ) ) );

		// Clear display cache
		$this->Display_Display_clearCache( $display );
	}

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