<?php

namespace Signteer\Web\Admin\Page\Setting\EmailNotification;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\DateTime\DateTimeFormatter;
use Plainwork\Ui\Html;
use Signteer\Core\Repo\SettingRepo;
use Signteer\Core\Model\SignupFieldFinder;
use Signteer\Core\Action\Signup\SendConfirmationEmailToVolunteer;
use Signteer\Core\Helper\SignupNotificationHelper;

final class EditEmailNotificationPage
{
    public $repo = SettingRepo::class;
    public $fieldFinder = SignupFieldFinder::class;
    public $sendConfirmationEmailToVolunteer = SendConfirmationEmailToVolunteer::class;
    public $signupNotificationHelper = SignupNotificationHelper::class;

    public function __invoke(Request $request)
    {
        $html = new Html();

        $messageId = $request->getQueryParam('message');

        $message = $subject = $pageTitle = '';
        if ('confirm' === $messageId) {
            list($subject, $message) = $this->sendConfirmationEmailToVolunteer->getTemplate();
            $pageTitle = '__Volunteer signup email__';
        }

        $form = $html->form();
        $ret = $html->blockList();

        $form->add($html->checkboxInput('enabled')->setValue(true)->setLabel('__Enabled__'));
        $ret->add($html->dl(null, $form->input('enabled')));

        $form->add($html->textInput('subject')->setValue($subject)->setRequired());
        $ret->add($html->dl('__Subject__', $form->input('subject')));

        $form->add($html->textareaInput('message')->setValue($message)->setRequired()->withAttr('rows', 8));
        $ret->add($html->dl('__Message__', $form->input('message')));

        $ret->add($html->dl(null, $html->button('__Save changes__')));

    // variables
        $variablesView = $html->table();
        $variablesView->withHeadCell('head', 'var')->setContent('__Available placeholders__');
        $variables = $this->signupNotificationHelper->getTemplateVariables();
        foreach ($variables as $k) {
            $variablesView->withCell($k, 'var')->setContent('{' . $k . '}');
        }

        $ret = $html->grid('3-1')
            ->setSpacing(3)
            ->add($ret)
            ->add($variablesView)
            ;

        $ret = $form->setContent($ret);

        $ret = $html->main($ret);
        $ret->title = $html->el('h1', $pageTitle);

        return $ret;
    }
}
