<?php
/**
 * includes/admin/manual-page.php
 *
 * ============================================================================
 * PÁGINA ADMIN "📖 MANUAL" — 1.5.149
 * ============================================================================
 *
 * Renderiza o ficheiro MANUAL.md (na raiz do plugin) numa página admin
 * com parser markdown leve (sem dependências externas).
 *
 * Funcionalidades:
 *   - Renderização: headings, listas, tabelas, code blocks, code inline,
 *     blockquotes, bold, italic, links, separadores
 *   - TOC (table of contents) flutuante à esquerda com scroll-to-section
 *   - Anchors automáticas em headings (slug)
 *   - Botão "📥 Download MANUAL.md" para offline reading
 *
 * Filosofia: parser inline (não usa Parsedown/CommonMark) porque o
 * manual é controlado por nós e não precisa de cobrir 100% do markdown.
 * Mantém zero dependências.
 */

if ( ! defined( 'ABSPATH' ) ) exit;


// ============================================================================
// HELPERS
// ============================================================================

/**
 * Localizar o MANUAL.md no plugin.
 *
 * [1.5.150] Antes usava WP_PLUGIN_DIR . '/1mz-for-artists/MANUAL.md'
 * que assume o nome da pasta. Falha se o plugin estiver instalado numa
 * pasta com nome diferente. Agora resolve dinamicamente.
 *
 * [1.5.151] MANUAL.md movido para assets/ (sítio padrão para recursos
 * do plugin, junto a css/ e js/).
 */
function rmbz_manual_get_path() {
    // includes/admin/manual-page.php → ../../assets/MANUAL.md
    $path = dirname( __FILE__, 3 ) . '/assets/MANUAL.md';
    return $path;
}

/**
 * Ler conteúdo do manual ou devolver string vazia.
 */
function rmbz_manual_get_content() {
    $path = rmbz_manual_get_path();
    if ( ! file_exists($path) ) return '';
    return (string) @file_get_contents($path);
}


// ============================================================================
// MARKDOWN PARSER (inline, leve)
// ============================================================================

/**
 * Parser markdown simples mas suficiente para o nosso MANUAL.md.
 * Suporta: # ## ### ####, **bold**, *italic*, `code`, ```block```,
 * - lists, 1. lists, > blockquotes, --- hr, [text](url),
 * | tables |, image-less-but-fine.
 *
 * NOTA: Cada heading recebe um id slug (anchor) para o TOC funcionar.
 *
 * @param string $md
 * @return string HTML
 */
function rmbz_manual_parse_markdown( $md ) {
    if ( empty($md) ) return '';

    // Normalizar quebras de linha
    $md = str_replace( ["\r\n", "\r"], "\n", $md );

    $lines = explode("\n", $md);
    $out = '';
    $in_code_block = false;
    $code_buffer = '';
    $code_lang = '';
    $in_list = false;
    $list_type = ''; // 'ul' | 'ol'
    $in_table = false;
    $table_rows = [];
    $in_blockquote = false;
    $blockquote_buffer = '';

    $close_list = function() use ( &$out, &$in_list, &$list_type ) {
        if ( $in_list ) {
            $out .= '</' . $list_type . ">\n";
            $in_list = false;
        }
    };

    $close_table = function() use ( &$out, &$in_table, &$table_rows ) {
        if ( $in_table && ! empty($table_rows) ) {
            $out .= '<div class="rmbz-manual-table-wrap"><table class="rmbz-manual-table">';
            $first_row = true;
            foreach ( $table_rows as $i => $row ) {
                // skip separator row (segunda linha tipicamente |---|---|)
                if ( $i === 1 && preg_match('/^\s*\|?\s*[\-:|\s]+\|?\s*$/', $row) ) continue;
                $cells = array_map( 'trim', explode('|', trim($row, "| \t")) );
                $tag = $first_row ? 'th' : 'td';
                $out .= '<tr>';
                foreach ( $cells as $c ) {
                    $out .= "<$tag>" . rmbz_manual_inline( $c ) . "</$tag>";
                }
                $out .= "</tr>\n";
                $first_row = false;
            }
            $out .= "</table></div>\n";
            $in_table = false;
            $table_rows = [];
        }
    };

    $close_blockquote = function() use ( &$out, &$in_blockquote, &$blockquote_buffer ) {
        if ( $in_blockquote ) {
            $out .= '<blockquote class="rmbz-manual-quote">' . rmbz_manual_inline( trim($blockquote_buffer) ) . "</blockquote>\n";
            $in_blockquote = false;
            $blockquote_buffer = '';
        }
    };

    foreach ( $lines as $line ) {
        // Code block fences
        if ( preg_match('/^```(\w*)$/', $line, $m) ) {
            if ( $in_code_block ) {
                // Fechar
                $out .= '<pre class="rmbz-manual-code"><code class="lang-' . esc_attr($code_lang) . '">'
                      . esc_html( rtrim($code_buffer, "\n") )
                      . "</code></pre>\n";
                $in_code_block = false;
                $code_buffer = '';
                $code_lang = '';
            } else {
                $close_list();
                $close_table();
                $close_blockquote();
                $in_code_block = true;
                $code_lang = $m[1] ?: 'text';
            }
            continue;
        }
        if ( $in_code_block ) {
            $code_buffer .= $line . "\n";
            continue;
        }

        // Tabelas
        if ( preg_match('/^\s*\|.*\|\s*$/', $line) ) {
            $close_list();
            $close_blockquote();
            $in_table = true;
            $table_rows[] = $line;
            continue;
        } elseif ( $in_table ) {
            $close_table();
        }

        // Blockquote
        if ( preg_match('/^>\s?(.*)$/', $line, $m) ) {
            $close_list();
            if ( ! $in_blockquote ) $in_blockquote = true;
            $blockquote_buffer .= $m[1] . "\n";
            continue;
        } elseif ( $in_blockquote ) {
            $close_blockquote();
        }

        // Heading
        if ( preg_match('/^(#{1,6})\s+(.+)$/', $line, $m) ) {
            $close_list();
            $level = strlen($m[1]);
            $text = trim($m[2]);
            $slug = rmbz_manual_slug( $text );
            $out .= "<h$level id=\"" . esc_attr($slug) . "\" class=\"rmbz-manual-h rmbz-manual-h$level\">"
                  . rmbz_manual_inline( $text ) . "</h$level>\n";
            continue;
        }

        // HR
        if ( preg_match('/^---+$/', trim($line)) ) {
            $close_list();
            $out .= "<hr class=\"rmbz-manual-hr\">\n";
            continue;
        }

        // List item — unordered (- ou *)
        if ( preg_match('/^[\-\*]\s+(.*)$/', $line, $m) ) {
            if ( ! $in_list || $list_type !== 'ul' ) {
                $close_list();
                $out .= "<ul class=\"rmbz-manual-ul\">\n";
                $in_list = true;
                $list_type = 'ul';
            }
            $out .= '<li>' . rmbz_manual_inline( $m[1] ) . "</li>\n";
            continue;
        }

        // List item — ordered
        if ( preg_match('/^\d+\.\s+(.*)$/', $line, $m) ) {
            if ( ! $in_list || $list_type !== 'ol' ) {
                $close_list();
                $out .= "<ol class=\"rmbz-manual-ol\">\n";
                $in_list = true;
                $list_type = 'ol';
            }
            $out .= '<li>' . rmbz_manual_inline( $m[1] ) . "</li>\n";
            continue;
        } else {
            $close_list();
        }

        // Linha vazia → fecha parágrafo (se houver)
        if ( trim($line) === '' ) {
            continue;
        }

        // Parágrafo normal
        $out .= '<p class="rmbz-manual-p">' . rmbz_manual_inline( $line ) . "</p>\n";
    }

    // Fechar tudo o que ficou aberto no fim
    $close_list();
    $close_table();
    $close_blockquote();

    return $out;
}


/**
 * Parsing inline: bold, italic, code, links.
 */
function rmbz_manual_inline( $text ) {
    // Escapar HTML primeiro (tudo no texto fica seguro)
    $text = esc_html( $text );

    // Code inline `xxx` — antes dos outros para não interferir
    $text = preg_replace('/`([^`]+)`/', '<code class="rmbz-manual-code-inline">$1</code>', $text);

    // Links [texto](url)
    $text = preg_replace_callback(
        '/\[([^\]]+)\]\(([^)]+)\)/',
        function($m) {
            $url = $m[2];
            // Anchors internas (#xxx) — manter
            if ( strpos($url, '#') === 0 ) {
                return '<a href="' . esc_attr($url) . '" class="rmbz-manual-link rmbz-manual-anchor">' . esc_html($m[1]) . '</a>';
            }
            // Externas — abrir em nova tab
            return '<a href="' . esc_url($url) . '" target="_blank" rel="noopener" class="rmbz-manual-link">' . esc_html($m[1]) . ' ↗</a>';
        },
        $text
    );

    // Bold **xxx**
    $text = preg_replace('/\*\*([^\*]+)\*\*/', '<strong>$1</strong>', $text);

    // Italic *xxx* (depois do bold para não conflitar)
    $text = preg_replace('/(?<!\*)\*([^\*\s][^\*]*)\*(?!\*)/', '<em>$1</em>', $text);

    return $text;
}


/**
 * Slug-ify para anchors. Usa o mesmo algoritmo que GitHub: lowercase,
 * espaços → hífen, remove caracteres não-alfanuméricos.
 */
function rmbz_manual_slug( $text ) {
    $text = strip_tags( $text );
    $text = mb_strtolower( $text, 'UTF-8' );
    // Remover acentos (transliteração simples)
    $text = remove_accents( $text );
    // Substituir espaços e caracteres especiais por hífen
    $text = preg_replace('/[^\w\s-]/u', '', $text);
    $text = preg_replace('/[\s_-]+/u', '-', $text);
    $text = trim( $text, '-' );
    return $text;
}


/**
 * Extrair TOC (lista de h2/h3) para sidebar.
 *
 * @param string $md
 * @return array [ ['level' => 2, 'text' => '...', 'slug' => '...'], ... ]
 */
function rmbz_manual_extract_toc( $md ) {
    $toc = [];
    $lines = explode("\n", $md);
    $in_code = false;
    foreach ( $lines as $line ) {
        if ( preg_match('/^```/', $line) ) { $in_code = ! $in_code; continue; }
        if ( $in_code ) continue;

        // Só capturamos h2 e h3 para o TOC (h1 é só o título do documento)
        if ( preg_match('/^(#{2,3})\s+(.+)$/', $line, $m) ) {
            $level = strlen($m[1]);
            $text = trim($m[2]);
            $toc[] = [
                'level' => $level,
                'text'  => $text,
                'slug'  => rmbz_manual_slug( $text ),
            ];
        }
    }
    return $toc;
}


// ============================================================================
// HANDLERS
// ============================================================================

/**
 * Endpoint para download do MANUAL.md como ficheiro.
 */
function rmbz_manual_handle_download() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    if ( ! check_admin_referer('rmbz_manual_download') ) wp_die('Falha de segurança.');

    $path = rmbz_manual_get_path();
    if ( ! file_exists($path) ) wp_die('Manual não encontrado.');

    $version = '';
    if ( function_exists('rmbz_predeploy_get_plugin_version') ) {
        $version = rmbz_predeploy_get_plugin_version();
    }
    $fname = 'MANUAL_1mz-for-artists' . ( $version ? '_v' . $version : '' ) . '.md';

    header('Content-Type: text/markdown; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $fname . '"');
    header('Content-Length: ' . filesize($path));
    @readfile($path);
    exit;
}
add_action('admin_post_rmbz_manual_download', 'rmbz_manual_handle_download');


// ============================================================================
// PÁGINA ADMIN
// ============================================================================

function rmbz_manual_render_page() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');

    $md = rmbz_manual_get_content();
    if ( empty($md) ) {
        echo '<div class="wrap"><h1>📖 Manual</h1>';
        echo '<div class="notice notice-error"><p>MANUAL.md não encontrado em <code>' . esc_html(rmbz_manual_get_path()) . '</code></p></div>';
        echo '</div>';
        return;
    }

    $toc = rmbz_manual_extract_toc( $md );
    $html = rmbz_manual_parse_markdown( $md );

    $download_url = wp_nonce_url(
        admin_url('admin-post.php?action=rmbz_manual_download'),
        'rmbz_manual_download'
    );
    ?>
    <div class="wrap">
        <h1 style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px;">
            <span>📖 Manual do 1MZ For Artists</span>
            <a href="<?php echo esc_url($download_url); ?>" class="button">⬇ Download MANUAL.md</a>
        </h1>

        <div class="rmbz-manual-layout">
            <?php /* TOC sidebar */ ?>
            <aside class="rmbz-manual-toc" id="rmbz-manual-toc">
                <h3>📑 Índice</h3>
                <nav>
                    <ul>
                        <?php foreach ( $toc as $item ): ?>
                            <li class="rmbz-toc-l<?php echo (int) $item['level']; ?>">
                                <a href="#<?php echo esc_attr($item['slug']); ?>"><?php echo esc_html($item['text']); ?></a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </nav>
            </aside>

            <?php /* Manual content */ ?>
            <article class="rmbz-manual-content">
                <?php echo $html; /* parser produz HTML controlado */ ?>
            </article>
        </div>
    </div>

    <style>
    /* [1.5.149] Estilos da página manual — auto-contidos, sem dependências */
    .rmbz-manual-layout {
        display: grid;
        grid-template-columns: 280px 1fr;
        gap: 24px;
        margin-top: 16px;
        max-width: 1400px;
    }
    @media (max-width: 900px) {
        .rmbz-manual-layout { grid-template-columns: 1fr; }
        .rmbz-manual-toc { position: static !important; max-height: 300px; }
    }

    .rmbz-manual-toc {
        position: sticky;
        top: 50px;
        max-height: calc(100vh - 80px);
        overflow-y: auto;
        background: #fff;
        border: 1px solid var(--rmbz-border-subtle, #ddd);
        border-radius: 6px;
        padding: 12px 14px;
        font-size: 13px;
        align-self: start;
    }
    .rmbz-manual-toc h3 { margin: 0 0 8px; font-size: 14px; color: #333; }
    .rmbz-manual-toc nav ul { list-style: none; margin: 0; padding: 0; }
    .rmbz-manual-toc nav li { margin: 2px 0; line-height: 1.4; }
    .rmbz-manual-toc nav a {
        text-decoration: none;
        color: var(--rmbz-info-strong, #2271b1);
        display: block;
        padding: 3px 6px;
        border-radius: 3px;
    }
    .rmbz-manual-toc nav a:hover { background: #f0f6fc; }
    .rmbz-manual-toc nav a.active { background: var(--rmbz-info-strong, #2271b1); color: #fff; font-weight: 600; }
    .rmbz-toc-l2 a { font-weight: 600; padding-left: 6px; }
    .rmbz-toc-l3 a { padding-left: 18px; color: #555; font-size: 12px; }

    .rmbz-manual-content {
        background: #fff;
        border: 1px solid var(--rmbz-border-subtle, #ddd);
        border-radius: 6px;
        padding: 24px 32px;
        line-height: 1.65;
        color: var(--wp-components-color-foreground, #1d2327);
        font-size: 14px;
    }
    .rmbz-manual-h { margin: 28px 0 12px; padding-top: 8px; scroll-margin-top: 50px; }
    .rmbz-manual-h1 { font-size: 28px; border-bottom: 2px solid var(--rmbz-info-strong, #2271b1); padding-bottom: 8px; }
    .rmbz-manual-h2 { font-size: 22px; border-bottom: 1px solid var(--rmbz-border-subtle, #e5e5e5); padding-bottom: 6px; color: var(--rmbz-info-strong, #2271b1); }
    .rmbz-manual-h3 { font-size: 17px; color: var(--wp-components-color-foreground, #1d2327); }
    .rmbz-manual-h4 { font-size: 15px; color: #444; }
    .rmbz-manual-h5, .rmbz-manual-h6 { font-size: 14px; color: #666; text-transform: uppercase; letter-spacing: 0.04em; }

    .rmbz-manual-p { margin: 8px 0 12px; }
    .rmbz-manual-hr { margin: 28px 0; border: none; border-top: 1px solid #e5e5e5; }

    .rmbz-manual-ul, .rmbz-manual-ol { margin: 8px 0 14px 24px; padding: 0; }
    .rmbz-manual-ul li, .rmbz-manual-ol li { margin: 4px 0; }

    .rmbz-manual-quote {
        margin: 12px 0;
        padding: 10px 14px;
        background: var(--rmbz-warning-soft, #fff8e1);
        border-left: 4px solid var(--rmbz-warning, #f0b90b);
        border-radius: 0 4px 4px 0;
        color: var(--rmbz-warning-strong, #5d4e1e);
    }
    .rmbz-manual-quote p { margin: 0; }

    .rmbz-manual-code-inline {
        background: #f3f4f6;
        color: var(--rmbz-brand-strong, #d63384);
        padding: 1px 6px;
        border-radius: 3px;
        font-family: Menlo, Consolas, monospace;
        font-size: 0.9em;
    }
    .rmbz-manual-code {
        background: #1f2328;
        color: #e6edf3;
        padding: 14px 16px;
        border-radius: 6px;
        overflow-x: auto;
        font-family: Menlo, Consolas, monospace;
        font-size: 12px;
        line-height: 1.5;
        margin: 12px 0;
    }
    .rmbz-manual-code code { background: transparent; color: inherit; padding: 0; }

    .rmbz-manual-table-wrap { overflow-x: auto; margin: 12px 0; }
    .rmbz-manual-table {
        border-collapse: collapse;
        width: 100%;
        font-size: 13px;
    }
    .rmbz-manual-table th, .rmbz-manual-table td {
        border: 1px solid #e5e5e5;
        padding: 8px 12px;
        text-align: left;
    }
    .rmbz-manual-table th {
        background: #f6f7f7;
        font-weight: 600;
        color: var(--wp-components-color-foreground, #1d2327);
    }
    .rmbz-manual-table tr:nth-child(even) td { background: #fafafa; }

    .rmbz-manual-link { color: var(--rmbz-info-strong, #2271b1); text-decoration: none; }
    .rmbz-manual-link:hover { text-decoration: underline; }
    .rmbz-manual-anchor { color: var(--rmbz-info-strong, #2271b1); }

    .rmbz-manual-content strong { color: var(--wp-components-color-foreground, #1d2327); }
    </style>

    <script>
    /* [1.5.149] Highlight da entrada actual no TOC ao fazer scroll. */
    (function(){
        var headings = document.querySelectorAll('.rmbz-manual-content h2, .rmbz-manual-content h3');
        var tocLinks = document.querySelectorAll('.rmbz-manual-toc a');
        if (!headings.length) return;
        if (!tocLinks.length) return;

        function setActive() {
            var scrollY = window.pageYOffset;
            var current = '';
            headings.forEach(function(h) {
                var top = h.offsetTop - 80;
                if (scrollY >= top) {
                    current = h.id;
                }
            });
            tocLinks.forEach(function(a) {
                a.classList.remove('active');
                if (a.getAttribute('href') === '#' + current) {
                    a.classList.add('active');
                }
            });
        }

        window.addEventListener('scroll', setActive, { passive: true });
        setActive();
    })();
    </script>
    <?php
}


// ============================================================================
// MENU
// ============================================================================

function rmbz_manual_register_menu() {
    // [1.5.150] Manual fica como último item do menu, junto às Configurações.
    // Prioridade 100 para garantir que aparece DEPOIS de todos os outros
    // submenus registados (incluindo Configurações que está em prioridade default).
    add_submenu_page(
        'rmbz-dashboard',
        'Manual do 1MZ',
        '📖 Manual',
        'manage_options',
        'rmbz-manual',
        'rmbz_manual_render_page'
    );
}
add_action('admin_menu', 'rmbz_manual_register_menu', 100);
