<?php

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

// Register routes
$this->bindClass('Sync\\Controller\\Utils', '/sync/utils');
$this->bindClass('Sync\\Controller\\Sync', '/sync');

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

    $settings['Addons'][] = [
        'icon' => 'sync:icon.svg',
        'route' => '/sync',
        'label' => 'Sync',
        'permission' => 'sync/manage'
    ];
});

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

    $permissions['Sync'] = [
        'sync/manage' => 'Manage Sync',
    ];
});

$this->on('spaces.config.create', function($config) {

    if (isset($config['sync']['syncKey'])) return;

    $config['sync'] = [
        'syncKey' => bin2hex(random_bytes(10))
    ];
});


$this->on([
    'content.singleton.item.aside',
    'content.collection.item.aside',
    'content.tree.item.aside'
], function($model) {

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

    $targets = $this->dataStorage->getKey('cockpit', 'sync.targets', []);

    if (empty($targets)) return;

    $caption = 'Sync item';

    if ($model['type'] == 'singleton') {
        $caption = 'Sync singleton';
    }

    echo $this->render('sync:views/partials/aside-sync-content.php', compact('model', 'targets', 'caption'));
});

$this->on('pages.page.aside', function($page) {

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

    $targets = $this->dataStorage->getKey('cockpit', 'sync.targets', []);

    if (empty($targets)) return;

    echo $this->render('sync:views/partials/aside-sync-page.php', compact('page', 'targets'));
});

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

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

    if (stripos('Sync', $search) !== false) {
        $findings[] = [
            'title' => 'Sync',
            'route' => $this->routeUrl('/sync'),
            'group' => 'Sync',
            'icon' => 'sync:icon.svg'
        ];
    }
});
