<?php

$this->helper('license')->require();

// Register routes
$this->bindClass('Inbox\\Controller\\Forms', '/inbox/forms');
$this->bindClass('Inbox\\Controller\\Submissions', '/inbox/submissions');
$this->bindClass('Inbox\\Controller\\Inbox', '/inbox');

//events
$this->on('app.layout.init', function() {

    if (
        !$this->helper('acl')->isAllowed('inbox/manage') &&
        !$this->helper('acl')->isAllowed('inbox/submissions')
    ) {
        return;
    }

    $this->helper('menus')->addLink('modules', [
        'label'  => 'Inbox',
        'icon'   => 'inbox:icon.svg',
        'route'  => '/inbox',
        'active' => false,
        'group'  => 'Addons',
        'prio'   => 1
    ]);
});

// events

$this->on('app.permissions.collect', function($permissions) {

    $permissions['Inbox'] = [
        'inbox/manage' => 'Manage inbox',
        'inbox/submissions' => 'Read inbox submissions',
    ];
});

$this->on('app.search', function($search, $findings) {

    if (!$this->helper('acl')->isAllowed('inbox/submissions') && !$this->helper('acl')->isAllowed('inbox/manage')) {
        return;
    }

    $forms = $this->dataStorage->find('inbox/forms', [
        'filter' => [
            'name' => ['$regex' => $search, '$options' => 'i']
        ],
        'limit' => 5
    ])->toArray();

    foreach ($forms as $form) {

        $findings[] = [
            'title' => $form['name'],
            'route' => $this->routeUrl("/inbox/submissions/form/{$form['_id']}"),
            'group' => 'Inbox',
            'icon' => 'inbox:icon.svg'
        ];
    }
});

$this->on('app.dashboard.widgets', function($widgets) {

    if (
        !$this->helper('acl')->isAllowed('inbox/manage') &&
        !$this->helper('acl')->isAllowed('inbox/submissions')
    ) {
        return;
    }

    $forms = $this->dataStorage->find('inbox/forms', [
        'sort' => ['name' => 1]
    ])->toArray();

    $forms = array_values(array_filter($forms, function($form) {

        $collection = "inbox/form_{$form['_id']}";

        return $this->dataStorage->count($collection);
    }));

    if (!count($forms)) {
        return;
    }

    $widgets[] = [
        'name' => 'dashboard-inbox-widget',
        'area' => 'secondary',
        'component' => 'inbox:assets/vue-components/dashboard-widget.js',
        'data' => compact('forms')
    ];

});
