<?php
/**
 * Lightweight Markdown → HTML converter for server-side persistence
 * - Keeps frontend markdown artifact intact (frontend renders markdown)
 * - Converts to safe HTML for saving into WordPress post_content
 */

if (!function_exists('fleekdash_markdown_to_html')) {
    function fleekdash_markdown_to_html(string $markdown): string
    {
        $text = str_replace(["\r\n", "\r"], "\n", $markdown);

        // Code blocks ```
        $text = preg_replace_callback('/```([\s\S]*?)```/m', function ($m) {
            $code = htmlspecialchars($m[1], ENT_QUOTES, 'UTF-8');
            return "<pre><code>{$code}</code></pre>";
        }, $text);

        // Inline code `code`
        $text = preg_replace_callback('/`([^`]+)`/', function ($m) {
            $code = htmlspecialchars($m[1], ENT_QUOTES, 'UTF-8');
            return "<code>{$code}</code>";
        }, $text);

        // Headings
        $text = preg_replace('/^######\s*(.+)$/m', '<h6>$1</h6>', $text);
        $text = preg_replace('/^#####\s*(.+)$/m', '<h5>$1</h5>', $text);
        $text = preg_replace('/^####\s*(.+)$/m', '<h4>$1</h4>', $text);
        $text = preg_replace('/^###\s*(.+)$/m', '<h3>$1</h3>', $text);
        $text = preg_replace('/^##\s*(.+)$/m', '<h2>$1</h2>', $text);
        $text = preg_replace('/^#\s*(.+)$/m', '<h1>$1</h1>', $text);

        // Bold and italic (basic)
        $text = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $text);
        $text = preg_replace('/\*(.+?)\*/s', '<em>$1</em>', $text);

        // Unordered lists: group contiguous lines starting with - or *
        $lines = explode("\n", $text);
        $out = [];
        $inUl = false;
        foreach ($lines as $line) {
            if (preg_match('/^\s*[-\*]\s+(.+)/', $line, $m)) {
                if (!$inUl) {
                    $out[] = '<ul>';
                    $inUl = true;
                }
                $out[] = '<li>' . $m[1] . '</li>';
            } else {
                if ($inUl) {
                    $out[] = '</ul>';
                    $inUl = false;
                }
                $out[] = $line;
            }
        }
        if ($inUl) {
            $out[] = '</ul>';
        }
        $text = implode("\n", $out);

        // Ordered lists: simple 1. 2. pattern
        $lines = explode("\n", $text);
        $out = [];
        $inOl = false;
        foreach ($lines as $line) {
            if (preg_match('/^\s*\d+\.\s+(.+)/', $line, $m)) {
                if (!$inOl) {
                    $out[] = '<ol>';
                    $inOl = true;
                }
                $out[] = '<li>' . $m[1] . '</li>';
            } else {
                if ($inOl) {
                    $out[] = '</ol>';
                    $inOl = false;
                }
                $out[] = $line;
            }
        }
        if ($inOl) {
            $out[] = '</ol>';
        }
        $text = implode("\n", $out);

        // Convert double newlines to paragraphs using wpautop when available
        if (function_exists('wpautop')) {
            $html = wpautop($text);
        } else {
            $parts = preg_split('/\n\s*\n/', trim($text));
            $html = '<p>' . implode('</p><p>', array_map('trim', $parts)) . '</p>';
        }

        // Sanitize to allowed HTML
        if (function_exists('wp_kses_post')) {
            $html = wp_kses_post($html);
        }

        return $html;
    }
}
