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

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

class ChangePassword extends Controller {

	protected function _doGetFormSettings( Context $context, array &$storage ) {
		$this->_submitButtons[]       = array(
			'#btn_label' => __( 'Change password', 'directories-pro' ),
			'#btn_color' => 'primary',
		);
		$this->_ajaxSubmit            = true;
		$this->_ajaxOnSuccessRedirect = $this->_ajaxOnErrorRedirect = false;
		$this->_ajaxOnSuccess         = 'function (result, target, trigger) {
    if (result.messages) DRTS.flash(result.messages, "success");
}';
		$this->_ajaxOnSuccessRedirect = $this->_ajaxOnErrorRedirect = false;

		return array(
			'password'             => array(
				'#type'       => 'password',
				'#title'      => __( 'Current password', 'directories-pro' ),
				'#horizontal' => true,
				'#required'   => true,
			),
			'new_password'         => array(
				'#type'       => 'password',
				'#title'      => __( 'New password', 'directories-pro' ),
				'#horizontal' => true,
				'#required'   => true,
			),
			'new_password_confirm' => array(
				'#type'       => 'password',
				'#title'      => __( 'Confirm new password', 'directories-pro' ),
				'#horizontal' => true,
				'#required'   => true,
			),
		);
	}

	public function submitForm( Form $form, Context $context ) {
		if ( $form->values['new_password'] !== $form->values['new_password_confirm'] ) {
			$form->setError( __( 'New passwords do not match.', 'directories-pro' ) );
			return;
		}

		$identity = $this->getUser()->getIdentity();
		if ( ! $this->getPlatform()->isCurrentPassword( $form->values['password'], $identity ) ) {
			$form->setError( __( 'Your current password is incorrect.', 'directories-pro' ) );
			return;
		}

		$this->getPlatform()->changePassword( $form->values['new_password'], $identity );

		$this->Action( 'dashboard_change_password_success', array( $identity ) );

		$context->setSuccess( false )->addFlash( __( 'Your password changed successfully.', 'directories-pro' ) );
	}
}
