<?php

namespace YOOtheme\Demo\Routes;

use Joomla\CMS\Router\Route;
use Joomla\Component\Content\Site\Helper\RouteHelper;
use Joomla\Database\DatabaseDriver;
use YOOtheme\Builder;
use YOOtheme\Builder\Templates\TemplateController;
use YOOtheme\Event;
use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use YOOtheme\Storage;
use function YOOtheme\app;

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

    public static function handle($demo)
    {
        Event::on('theme.init', function () {
            $urls = array_values(
                array_filter(
                    array_map(
                        fn($tmpl) => $tmpl->url ?? null,
                        json_decode(
                            (string) TemplateController::index(
                                ...app(
                                    Request::class,
                                    Response::class,
                                    Storage::class,
                                    Builder::class
                                )
                            )->getBody()
                        )
                    ),
                    fn($url) => $url && !str_starts_with('#', $url)
                )
            );

            /** @var DatabaseDriver $db */
            $db = app(DatabaseDriver::class);
            $query = 'SELECT id, catid FROM #__content WHERE `fulltext` LIKE "%} -->"';

            foreach ($db->setQuery($query)->loadAssocList() as $article) {
                $urls[] = Route::_(RouteHelper::getArticleRoute($article['id'], $article['catid']));
            }

            echo json_encode($urls);
            exit();
        });
    }
}
