<?php

namespace Signteer\Web\Admin\Page\Sheet;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Ui\Html;
use Signteer\Core\Action\Volunteer\CreateVolunteer;
use Signteer\Core\Criteria\TaskCriteria;
use Signteer\Core\Criteria\VolunteerCriteria;
use Signteer\Core\Criteria\SignupCriteria;
use Signteer\Core\Finder\SheetFinder;
use Signteer\Core\Finder\TaskFinder;
use Signteer\Core\Finder\SignupFinder;
use Signteer\Core\Finder\VolunteerFinder;
use Signteer\Core\Model\Task;
use Signteer\Core\Model\Volunteer;

final class AssignNewVolunteerPage
{
    public $actionCreateVolunteer = CreateVolunteer::class;
    public $taskFinder = TaskFinder::class;
    public $sheetFinder = SheetFinder::class;
    public $signupFinder = SignupFinder::class;
    public $volunteerFinder = VolunteerFinder::class;

    public function __invoke(Request $request)
    {
        $sheetId = $request->getQueryParam('sheet');
        if (!$sheetId) {
            return new Redirect('admin/sheet');
        }

        $taskId = $request->getQueryParam('-task');
        if (!$taskId) {
            return new Redirect('admin/sheet/' . $sheetId);
        }

        $c = (new TaskCriteria())->whereSheetId('=', $sheetId)->whereId('=', $taskId);
        $task = current($this->taskFinder->find($c));
        if (!$task) {
            return new Redirect('admin/sheet/' . $sheetId);
        }

        $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->actionCreateVolunteer)($values['title'], $values['email'], $values['phone']);
                if ($res->isOk()) {
                    $id = $res->getReturn();

                    return (new Redirect('..', ['volunteer' => $id]));
                }

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

        $ret->add($html->dl(null, $html->button('__Save volunteer details and continue__')));
        $ret = $form->setContent($ret);

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

        return $ret;
    }
}
