<?php

namespace Signteer\Web\Admin\Page\Sheet;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Ui\Html;
use Signteer\Core\Action\Sheet\CreateSheet;

final class CreateSheetPage
{
    public $action = CreateSheet::class;

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

        $form = $html->form()
            ->add($html->textInput('title')->setRequired())
            ->add($html->textareaInput('description'))
            ;

        $ret = $html->blockList()
            ->add($html->dl('__Title__', $form->input('title')))
            ->add($html->dl('__Description__', $form->input('description')))
            ;

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

                    return (new Redirect('../' . $id . '/task/create'));
                }

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

        $ret->add($html->dl(null, $html->button('__Save sheet and continue to sheet tasks__')));
        $ret = $form->setContent($ret);

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

        return $ret;
    }
}
