<?php

/**
 * @am_plugin_api 6.0
 */
class Am_Plugin_DropMe extends Am_Plugin
{
    const PLUGIN_STATUS = self::STATUS_BETA;
    const PLUGIN_COMM = self::COMM_FREE;
    const PLUGIN_REVISION = '6.3.43';
    protected $_configPrefix = 'misc.';

    static function getEtXml()
    {
        return <<<CUT
<table_data name="email_template">
    <row type="email_template">
        <field name="name">misc.drop-me.notify_admin</field>
        <field name="email_template_layout_id">2</field>
        <field name="lang">en</field>
        <field name="format">text</field>
        <field name="subject">%site_title%: %user.login% removed his account</field>
        <field name="txt">
The following user removed his account on your site.

Login: %user.login%
Name: %user.name_f% %user.name_l%
Email: %user.email%
        </field>
    </row>
</table_data>
CUT;
    }

    function onInitBlocks(Am_Event $e)
    {
        $e->getBlocks()->add('member/main/right', new Am_Block_Base(___('Your Account Removal'), $this->getId(), $this, [$this, 'renderBlock']), Am_Blocks::BOTTOM);
    }

    function onSetupEmailTemplateTypes(Am_Event $e) {

        $e->addReturn([
            'id' => 'misc.drop-me.notify_admin',
            'title' => 'Notify Admin about User Removal',
            'mailPeriodic' => Am_Mail::ADMIN_REQUESTED,
            'isAdmin' => true,
            'vars' => ['user'],
        ], 'misc.drop-me.notify_admin');
    }

    function getTitle()
    {
        return ___('Drop Me');
    }

    function _initSetupForm(Am_Form_Setup $form)
    {
        $form->addText('redirect_url', ['class' => 'am-el-wide', 'placeholder' => $this->getDi()->url('',null,false,2)])
            ->setLabel(___("Redirect URL\n" .
                'aMember will redirect user to this url after account removal, ' .
                'User will be redirected to aMember root url in case of this ' .
                'option is empty'));
        $form->addHtmleditor('last_msg', null, ['showInPopup' => true])
            ->setLabel(___("Message\n" .
                'It is last message that will be shown to user before account ' .
                'removal, you can place some special offer here.'))
            ->setValue(___('It is last message that will be shown to user before account removal, you can place some special offer here.'));
        $form->addElement('email_checkbox', 'notify_admin')
            ->setLabel(___("Notify Admin\n" .
                "once user removed himself"));
    }

    function checkPassword($pass)
    {
        $user = $this->getDi()->auth->getUser();
        if (!$user) return false;
        return $user->checkPassword($pass);
    }

    function directAction(Am_Mvc_Request $request, Am_Mvc_Response $response, array $invokeArgs)
    {
        $this->getDi()->auth->requireLogin();

        $form = new Am_Form();

        $form->addPassword('pass')
            ->setLabel(___('Your Password'))
            ->addRule('required')
            ->addRule('callback', ___('Wrong password'), [$this, 'checkPassword']);

        $form->addSaveButton(___('Remove My Account'));

        $form->setDataSources([$request]);

        if ($form->isSubmitted() && $form->validate()) {
            $user = $this->getDi()->user;
            $this->getDi()->auth->logout();
            foreach ($this->getDi()->invoiceTable->findByUserId($user->pk()) as $invoice){
                if ($invoice->status == Invoice::RECURRING_ACTIVE){
                    $ps = $invoice->getPaysystem();
                    if (!$ps)
                        continue;
                    $result = new Am_Paysystem_Result();
                    try {
                        $ps->cancelAction($invoice, 'cancel', $result);
                        if ($result->isSuccess())
                            continue;
                    } catch (Am_Exception_NotImplemented $e) {
                        // nop
                    } catch (Exception $e) {
                        $this->getDi()->logger->error("Error in drop-me plugin", ["exception" => $e]);
                        // catch all errors
                    }

                }
            }
            $user->delete();

            if ($this->getConfig('notify_admin')) {
                $et = Am_Mail_Template::load('misc.drop-me.notify_admin');
                $et->setUser($user);
                $et->sendAdmin();
            }

            $url = $this->getConfig('redirect_url', $this->getDi()->url('',null,false,2));
            return $response->redirectLocation($url);
        } else {
            $view = $this->getDi()->view;
            $view->title = ___('Your Account Removal');
            $view->content = $this->getConfig('last_msg', '') . $form;
            $view->display('layout.phtml');
        }
    }

    function renderBlock(Am_View $view)
    {
        $url = $this->getDi()->url('misc/drop-me');

        $label1 = ___('You can remove your account in our system.');
        $label2 = ___('Please note: it is impossible to restore
your current account after deleting but
you still can signup again as new user.');
        $label3 = ___('Yes, I want to remove my account with all associated info on this site');
        return <<<CUT
   <p>$label1</p>
   <p><strong>$label2</strong></p>
   <p><a href="$url">$label3</a></p>
CUT;
    }
}