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

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

class EditProfile extends Controller {

	protected function _doGetFormSettings( Context $context, array &$storage ) {
		if ( ! $entity = $this->_getEntity( $context ) ) {
			return;
		}

		$this->_ajaxSubmit      = false;
		$this->_submitButtons[] = array(
			'#btn_label' => __( 'Save Changes', 'directories-pro' ),
			'#btn_color' => 'primary',
			'#btn_size'  => 'lg',
		);
		$context->addTemplate( 'entity_form' );

		return array(
			'#enable_storage' => true,
			'#header'         => array(
				'<div class="' . DRTS_BS_PREFIX . 'float-end ' . DRTS_BS_PREFIX . 'mb-3">' . $this->LinkTo(
					__( 'View public profile', 'directories-pro' ),
					$this->Entity_PermalinkUrl( $entity ),
					array(),
					array(
						'class'  => DRTS_BS_PREFIX . 'btn ' . DRTS_BS_PREFIX . 'btn-sm ' . DRTS_BS_PREFIX . 'btn-outline-secondary',
						'target' => '_blank',
					)
				) . '</div>',
			),
			'#action'         => $this->Dashboard_Panels_panelUrl( 'account', 'edit_profile', '/edit_profile', array(), true ),
		) + $this->Entity_Form(
			$entity,
			array(
				'values'             => $context->getRequest()->getParams(),
				'pre_render_display' => true,
				'wrap'               => 'drts',
			)
		);
	}

	protected function _getEntity( Context $context ) {
		return $this->Entity_Entity( 'user', $this->getUser()->id );
	}

	public function submitForm( Form $form, Context $context ) {
		$entity = $this->_saveEntity( $this->_getEntity( $context ), $form );
		$context->setSuccess( $this->Dashboard_Panels_panelUrl( 'account', 'edit_profile', '/edit_profile', array(), true ) )
			->addFlash( __( 'Your profile has been updated successfully.', 'directories-pro' ) );

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

		return $entity;
	}

	protected function _saveEntity( IEntity $entity, 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();
		$extra_args['entity_field_max_num_items'] = $form->settings['#entity_field_max_num_items'];

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