<?php
class Plugg_User_Main_Identity_Delete extends Sabai_Application_Controller
{
    protected function _doExecute(Sabai_Application_Context $context)
    {
        $identity = $this->_parent->getRequestedUserIdentity($context);
        $manager = $context->plugin->getManagerPlugin();

        if ($manager instanceof Plugg_User_Manager_API) {
            $manager->userDelete($context, $identity);
            return;
        }

        // Check permissions
        if ($identity->getId() != $context->user->getId()) {
            if (!$context->user->hasPermission('user profile delete any')) {
                $context->response->setError($context->plugin->_('You are not allowed to delete other user profile.'));
                return;
            }
        } else {
            if (!$context->user->hasPermission('user profile delete own') ||
                $context->user->isSuperUser() // Not allowed to delete oneself if super user
            ) {
                $context->response->setError($context->plugin->_('You are not allowed to delete your own profile.'));
                return;
            }
        }

        // Validate form and submit
        $form = $this->_getForm($context, $identity);
        if ($form->validate()) {
            if ($manager->userDeleteSubmit($identity)) {
                $context->response->setSuccess($context->plugin->_('User data removed successfully'));
                $this->pluginManager->dispatch('UserIdentityDeleteSuccess', array($identity));
                return;
            }
        }

        // view
        $context->response
            ->setPageInfo($context->plugin->_('Delete account'))
            ->setVars(array(
                'form' => $form,
            ));
    }

    function _getForm(Sabai_Application_Context $context, $identity)
    {
        require_once 'Sabai/HTMLQuickForm.php';
        $form = new Sabai_HTMLQuickForm();
        $form->addElement('static', '', $context->plugin->_('Name'), h($identity->getUsername()));
        $form->addSubmitButtons($context->plugin->_('Delete account'));
        $form->useToken(get_class($this));
        return $form;
    }
}