<?php

$app = $this->app;

return [
    'name' => 'layout',
    'label' => 'Layout',
    'icon' => 'pages:assets/icons/layout.svg',
    'group' => 'Core',
    'data' => function() use($app) {

        $allowdLayoutComponents = $app->module('pages')->settings()['allowedLayoutComponents'] ?? [];

        return [
            [
                'name' => 'layout',
                'type' => 'layout',
                'i18n' => true,
                'opts' => ['allowedComponents' => $allowdLayoutComponents]
            ]
        ];
    },

    'process' => function($page, $locale = 'default', $options = []) use ($app) {

        if (is_array($page['data']['layout'] ?? null)) {

            $filterHiddenComponents = function($components) use(&$filterHiddenComponents) {
                $return = [];
                foreach ($components as $component) {
                    if ($component['hidden'] ?? false) continue;

                    if (isset($component['children']) && is_array($component['children']) && count($component['children'])) {
                        $component['children'] = $filterHiddenComponents($component['children']);
                    }
                    $return[] = $component;
                }
                return $return;
            };

            $page['data']['layout'] = $filterHiddenComponents($page['data']['layout']);
        }

        return $page;
    }
];
