<?php

namespace Signteer\Web\Admin\Page\Volunteer;

use Plainwork\Http\Request;
use Plainwork\Http\Redirect;
use Plainwork\Http\Dispatch;
use Plainwork\Ui\Html;
use Signteer\Core\Criteria\VolunteerCriteria as Criteria;
use Signteer\Core\Finder\VolunteerFinder;

final class Index
{
    public $finder = VolunteerFinder::class;

    public function __invoke(Request $request)
    {
        $c = (new Criteria());

        $limit = 10;
        $offset = $request->getQueryParam('offset-') ?? 0;
        $count = $this->finder->count($c);
        if (!$count) {
            return new Redirect('./create');
            // return new Dispatch('./create');
        }

        $ms = $this->finder->find($c, null, $limit, $offset);

        $html = new Html();

        $ret = $html->menu()->setVertical();
        foreach ($ms as $m) {
            $id = $m->getId();
            $ret_ = $html->link('admin/volunteer/' . $id, [], $m);
            $ret->add($ret_);
        }

        if ($count > $limit) {
            $pager = $html->pager($count, $limit)->setOffset($offset);
            $ret = $html->blockList($ret, $pager);
        }

        $ret = $html->main($ret);
        $ret->title = $html->el('h1', '__Volunteers__');
        $ret->titleMenu->add($html->link('./create', [], '__Add new__'));

        return $ret;
    }
}
