<?php
if(!defined('ABSPATH')){echo 'Look your sister';exit;}

function boxmoe_markdown_to_html($text){
    $text = str_replace(["\r\n","\r"],"\n",$text);
    $blocks = [];
    $text = preg_replace_callback('/```([\s\S]*?)```/m', function($m) use (&$blocks){
        $key = '__MD_CODE_'.count($blocks).'__';
        $blocks[$key] = '<pre class="prettyprint linenums"><code>'.esc_html($m[1]).'</code></pre>';
        return $key;
    }, $text);
    $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);
    $text = preg_replace('/^>\s?(.+)$/m','<blockquote><p>$1</p></blockquote>',$text);
    $text = preg_replace_callback('/(^|\n)(?:-\s+.+(?:\n|$))+/', function($m){
        $items = preg_split('/\n/', trim($m[0]));
        $lis = '';
        foreach($items as $it){
            if(preg_match('/^-\s+(.+)/',$it,$mm)){$lis .= '<li>'.$mm[1].'</li>';}
        }
        return '<ul>'.$lis.'</ul>';
    }, $text);
    $text = preg_replace_callback('/(^|\n)(?:\d+\.\s+.+(?:\n|$))+/', function($m){
        $items = preg_split('/\n/', trim($m[0]));
        $lis = '';
        foreach($items as $it){
            if(preg_match('/^\d+\.\s+(.+)/',$it,$mm)){$lis .= '<li>'.$mm[1].'</li>';}
        }
        return '<ol>'.$lis.'</ol>';
    }, $text);
    $text = preg_replace('/\*\*(.+?)\*\*/s','<strong>$1</strong>',$text);
    $text = preg_replace('/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/s','<em>$1</em>',$text);
    $text = preg_replace('/`([^`]+)`/s','<code>$1</code>',$text);
    $text = preg_replace('/!\[([^\]]*)\]\(([^\)]+)\)/','<img src="$2" alt="$1" />',$text);
    $text = preg_replace('/\[([^\]]+)\]\(([^\)]+)\)/','<a href="$2"'.(is_admin()?'':' target="_blank"').'>$1</a>',$text);
    $parts = preg_split('/\n\n+/', trim($text));
    foreach($parts as &$p){
        if(!preg_match('/^\s*<(h\d|ul|ol|pre|blockquote|img)/i',$p)){
            $p = '<p>'.$p.'</p>';
        }
    }
    $html = implode("\n", $parts);
    foreach($blocks as $k=>$v){$html = str_replace($k,$v,$html);}    
    return $html;
}

function boxmoe_md_the_content($content){
    if(get_boxmoe('boxmoe_md_editor_switch')){
        return boxmoe_markdown_to_html($content);
    }
    return $content;
}
add_filter('the_content', 'boxmoe_md_the_content', 9);

if(get_boxmoe('boxmoe_md_editor_switch')){
    add_filter('use_block_editor_for_post', '__return_false');
    add_filter('user_can_richedit', '__return_false');
    add_action('admin_enqueue_scripts', function($hook){
        if($hook==='post.php' || $hook==='post-new.php'){
            wp_enqueue_style('boxmoe-md-editor', get_template_directory_uri().'/assets/css/markdown-editor.css', [], THEME_VERSION);
            wp_enqueue_script('boxmoe-md-editor', get_template_directory_uri().'/assets/js/markdown-editor.js', ['jquery'], THEME_VERSION, true);
            wp_localize_script('boxmoe-md-editor','BoxmoeMdEditor',[
                'enabled'=>true,
                'ajaxUrl'=>admin_url('admin-ajax.php'),
                'nonce'=>wp_create_nonce('boxmoe_md')
            ]);
        }
    });
    add_action('wp_ajax_boxmoe_md_preview', function(){
        if(!current_user_can('edit_posts')){wp_send_json_error(['message'=>'forbidden']);}
        if(!isset($_POST['nonce'])||!wp_verify_nonce($_POST['nonce'],'boxmoe_md')){wp_send_json_error(['message'=>'bad_nonce']);}
        $md = isset($_POST['markdown']) ? (string) wp_unslash($_POST['markdown']) : '';
        $html = boxmoe_markdown_to_html($md);
        $html = do_shortcode($html);
        wp_send_json_success(['html'=>$html]);
    });
}
