<?php
/**
 * AI Auto Tool - Markdown Parser
 * Convert markdown text to HTML
 * 
 * Features:
 * - Parse markdown to HTML
 * - Support for various markdown syntax
 * - Lightweight and fast
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

if (!class_exists('AI_AutoTool_MarkdownParser')) {

class AI_AutoTool_MarkdownParser {
    public $active = false;
    public $active_option_name = 'AI_AutoTool_MarkdownParser_active';
    public $icon = '<i class="fa-solid fa-code"></i>';
    
    public function __construct() {
        $this->active = get_option($this->active_option_name, false);
        
        if ($this->active == 'true') {
            $this->init();
        }
        
        // AJAX handlers
        add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback'));
    }
    
    public function init() {
        // Initialize markdown parser functionality
        add_action('init', array($this, 'register_markdown_shortcodes'));
    }
    
    /**
     * Register markdown shortcodes
     */
    public function register_markdown_shortcodes() {
        add_shortcode('markdown', array($this, 'markdown_shortcode'));
    }
    
    /**
     * Markdown shortcode handler
     */
    public function markdown_shortcode($atts, $content = null) {
        if (empty($content)) {
            return '';
        }
        
        return $this->parse_markdown($content);
    }
    
    /**
     * Parse markdown text to HTML
     */
    public function parse_markdown($markdownText) {
        // Check if Parsedown class exists
        if (!class_exists('Parsedown')) {
            // Simple fallback parser for basic markdown
            return $this->simple_markdown_parser($markdownText);
        }
        
        $parsedown = new Parsedown();
        $html = $parsedown->text($markdownText);
        return $html;
    }
    
    /**
     * Simple markdown parser fallback
     */
    private function simple_markdown_parser($text) {
        // Convert headers
        $text = preg_replace('/^### (.*$)/m', '<h3>$1</h3>', $text);
        $text = preg_replace('/^## (.*$)/m', '<h2>$1</h2>', $text);
        $text = preg_replace('/^# (.*$)/m', '<h1>$1</h1>', $text);
        
        // Convert bold
        $text = preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $text);
        
        // Convert italic
        $text = preg_replace('/\*(.*?)\*/', '<em>$1</em>', $text);
        
        // Convert links
        $text = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '<a href="$2">$1</a>', $text);
        
        // Convert line breaks
        $text = nl2br($text);
        
        return $text;
    }
    
    /**
     * Update active option callback
     */
    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active, null, 'no');
            
            wp_send_json_success(array('active' => $active));
        }
        
        wp_send_json_error('Invalid request');
    }
    
    /**
     * Render feature settings
     */
    public function render_feature() {
        $box = new AutoToolBox(
            $this->icon . ' Markdown Parser',
            'Convert markdown text to HTML with support for various syntax',
            admin_url('admin.php?page=aiautotool_integrations'),
            $this->active_option_name,
            $this->active,
            '',
            false
        );
        
        echo $box->generateHTML();
    }
}

}

// Global function for backward compatibility
if (!function_exists('markdown')) {
    function markdown($markdownText) {
        if (class_exists('AI_AutoTool_MarkdownParser')) {
            $parser = new AI_AutoTool_MarkdownParser();
            return $parser->parse_markdown($markdownText);
        }
        
        // Fallback to simple parser
        return AI_AutoTool_MarkdownParser::simple_markdown_parser($markdownText);
    }
}
