<?php

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

// Register routes
$this->bindClass('Lokalize\\Controller\\Projects', '/lokalize/projects');
$this->bindClass('Lokalize\\Controller\\Utils', '/lokalize/utils');


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

    if (!$this->helper('acl')->isAllowed('lokalize/projects/manage')) {
        return;
    }

    $this->helper('menus')->addLink('modules', [
        'label'  => 'Lokalize',
        'icon'   => 'lokalize:icon.svg',
        'route'  => '/lokalize/projects',
        'active' => false,
        'group'  => 'Addons'
    ]);

    if (!$this->retrieve('lokalize/translation')) {
        return;
    }

    $this->on('app.layout.assets', function (array &$assets, $context) {
        if ($context === 'app:footer') $assets[] = ['src' => 'lokalize:assets/js/lokalize.js', 'type' => 'module'];
    });
});

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

    $permissions['Lokalize'] = [
        'lokalize/projects/manage' => 'Manage projects',
        'lokalize/api/read' => 'API access',
    ];
});

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

    if (!$this->helper('acl')->isAllowed('lokalize/projects/manage')) {
        return;
    }

    $projects = $this->dataStorage->find('lokalize/projects', [
        'filter' => [
            '$or' => [
                ['name' => ['$regex' => $search, '$options' => 'i']],
                ['label' => ['$regex' => $search, '$options' => 'i']],
            ]
        ],
        'fields' => ['values' => 0],
        'limit' => 5
    ])->toArray();

    foreach ($projects as $project) {

        $findings[] = [
            'title' => $project['name'],
            'route' => $this->routeUrl("/lokalize/projects/project/{$project['name']}"),
            'group' => 'Lokalize',
            'icon' => 'lokalize:icon.svg'
        ];
    }
});
