<?php

namespace Core\System;

class ContentSeoManager
{
    protected static bool $enabled = false;

    public static function start(): void
    {
        if (self::$enabled) {
            return;
        }
        self::$enabled = true;
        ob_start([self::class, 'process']);
    }

    public static function process(string $html): string
    {
        static $h1Found = false;

        $html = preg_replace_callback('/<h1\b[^>]*>(.*?)<\/h1>/is', function ($m) use (&$h1Found) {
            if ($h1Found) {
                return '<h2>' . $m[1] . '</h2>';
            }
            $h1Found = true;
            return $m[0];
        }, $html);

        $context = SeoManager::get();
        $fallbackAlt = htmlspecialchars($context['meta_title'] ?? $context['title'] ?? 'Image', ENT_QUOTES, 'UTF-8');

        $html = preg_replace_callback('/<img\b([^>]*)>/i', function ($m) use ($fallbackAlt) {
            $attrs = $m[1];
            if (stripos($attrs, 'alt=') === false) {
                $attrs .= ' alt="' . $fallbackAlt . '"';
            } elseif (preg_match('/alt\s*=\s*(["\"])\s*\1/i', $attrs)) {
                $attrs = preg_replace('/alt\s*=\s*(["\"])\s*\1/i', 'alt="' . $fallbackAlt . '"', $attrs, 1);
            }
            if (stripos($attrs, 'loading=') === false) {
                $attrs .= ' loading="lazy"';
            }
            if (stripos($attrs, 'decoding=') === false) {
                $attrs .= ' decoding="async"';
            }
            return '<img ' . trim($attrs) . '>';
        }, $html);

        $html = preg_replace_callback('/<a\b([^>]*)target=["\"][^"\"]["\"]([^>]*)>/i', function ($m) {
            $attrs = $m[1] . $m[2];
            if (stripos($attrs, 'rel=') === false) {
                return '<a ' . trim($m[1]) . 'target="_blank" rel="noopener noreferrer" ' . trim($m[2]) . '>';
            }
            return $m[0];
        }, $html);

        return $html;
    }
}
