<?php

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

// Register routes
$this->bindClass('Layout\\Controller\\Shared', '/layout-components/shared');
$this->bindClass('Layout\\Controller\\Templates', '/layout-components/templates');
$this->bindClass('Layout\\Controller\\Settings', '/layout-components');

$this->bind('/layout/components', function() {

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

    $components = new ArrayObject($this->helper('layoutComponents')->components());

    if ($this->param('list', 0)) {

        $this->response->mime = 'json';

        $list = [];

        foreach ($components as $name => $component) {

            $component['name'] = $name;
            $list[] = $component;
        }

        return $list;
    }

    $this->response->mime = 'js';

    return 'export default '.json_encode($components);
});

// events

$this->on('app.layout.assets', function(array &$assets, $context) {

    if ($context === 'app:header') $assets[] = 'layout:assets/css/layout.css';
    if ($context === 'app:footer') $assets[] = ['src' => 'layout:assets/js/layout.js', 'type' => 'module'];
});

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

    $settings['Addons'][] = [
        'icon' => 'layout:assets/icons/component.svg',
        'route' => '/layout-components',
        'label' => 'Layout Components',
        'permission' => 'layout/components/manage'
    ];
});

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

    $permissions['Layout'] = [
        // Align permission key with checks throughout the addon
        'layout/components/manage' => 'Manage components',
    ];
});

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

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

    if (stripos('Layout', $search) !== false || stripos('Components', $search) !== false) {

        $findings[] = [
            'title' => 'Layout Components',
            'route' => $this->routeUrl('/layout-components'),
            'group' => 'Layout Components',
            'icon' => 'layout:icon.svg'
        ];

        $findings[] = [
            'title' => 'Shared Layout Components',
            'route' => $this->routeUrl('/layout-components/shared'),
            'group' => 'Layout Components',
            'icon' => 'layout:assets/icons/shared.svg'
        ];
    }
});
