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

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

class AssignPost 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',
			'#attributes' => array( 'data-modal-title' => '' ), // prevents modal title from changing on submit error
		);

		return array(
			'#enable_storage' => true,
			'#action'         => $this->_getPanelUrl( $context->entity, $current_display ),
			'#entity'         => $context->entity,
			'post_author'     => array( // we can't use "author" here in WP -> 404 error
				'#type'          => 'user',
				'#default_value' => $context->entity->getAuthorId(),
				'#required'      => (bool) $context->entity->getAuthorId(),
			),
		);
	}

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

	public function submitForm( Form\Form $form, Context $context ) {
		$this->Entity_Save( $context->entity, array( 'author' => $form->values['post_author'] ) );
		$context->setSuccess( $this->_getSuccessUrl( $context, ! empty( $form->storage['from_dashboard'] ), $form->storage['display'] ) )
			->addFlash( __( 'Author has been updated successfully.', 'directories-pro' ), 'success' );
	}

	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 ) );
	}
}
