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

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

class DeleteAccount extends Controller {

	protected function _doGetFormSettings( Context $context, array &$storage ) {
		if ( $this->getUser()->isAdministrator() ) {
			return array(
				'message' => array(
					'#type'   => 'item',
					'#markup' => '<div class="' . DRTS_BS_PREFIX . 'alert ' . DRTS_BS_PREFIX . 'alert-warning">'
						. __( 'An administrator account may not be deleted.', 'directories-pro' ) . '</div>',
				),
			);
		}

		$this->_ajaxOnSuccessRedirect = true;
		$this->_submitButtons[]       = array(
			'#btn_label' => __( 'Delete account', 'directories-pro' ),
			'#btn_color' => 'danger',
		);

		return array(
			'message'  => array(
				'#type'   => 'item',
				'#markup' => '<div class="' . DRTS_BS_PREFIX . 'alert ' . DRTS_BS_PREFIX . 'alert-warning">'
					. __( 'Are you sure you want to permanently delete your account?', 'directories-pro' ) . '</div>',
			),
			'password' => array(
				'#type'        => 'password',
				'#title'       => __( 'Current password', 'directories-pro' ),
				'#description' => __( 'Please enter your current password to confirm.', 'directories-pro' ),
				'#horizontal'  => true,
				'#required'    => true,
			),
		);
	}

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

		if ( ! $this->getPlatform()->deleteAccount( $identity ) ) {
			$form->setError( __( 'Your account could not be deleted.', 'directories-pro' ) );
			return;
		}

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

		$context->setSuccess( '/' . $this->getComponent( 'Dashboard' )->getSlug( 'dashboard' ) );
	}
}
