<?php

namespace Core\System;

class SchemaManager
{
    protected static array $schemas = [];
    protected static bool $booted = false;

    public static function boot(): void
    {
        if (self::$booted) {
            return;
        }

        self::$booted = true;
        $seo = SeoManager::get();

        self::organization();
        if ($seo['type'] === 'product' && !empty($seo['schema']) && is_array($seo['schema'])) {
            self::$schemas[] = array_filter($seo['schema']);
        }
        self::breadcrumb($seo);
    }

    protected static function organization(): void
    {
        $logo = SeoManager::get()['image'] ?? '';
        $schema = [
            '@context' => 'https://schema.org',
            '@type'    => 'Organization',
            'name'     => ThemeManager::getSetting('site_name', 'Website'),
            'url'      => url('/'),
            'logo'     => $logo !== '' ? url($logo) : null,
            'sameAs'   => self::socialLinks(),
        ];

        self::$schemas[] = array_filter($schema);
    }

    protected static function breadcrumb(array $seo): void
    {
        $items = [[
            '@type' => 'ListItem',
            'position' => 1,
            'name' => ThemeManager::getSetting('site_name', 'Home'),
            'item' => url('/'),
        ]];

        if (in_array($seo['type'] ?? '', ['product', 'page', 'products_archive', 'category_archive'], true)) {
            $items[] = [
                '@type' => 'ListItem',
                'position' => 2,
                'name' => $seo['meta_title'] ?? $seo['title'] ?? '',
                'item' => $seo['canonical'] ?? url('/'),
            ];
        }

        self::$schemas[] = [
            '@context' => 'https://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => $items,
        ];
    }

    public static function render(): string
    {
        if (empty(self::$schemas)) {
            self::boot();
        }

        return '<script type="application/ld+json">' . json_encode(self::$schemas, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>';
    }

    protected static function socialLinks(): array
    {
        $links = [];
        foreach (['facebook','instagram','twitter','youtube','linkedin'] as $s) {
            $val = ThemeManager::getSetting('social_' . $s);
            if ($val) {
                $links[] = $val;
            }
        }
        return $links;
    }
}
