<?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;
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\Model\SignupFieldFinder;

final class ViewSignupPage
{
    public $action = CreateSheet::class;
    public $sheetFinder = SheetFinder::class;
    public $taskFinder = TaskFinder::class;
    public $signupFinder = SignupFinder::class;

    public function breadcrumbTitle(Request $request)
    {
        $sheetId = $request->getQueryParam('sheet');
        $signupId = $request->getQueryParam('signup');
        if ((null === $sheetId) or (null === $signupId)) {
            return;
        }

        $c = (new SignupCriteria())
            ->whereSheetId('=', $sheetId)
            ->whereId('=', $signupId)
            ;
        $signup = current($this->signupFinder->findWithVolunteer($c));
        if (!$signup) {
            return;
        }

        $volunteer = $signup->getVolunteer();
        if (!$volunteer) {
            return;
        }

        $ret = $volunteer->getTitle();

        return $ret;
    }

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

        $c = (new SignupCriteria())
            ->whereSheetId('=', $sheetId)
            ->whereId('=', $signupId)
            ;
        $signup = current($this->signupFinder->findWithVolunteer($c));
        if (!$signup) {
            return (new Redirect('admin/sheet'));
        }

        $volunteer = $signup->getVolunteer();
        $task = $this->taskFinder->get($signup->getTaskId());

        $html = new Html();

        $ret = $html->dl()->asTable()
            ->add('__Task__', $task)
            ->add('__Volunteer__', $volunteer)
            ;

        $ret = $html->main($ret);
        $ret->title = $html->el('h1', '__Sign-up details__');
        $ret->menu->add($html->link('./notify', [], '__Resend notification__'));
        $ret->menu->add($html->link('./unassign', [], '__Unassign volunteer__'));

        return $ret;
    }
}
