<?php

namespace YOOtheme\Demo\Routes;

use YOOtheme\Builder;
use YOOtheme\Builder\CollapseTransform;
use YOOtheme\Builder\Source\SourceTransform;
use YOOtheme\Builder\OptimizeTransform;
use YOOtheme\Http\Request;
use YOOtheme\Url;
use YOOtheme\View;
use function YOOtheme\app;

class ExportLayouts
{
    public static function match(Request $request)
    {
        return $request->getQueryParam('export');
    }

    public static function handle($demo)
    {
        $export = app('request')->getQueryParam('export');

        app()->extend(Builder::class, function (Builder $builder) use ($export) {
            $builder
                ->addTransform(
                    'preload',
                    function ($node, array &$params) use ($builder, $export) {
                        $params += ['context' => '', 'prefix' => '', 'template' => ''];

                        if (
                            empty($params['parent']) &&
                            $params['context'] !== 'export' &&
                            ((str_starts_with($params['prefix'], $export) &&
                                !str_starts_with($params['template'], '_')) ||
                                $params['template'] === $export)
                        ) {
                            $exported = json_encode(
                                $builder->load(
                                    json_encode($node),
                                    ['context' => 'export'] + $params
                                ),
                                JSON_UNESCAPED_SLASHES
                            );

                            $baseUrl = trim(json_encode(Url::base()), '"');

                            // remove demo content links
                            $exported = preg_replace(
                                "#href=\\\\\\\"({$baseUrl}|index\\.php)[^\"]*?\\\\\\\"#",
                                'href=\\"\\"',
                                $exported
                            );

                            $exported = preg_replace(
                                "#\"({$baseUrl}|index\\.php)[^\"]*?\"#",
                                '"#"',
                                $exported
                            );

                            // cleanup JoomlaImage URL
                            $exported = preg_replace('#\#joomlaImage[^"]*#', '', $exported);

                            $node->props['js'] = sprintf(
                                'var $export = JSON.parse(atob("%s"));',
                                base64_encode($exported)
                            );
                        }

                        if ($params['context'] === 'export') {
                            $params['context'] = 'render';
                            app(CollapseTransform::class)->preload($node, $params);
                            app(SourceTransform::class)->preload($node, $params);
                            $params['context'] = 'export';
                        }
                    },
                    0
                )
                ->addTransform('preexport', new OptimizeTransform())
                ->addTransform(
                    'preexport',
                    function ($node, &$params) use ($builder) {
                        if (($node->source->query->arguments->order ?? '') === 'rand') {
                            $node->source->query->arguments->order = 'publish_up';
                        }

                        return app(SourceTransform::class)->prerender($node, $params);
                    },
                    0
                )
                ->addTransform('export', [CollapseTransform::class, 'render'])
                ->addTransform('export', function ($node) use ($builder) {
                    unset($node->source, $node->parent);

                    // disable `Blend with page content`
                    if (isset($node->props['blend'])) {
                        $node->props['blend'] = false;
                    }

                    if ($node->type === 'row') {
                        $layouts = [
                            1 => '',
                            2 => '1-2,1-2',
                            3 => '1-3,1-3,1-3',
                            4 => '1-4,1-4,1-4,1-4|1-2,1-2,1-2,1-2',
                            5 => '1-5,1-5,1-5,1-5,1-5|1-2,1-2,1-3,1-3,1-3',
                            6 => '1-6,1-6,1-6,1-6,1-6,1-6|1-3,1-3,1-3,1-3,1-3,1-3',
                        ];

                        $columns = count(
                            explode(',', explode('|', $node->props['layout'] ?? '')[0])
                        );
                        $childrenCount = count($node->children ?? []);
                        if ($childrenCount && $columns !== $childrenCount) {
                            $node->props['layout'] = $layouts[$childrenCount];
                        }

                        if (!$childrenCount) {
                            unset($node->props['layout']);
                        }
                    }
                });

            $loader = function ($name, $parameters, callable $next) {
                $content = $next($name, $parameters);

                if (!empty($parameters['props']['js'])) {
                    $content .= "\n<script>{$parameters['props']['js']}</script>";
                }

                return $content;
            };

            // Append script to layout (similar to custom CSS) to make it work on error page too
            app(View::class)
                ->addLoader($loader, '*/builder/elements/layout/templates/template.php')
                ->addLoader($loader, '*/builder/elements/fragment/templates/template.php');
        });
    }
}
