<?php

namespace Signteer\Web\Admin\Page\Sheet;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Ui\Html;
use Signteer\Core\Criteria\TaskCriteria;
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\Action\Signup\SendConfirmationEmailToVolunteer;

final class ResendSignupNotificationPage
{
    public $finder = SheetFinder::class;
    public $taskFinder = TaskFinder::class;
    public $signupFinder = SignupFinder::class;
    public $volunteerFinder = VolunteerFinder::class;
    public $sendAction = SendConfirmationEmailToVolunteer::class;

    public function __invoke(Request $request)
    {
        $signupId = $request->getQueryParam('signup');
        $signup = $this->signupFinder->get($signupId);
        if (!$signup) {
            return (new Redirect('admin/signup'));
        }

        $volunteer = $this->volunteerFinder->get($signup->getVolunteerId());
        if (!$signup) {
            return (new Redirect('admin/signup/' . $signupId));
        }

        $html = new Html();

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

        $v = $volunteer->getEmail();
        $ret->add($html->dl('__To__', $html->card($v)));

        list($subj, $msg) = $this->sendAction->buildSubjectMessage($signupId);

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

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

        $values = $form->grab($request);
        if ($values) {
            if ($form->isValid()) {
                $res = ($this->sendAction)($signupId, $values['subj'], $values['msg']);
                if ($res->isOk()) {
                    $id = $res->getReturn();

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

                $form->addErrors($res->getErrors());
            }
        }

        $errors = $form->getErrors();
        if ($errors) {
            $ret->add($html->dl('__Error__', $errors));
        }

        $ret->add($html->dl(null, $html->button('__Send notification__')));

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

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

        return $ret;
    }
}
