<?php

namespace Inbox\Controller;

class Inbox extends Controller {

    protected function before() {

        if (!$this->isAllowed('inbox/submissions') && !$this->isAllowed('inbox/manage') && !$this->hasAnyFormAccess()) {
            return $this->stop(401);
        }
    }

    protected function hasAnyFormAccess(): bool {

        $acl = $this->helper('acl');
        $forms = $this->app->dataStorage->find('inbox/forms', ['fields' => ['_id' => 1]])->toArray();

        foreach ($forms as $form) {
            if ($acl->isAllowed("inbox/{$form['_id']}/submissions")) {
                return true;
            }
        }

        return false;
    }

    public function index() {

        $this->helper('theme')->favicon('inbox:icon.svg');

        return $this->render('inbox:views/index.php');
    }

    public function load() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $options = [
            'sort' => ['name' => 1]
        ];

        $forms = $this->app->dataStorage->find('inbox/forms', $options)->toArray();

        // filter by per-form permissions unless global permission is set
        if (!$this->helper('acl')->isSuperAdmin() && !$this->isAllowed('inbox/submissions') && !$this->isAllowed('inbox/manage')) {

            $forms = \array_values(\array_filter($forms, function($form) {
                return $this->isAllowed("inbox/{$form['_id']}/submissions");
            }));
        }

        return $forms;
    }

}
