<?php
/**
 * DokuWiki Plugin docmaster (Syntax Component)
 *
 * Sintaxis: {{docmaster>listado}}
 * Opciones: {{docmaster>listado&ns=compartidos&active=1}}
 *
 * Renderiza la tabla del Listado Maestro de Documentos dentro de una página wiki.
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  SIE Systems <soporte@systemsie.site>
 */

class syntax_plugin_docmaster extends DokuWiki_Syntax_Plugin
{
    /**
     * @return string Tipo de sintaxis
     */
    public function getType()
    {
        return 'substition';
    }

    /**
     * @return string Tipo de párrafo
     */
    public function getPType()
    {
        return 'block';
    }

    /**
     * @return int Prioridad de coincidencia
     */
    public function getSort()
    {
        return 300;
    }

    /**
     * Registrar el patrón de sintaxis
     */
    public function connectTo($mode)
    {
        $this->Lexer->addSpecialPattern('\{\{docmaster>[^\}]+\}\}', $mode, 'plugin_docmaster');
    }

    /**
     * Parsear la sintaxis
     */
    public function handle($match, $state, $pos, Doku_Handler $handler)
    {
        // Extraer contenido entre {{docmaster> y }}
        $inner = substr($match, 13, -2); // quitar '{{docmaster>' y '}}'
        $parts = explode('&', $inner);

        $params = [
            'view'   => 'listado',
            'ns'     => '',
            'active' => 1,
            'search' => '',
        ];

        // Primer parte es el tipo de vista
        $params['view'] = trim($parts[0]);

        // Parsear parámetros adicionales
        for ($i = 1; $i < count($parts); $i++) {
            if (strpos($parts[$i], '=') !== false) {
                list($key, $value) = explode('=', $parts[$i], 2);
                $params[trim($key)] = trim($value);
            }
        }

        return $params;
    }

    /**
     * Renderizar la tabla
     */
    public function render($mode, Doku_Renderer $renderer, $data)
    {
        if ($mode !== 'xhtml') return false;

        /** @var helper_plugin_docmaster $helper */
        $helper = plugin_load('helper', 'docmaster');
        if (!$helper || !$helper->getDB()) {
            $renderer->doc .= '<div class="error">Docmaster: Error de base de datos</div>';
            return true;
        }

        switch ($data['view']) {
            case 'listado':
                $this->_renderListado($renderer, $helper, $data);
                break;
            case 'formatos':
                $this->_renderFormatos($renderer, $helper, $data);
                break;
            case 'stats':
                $this->_renderStats($renderer, $helper);
                break;
            default:
                $renderer->doc .= '<div class="error">Docmaster: Vista desconocida "' . hsc($data['view']) . '"</div>';
        }

        return true;
    }

    /**
     * Renderiza el listado maestro de documentos
     */
    protected function _renderListado(Doku_Renderer $renderer, $helper, $params)
    {
        $filters = [
            'active_only' => (bool) $params['active'],
        ];

        if (!empty($params['ns'])) {
            $filters['namespace'] = $params['ns'];
        }
        if (!empty($params['search'])) {
            $filters['search'] = $params['search'];
        }

        $documents = $helper->getDocuments($filters);

        $renderer->doc .= '<div class="docmaster-embed">';
        $renderer->doc .= '<div class="docmaster-table-wrap">';
        $renderer->doc .= '<table class="docmaster-table">';

        // Header
        $renderer->doc .= '<thead><tr>';
        $renderer->doc .= '<th>' . $this->getLang('col_title') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_code') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_version') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_validity') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_namespace') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_formats') . '</th>';
        $renderer->doc .= '</tr></thead>';

        // Body
        $renderer->doc .= '<tbody>';

        if (empty($documents)) {
            $renderer->doc .= '<tr><td colspan="6" style="text-align:center;color:#94a3b8;padding:2rem;">';
            $renderer->doc .= $this->getLang('no_results');
            $renderer->doc .= '</td></tr>';
        } else {
            foreach ($documents as $doc) {
                $pageUrl = wl($doc['page_id']);
                $formatCount = isset($doc['format_count']) ? (int) $doc['format_count'] : 0;

                $renderer->doc .= '<tr>';

                // Título
                $renderer->doc .= '<td>';
                $renderer->doc .= '<a href="' . $pageUrl . '">';
                $renderer->doc .= hsc($doc['title'] ?: $doc['page_id']);
                $renderer->doc .= '</a></td>';

                // Código
                $renderer->doc .= '<td>' . hsc($doc['code']) . '</td>';

                // Versión
                $renderer->doc .= '<td style="text-align:center;">' . (int) $doc['version'] . '</td>';

                // Vigencia
                $renderer->doc .= '<td>' . hsc($doc['validity_date']) . '</td>';

                // Namespace
                $renderer->doc .= '<td><span class="dm-ns-badge">' . hsc($doc['namespace']) . '</span></td>';

                // Formatos
                $renderer->doc .= '<td style="text-align:center;">';
                if ($formatCount > 0) {
                    // Mostrar formatos inline
                    $formats = $helper->getDocumentFormats($doc['id']);
                    $fmtNames = [];
                    foreach ($formats as $fmt) {
                        $fmtNames[] = hsc($fmt['display_name'] ?: $fmt['media_id']);
                    }
                    $renderer->doc .= '<span title="' . implode(', ', $fmtNames) . '">';
                    $renderer->doc .= $formatCount;
                    $renderer->doc .= '</span>';
                } else {
                    $renderer->doc .= '<span style="color:#cbd5e1;">0</span>';
                }
                $renderer->doc .= '</td>';

                $renderer->doc .= '</tr>';
            }
        }

        $renderer->doc .= '</tbody>';
        $renderer->doc .= '</table>';
        $renderer->doc .= '</div>'; // .docmaster-table-wrap
        $renderer->doc .= '</div>'; // .docmaster-embed
    }

    /**
     * Renderiza la tabla de formatos
     */
    protected function _renderFormatos(Doku_Renderer $renderer, $helper, $params)
    {
        $filters = [];
        if (!empty($params['search'])) {
            $filters['search'] = $params['search'];
        }

        $formats = $helper->getFormats($filters);

        $renderer->doc .= '<div class="docmaster-embed">';
        $renderer->doc .= '<div class="docmaster-table-wrap">';
        $renderer->doc .= '<table class="docmaster-table">';

        $renderer->doc .= '<thead><tr>';
        $renderer->doc .= '<th>' . $this->getLang('col_format_name') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_format_media') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_format_code') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_format_version') . '</th>';
        $renderer->doc .= '<th>' . $this->getLang('col_format_docs') . '</th>';
        $renderer->doc .= '</tr></thead>';

        $renderer->doc .= '<tbody>';

        if (empty($formats)) {
            $renderer->doc .= '<tr><td colspan="5" style="text-align:center;color:#94a3b8;padding:2rem;">Sin formatos</td></tr>';
        } else {
            foreach ($formats as $fmt) {
                $docCount = isset($fmt['document_count']) ? (int) $fmt['document_count'] : 0;

                $renderer->doc .= '<tr>';
                $renderer->doc .= '<td>' . hsc($fmt['display_name'] ?: '-') . '</td>';
                $renderer->doc .= '<td>' . hsc($fmt['media_id']) . '</td>';
                $renderer->doc .= '<td>' . hsc($fmt['code'] ?: '-') . '</td>';
                $renderer->doc .= '<td style="text-align:center;">' . ($fmt['version'] ?: '-') . '</td>';
                $renderer->doc .= '<td style="text-align:center;">' . $docCount . '</td>';
                $renderer->doc .= '</tr>';
            }
        }

        $renderer->doc .= '</tbody>';
        $renderer->doc .= '</table>';
        $renderer->doc .= '</div>';
        $renderer->doc .= '</div>';
    }

    /**
     * Renderiza estadísticas
     */
    protected function _renderStats(Doku_Renderer $renderer, $helper)
    {
        $stats = $helper->getStats();

        $renderer->doc .= '<div class="docmaster-embed">';
        $renderer->doc .= '<div class="docmaster-stats">';

        $items = [
            ['label' => $this->getLang('stat_documents'), 'value' => $stats['total_documents'] ?? 0],
            ['label' => $this->getLang('stat_formats'), 'value' => $stats['total_formats'] ?? 0],
            ['label' => $this->getLang('stat_namespaces'), 'value' => $stats['total_namespaces'] ?? 0],
            ['label' => $this->getLang('stat_shared'), 'value' => $stats['shared_formats'] ?? 0],
        ];

        foreach ($items as $item) {
            $renderer->doc .= '<div class="stat-card">';
            $renderer->doc .= '<span class="stat-number">' . (int) $item['value'] . '</span>';
            $renderer->doc .= '<span class="stat-label">' . hsc($item['label']) . '</span>';
            $renderer->doc .= '</div>';
        }

        $renderer->doc .= '</div>';
        $renderer->doc .= '</div>';
    }
}
