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

use SabaiApps\Directories\Component\Form;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Context;

class EditPost extends Form\Controller {

	protected function _doGetFormSettings( Context $context, array &$formStorage ) {
		if ( ! isset( $formStorage['from_dashboard'] ) ) {
			$formStorage['from_dashboard'] = $context->getRequest()->asBool( 'from_dashboard' );
		}
		$current_display = $context->getRequest()->asStr( 'display' );
		if ( ! isset( $formStorage['display'] ) ) {
			$formStorage['display'] = $current_display;
		}
		$this->_cancelUrl               = $this->_getSuccessUrl( $context, ! empty( $formStorage['from_dashboard'] ) );
		$this->_submitButtons['submit'] = array(
			'#btn_label'  => __( 'Save Changes', 'directories-pro' ),
			'#btn_color'  => 'primary',
			'#btn_size'   => 'lg',
			'#attributes' => array( 'data-modal-title' => '' ), // prevents modal title from changing on submit error
		);
		if ( $formStorage['from_dashboard'] ) {
			$this->_ajaxOnSuccessRedirect = false;
			$this->_ajaxOnSuccess         = 'function (result, target, trigger) {
    if (target.attr("id") === "drts-modal") {
        target.find(".drts-modal-close").click();
    } else {
        target.hide();
    }
    var oldRow = $("tr.drts-display--dashboard-row[data-entity-id=\'' . $context->entity->getId() . '\']"),
        newRow = $(result.post).attr("id", oldRow.attr("id")).find("td > .drts-display-element-header").remove().end();
    oldRow.replaceWith(newRow);
    if ($.effects && $.effects.effect.highlight) {
        newRow.find("> td").effect("highlight", {}, 1000);
    }
}';
		}
		$context->addTemplate( 'dashboard_edit_post_form' );
		$displays = array( 'default' => array( 'label' => __( 'General', 'directories-pro' ) ) );
		foreach ( $this->getModel( 'Display', 'Display' )->bundleName_is( $context->entity->getBundleName() )->type_is( 'form' )->fetch() as $_display ) {
			if ( $_display->name === 'default' ) {
				continue;
			}

			$displays[ $_display->name ]['label'] = $_display->data['label'];
		}
		if ( ! isset( $displays[ $current_display ] ) ) {
			$current_display = 'default';
		}
		if ( count( $displays ) > 1 ) {
			foreach ( array_keys( $displays ) as $display_name ) {
				if ( $display_name === $current_display ) {
					continue;
				}

				$displays[ $display_name ]['url'] = $this->_getPanelUrl( $context->entity, $display_name, array( 'from_dashboard' => 1 ) );
			}
			$context->displays = $displays;
		}

		return array(
			'#enable_storage' => true,
			'#action'         => $this->_getPanelUrl( $context->entity, $current_display ),
		) + $this->Entity_Form(
			$context->entity,
			array(
				'values'             => $context->getRequest()->getParams(),
				'pre_render_display' => true,
				'wrap'               => 'drts',
				'display'            => $current_display,
			)
		);
	}

	protected function _getPanelUrl( IEntity $entity, $displayName, array $params = array() ) {
		return $this->Dashboard_Panels_postsPanelUrl(
			$entity,
			'/posts/' . $entity->getId(),
			$params + array( 'display' => $displayName ),
			true
		);
	}

	public function submitForm( Form\Form $form, Context $context ) {
		$was_published = $context->entity->isPublished();
		$entity        = $this->_saveEntity( $context->entity, $form );
		$attr          = array(
			'post' => $this->_application->Display_Render(
				$entity,
				'dashboard_row',
				$entity,
				array(
					'tag'          => 'tr',
					'element_tag'  => 'td',
					'render_empty' => true,
					'pre_render'   => true,
				)
			),
		);

		$context->setSuccess( $this->_getSuccessUrl( $context, ! empty( $form->storage['from_dashboard'] ), $form->storage['display'] ), $attr )
			->addFlash( __( 'Your item has been updated successfully.', 'directories-pro' ), 'success', 60000 );

		if ( $was_published
			&& ! $entity->isPublished()
		) {
			$info_msg = $this->Filter(
				'dashboard_edit_post_success_msg2',
				$this->H( __( 'We will review your submission and publish it on this site when it is approved.', 'directories-pro' ) ),
				array( $entity )
			);
			$context->addFlash( $info_msg, 'info', 60000 );
		}

		$this->Action( 'dashboard_edit_post_success', array( $entity ) );

		return $entity;
	}

	protected function _saveEntity( IEntity $entity, Form\Form $form, array $extraArgs = array() ) {
		$values = $form->values['drts'];

		// Make sure the parent entity can not be changed
		unset( $values['entity_parent'], $values['parent'] );

		$extra_args = array(
			'entity_field_max_num_items' => $form->settings['#entity_field_max_num_items'],
			'dashboard_edit_post'        => true,
		);

		return $this->Entity_Save( $entity, $values, $extra_args );
	}

	protected function _getSuccessUrl( Context $context, $fromDashboard = false, $display = null ) {
		if ( empty( $fromDashboard ) ) {
			if ( $url = $this->Filter( 'dashboard_edit_post_success_url', null, array( $context->entity ) ) ) {
				return $url;
			}

			return $this->Entity_PermalinkUrl( $context->entity );
		}
		if ( empty( $display ) ) {
			return $this->Dashboard_Panels_postsPanelUrl( $context->entity );
		}

		return $this->_getPanelUrl( $context->entity, $display, array( 'from_dashboard' => 1 ) );
	}
}
