<?php

namespace Wizard\Framework\Database;

class MarkdownParser
{
    public static function toHtml(string $markdown): string
    {
        $code_block_pattern = '/```([a-z]+)\s+(.*?)\s+```/si';
        $inline_code_pattern = '/`\s*(.*?)\s*`/si';
        $matches = [];

        preg_match_all($code_block_pattern, $markdown, $matches, PREG_SET_ORDER);
        $code_blocks = [];
        foreach ($matches as $index => $match) {
            $code_blocks[] = [
                'language' => $match[1],
                'code' => $match[2],
            ];
        }

        foreach ($matches as $index => $match) {
            $markdown = preg_replace('/'.preg_quote($match[0], '/').'/', '[CODE_BLOCK_'.$index.']', $markdown, 1);
        }

        preg_match_all($inline_code_pattern, $markdown, $matches, PREG_SET_ORDER);
        $inline_code = [];
        foreach ($matches as $index => $match) {
            $inline_code[] = [
                'code' => $match[1],
            ];
        }

        foreach ($matches as $index => $match) {
            $markdown = preg_replace('/'.preg_quote($match[0], '/').'/', '[INLINE_CODE_'.$index.']', $markdown, 1);
        }

        $markdown = preg_replace('/`(.+?)`/', '<code>$1</code>', $markdown);
        $markdown = preg_replace('/\#{6}\s(.+)/', '<h6>$1</h6>', $markdown);
        $markdown = preg_replace('/\#{5}\s(.+)/', '<h5>$1</h5>', $markdown);
        $markdown = preg_replace('/\#{4}\s(.+)/', '<h4>$1</h4>', $markdown);
        $markdown = preg_replace('/\#{3}\s(.+)/', '<h3>$1</h3>', $markdown);
        $markdown = preg_replace('/\#{2}\s(.+)/', '<h2>$1</h2>', $markdown);
        $markdown = preg_replace('/\#\s(.+)/', '<h1>$1</h1>', $markdown);
        $markdown = preg_replace('/\*\*\*(.+?)\*\*\*/', '<strong><em>$1</em></strong>', $markdown);
        $markdown = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $markdown);
        $markdown = preg_replace('/\*(.+?)\*/', '<em>$1</em>', $markdown);
        $markdown = preg_replace('/\[(.+?)\]\((.+?)\)/', '<a href="$2">$1</a>', $markdown);
        $markdown = preg_replace("/\r\n|\r|\n/", '<br>', $markdown);

        foreach ($code_blocks as $index => $code_block) {
            $language = $code_block['language'];
            $language = $language == 'blade' ? 'html' : $language;
            $code_block['code'] = '<pre><code class="match-braces language-'.$language.'">'.htmlentities($code_block['code']).'</code></pre>';
            $markdown = str_replace('[CODE_BLOCK_'.$index.']', $code_block['code'], $markdown);
        }

        foreach ($inline_code as $index => $code) {
            $code['code'] = '<code>'.htmlentities($code['code']).'</code>';
            $markdown = str_replace('[INLINE_CODE_'.$index.']', $code['code'], $markdown);
        }

        return $markdown;
    }
}
