<?php


// update assets references on asset remove
$this->on('assets.asset.remove', function(array $asset) {

    if ($this->helper('async')->possible()) {
        $this->helper('async')->exec('Cockpit()->module("pages")->updateRefs($asset["_id"], null);', compact('asset'));
    } else {
        $this->module('pages')->updateRefs($asset['_id'], null);
    }
});

// update assets references on asset update
$this->on('assets.asset.update', function(array $asset) {

    if ($this->helper('async')->possible()) {
        $this->helper('async')->exec('Cockpit()->module("pages")->updateRefs($asset["_id"], $asset);', compact('asset'));
    } else {
        $this->module('pages')->updateRefs($asset['_id'], $asset);
    }
});

// populate linked collection page type components
$this->on('layout.component.process', function ($component, &$array, $context = []) {

    $fields = [];
    $locale = $context['locale'] ?? 'default';

    if (!isset($array['data']) || !is_array($array['data'])) {
        return;
    }

    foreach ($array['data'] as $k => $v) {

        if (!isset($v['pageCollectionId'], $v['items']) || !$v['pageCollectionId']) continue;

        $page = $this->dataStorage->findOne('pages', ['_id' => $v['pageCollectionId']]);

        if (!$page || !isset($page['data']['collection']) || !$page['data']['collection'] || !$this->module('content')->exists($page['data']['collection'])) {
            $array['data'][$k]['items'] = [];
            continue;
        }

        $mode = $v['mode'] ?? 'dynamic';

        if (
            $mode == 'selected' &&
            !(isset($v['items']) && is_countable($v['items']) && count($v['items']))
        ) {
            $array['data'][$k]['items'] = [];
            continue;
        }

        $collection = $page['data']['collection'];
        $slugField  = isset($page['data']['slugField']) && $page['data']['slugField'] ? $page['data']['slugField'] : '_id';

        $filter = $page['data']['filter'] ?? [];
        $sort = $page['data']['sort'] ?? ['_created' => -1];
        $limit = $v['limit'] ?? 10;

        if (is_string($filter)) {

            try {
                $filter = json5_decode($filter, true);
            } catch (\Exception $e) {
                $filter = [];
            }
        }

        if (is_string($sort)) {

            try {
                $sort = json5_decode($sort, true);
            } catch (\Exception $e) {
                $sort = ['_created' => -1];
            }
        }

        $routeKey = $locale == 'default' ? '_r' : "_r_{$locale}";
        $list = [];

        $_filter = [
            ['_state' => 1]
        ];

        if (is_array($filter) && count($filter)) {
            $_filter[] = $filter;
        }

        if ($mode == 'selected') {

            $ids = [];

            foreach ($v['items'] as $item) {
                if (!isset($item['_id'])) continue;
                $ids[] = $item['_id'];
            }

            if (count($ids)) {
                $_filter[] = ['_id' => ['$in' => $ids]];
            }

        } elseif ($mode == 'dynamic') {

            if (isset($v['filter'])) {

                if (is_string($v['filter'])) {

                    try {
                        $v['filter'] = json5_decode($v['filter'], true);
                    } catch (\Exception $e) {
                        $v['filter'] = null;
                    }
                }

                if (is_array($v['filter'])) {
                    $_filter[] = $v['filter'];
                }
            }
        }

        $opts = [
            'filter' => ['$and' => $_filter],
            'sort' => $sort,
            'limit' => $limit ? $limit : 10,
        ];

        $process = [];

        if (isset($context['populate']) && $context['populate']) {
            //$process['populate'] = $context['populate'];
        }

        $items = $this->module('content')->items($collection, $opts, $process);

        if (count($items)) {

            if ($slugField != '_id' && $locale != 'default') {

                $model = $this->module('content')->model($collection);
                $fields = $model['fields'] ?? [];

                foreach ($fields as $field) {

                    if ($field['name'] == $slugField) {

                        if ($field['i18n']) {
                            $slugField = "{$slugField}_{$locale}";
                        }

                        break;
                    }
                }
            }

            foreach ($items as $item) {

                if (!isset($item[$slugField])) {
                    continue;
                }

                $list[] = [
                    'item' => $this->helper('locales')->applyLocales($item, $locale),
                    'route' => $page[$routeKey].'/'.$item[$slugField]
                ];
            }
        }

        $array['data'][$k]['items'] = $list;
    }

});
