<?php
if(!defined('DOKU_INC')) die();

class syntax_plugin_pgpblock extends DokuWiki_Syntax_Plugin {
    public function getType() { return 'protected'; }
    public function getPType() { return 'normal'; }
    public function getSort() { return 150; }

    public function connectTo($mode) {
        /**
         * We use (?s:...) which is the PCRE 'DOTALL' modifier.
         * This allows the dot (.) to match newlines, which is 
         * mandatory for multi-line PGP blocks.
         */
        $this->Lexer->addSpecialPattern('(?s:<pgp\b.*?>.*?</pgp>)', $mode, 'plugin_pgpblock');
        $this->Lexer->addSpecialPattern('(?s:<gpg\b.*?>.*?</gpg>)', $mode, 'plugin_pgpblock');
        $this->Lexer->addSpecialPattern('(?s:<pgpfile\b.*?>.*?</pgpfile>)', $mode, 'plugin_pgpblock');
    }

    public function handle($match, $state, $pos, Doku_Handler $handler) {
        // 1. Identify the tag and capture attributes
        if (preg_match('/^<(pgp|gpg|pgpfile)(.*?)>(.*)<\/\1>$/is', $match, $matches)) {
            $tag = strtolower($matches[1]);
            $attr_str = $matches[2];
            $text = trim($matches[3]);
        } else {
            return false;
        }

        // 2. Extract filename attribute safely
        $filename = '';
        if (preg_match('/filename=["\']([^"\']+)["\']/i', $attr_str, $fn_match)) {
            $filename = $fn_match[1];
        }
        
        return array($text, $tag, $filename);
    }

    public function render($format, Doku_Renderer $renderer, $data) {
        if($format != 'xhtml' || $data === false) return false;

        list($text, $tag, $filename) = $data;
        $is_encrypted = (strpos($text, '-----BEGIN PGP MESSAGE-----') !== false);
        $encoded_text = hsc($text);

        if ($is_encrypted) {
            $is_file = ($tag === 'pgpfile');
            $type_class = $is_file ? 'pgp-type-file' : 'pgp-type-text';
            $title = $is_file ? '📦 Encrypted File' : '📄 Encrypted Text';
            if ($is_file && $filename) $title .= ': ' . hsc($filename);
            
            $renderer->doc .= '<div class="pgpblock-container ' . $type_class . '">';
            $renderer->doc .= '<div class="pgp-header">' . $title . '</div>';
            $renderer->doc .= '<pre class="pgpblock">' . $encoded_text . '</pre>';
            $renderer->doc .= '</div>';
        } else {
            // Render unencrypted text in the white box
            $renderer->doc .= '<pre class="pgpblock-plaintext">' . $encoded_text . '</pre>';
        }

        return true;
    }
}
