<?php

namespace Signteer\Web\Admin\Page\Volunteer;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Ui\Html;
use Signteer\Core\Action\Volunteer\CreateVolunteer;

final class Create
{
    public $action = CreateVolunteer::class;

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

        $form = $html->form()
            ->add($html->textInput('title')->setRequired())
            ->add($html->textInput('email')->setRequired())
            ->add($html->textInput('phone'))
            ;

        $ret = $html->blockList()
            ->add($html->dl('__Volunteer name__', $form->input('title')))
            ->add($html->dl('__Email__', $form->input('email')))
            ->add($html->dl('__Phone__', $form->input('phone')))
            ;

        $values = $form->grab($request);
        if ($values) {
            if ($form->isValid()) {
                $res = ($this->action)($values['title'], $values['email'], $values['phone']);
                if ($res->isOk()) {
                    $id = $res->getReturn();

                    return (new Redirect('..'));
                }

                $ret->add($html->dl('__Error__', $html->formErrors($res->getErrors())));
            }
        }

        $ret->add($html->dl(null, $html->button('__Save__')));
        $ret = $form->setContent($ret);

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

        return $ret;
    }
}
