<?php
/**
 * 视图模板引擎（优化版）
 * Date: 2026-07-18
 * Author: 小新
 * SystemName: XiaoPHP
 */

namespace XiaoPHP\System;

class View
{
    private $data = [];
    private $path = '';
    private $autoEscape = true;
    private $debug = null;

    // 全局配置
    private static $config = [
        'cache_dir'      => null,
        'debug'          => false,
        'minify_html'    => true,
        'preserve_tags'  => ['pre', 'textarea', 'script', 'style'],
        'asset_meta'     => null,
    ];

    /**
     * 设置全局配置
     */
    public static function setConfig(array $config)
    {
        self::$config = array_merge(self::$config, $config);
        if (self::$config['cache_dir'] === null) {
            self::$config['cache_dir'] = SYS_ROOT.'/../Temp/View';
        }
       
        if (!is_dir(self::$config['cache_dir'])) {
            mkdir(self::$config['cache_dir'], 0755, true);
        }
    }

    /**
     * 绑定数据、设置模板路径前缀，并可单独指定调试模式
     */
    public function set($data, $path = '', $debug = null)
    {
        $this->data = array_merge($this->data, $data);
        $path = preg_replace('/[^a-zA-Z0-9_\-\\/]/', '', $path);
        $path = preg_replace('#/+#', '/', $path);
        $parts = array_filter(explode('/', $path), function ($p) {
            return $p !== '..' && $p !== '.';
        });
        $this->path = implode('/', $parts);
        $this->debug = $debug;
        return $this;
    }

    /**
     * 设置是否自动转义
     */
    public function setAutoEscape($enabled = true)
    {
        $this->autoEscape = $enabled;
        return $this;
    }

    /**
     * 获取当前模块的 View 目录
     */
    private function getModulePath()
    {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        $callerFile = $trace[1]['file'] ?? __FILE__;
        return dirname($callerFile, 2) . DIRECTORY_SEPARATOR;
    }

    /**
     * 渲染模板并返回内容
     */
    public function show($filename)
    {
        $filename = basename($filename);
        $filename = preg_replace('/[^a-zA-Z0-9_\-.]/', '', $filename);
        $viewBase = $this->getModulePath() . 'View';
        if (!is_dir($viewBase)) {
            throw new \Exception("视图根目录不存在: $viewBase");
        }

        $relative = ($this->path ? $this->path . '/' : '') . $filename . '.html';
        $relative = ltrim($relative, '/');
        $file = $viewBase . '/' . $relative;

        $realFile = realpath($file);
        if ($realFile === false || strpos($realFile, $viewBase) !== 0) {
            throw new \Exception("模板不存在或非法路径: $relative");
        }
        if (!file_exists($realFile)) {
            throw new \Exception("模板不存在: $relative");
        }

        $compiledFile = $this->getCompiledPath($realFile);
        if (!file_exists($compiledFile) || filemtime($realFile) > filemtime($compiledFile)) {
            $content = file_get_contents($realFile);
            $compiled = $this->compile($content);
            $cacheDir = dirname($compiledFile);
            if (!is_dir($cacheDir)) {
                mkdir($cacheDir, 0755, true);
            }
            file_put_contents($compiledFile, $compiled);
        }

        extract($this->data);
        ob_start();
        try {
            include $compiledFile;
            $output = ob_get_contents();
            ob_end_clean();
        } catch (\Throwable $e) {
            ob_end_clean();
            throw $e;
        }

        $isDebug = ($this->debug === null) ? self::$config['debug'] : $this->debug;
        if (!$isDebug && self::$config['minify_html']) {
            $output = $this->minifyHtml($output);
        }
        $output = $this->injectAssetMeta($output);

        return $output;
    }

    /**
     * 获取编译后的缓存文件路径
     */
    private function getCompiledPath($templateFile)
    {
        $cacheDir = self::$config['cache_dir'];
        if (!is_dir($cacheDir)) {
            mkdir($cacheDir, 0755, true);
        }
        $key = md5($templateFile);
        return $cacheDir . '/' . $key . '.php';
    }

    /**
     * 模板编译主方法（优化版）
     */
    private function compile($content)
    {
        // 1. 保护 CSS 和 JS 中的特殊语法（@media、@keyframes 等）
        $protectedBlocks = $this->protectSpecialBlocks($content);
        $content = $protectedBlocks['content'];
        $placeholders = $protectedBlocks['placeholders'];

        // 2. 执行原有的编译逻辑
        $content = $this->compileExtends($content);
        $content = $this->compileInclude($content);
        $content = $this->compileIf($content);
        $content = $this->compileForeach($content);
        $content = $this->compileFor($content);
        $content = preg_replace('/@php\s+(.*?)\s+@endphp/is', '<?php $1 ?>', $content);
        $content = $this->compileVariables($content);
        $content = $this->compileYield($content);
        $content = preg_replace('/\{\{--(.*?)--\}\}/s', '', $content);
        $content = $this->compileRawPhp($content);

        // 3. 恢复被保护的 CSS/JS 内容
        foreach ($placeholders as $key => $value) {
            $content = str_replace($key, $value, $content);
        }

        return $content;
    }

    /**
     * 保护 CSS 和 JS 中的特殊语法不被 compileRawPhp 破坏
     */
    private function protectSpecialBlocks($content)
    {
        $placeholders = [];
        $counter = 0;

        // 保护 <style> 标签内容
        $content = preg_replace_callback(
            '/<style([^>]*)>(.*?)<\/style>/is',
            function ($m) use (&$placeholders, &$counter) {
                $key = '%%PROTECTED_BLOCK_' . $counter++ . '%%';
                $placeholders[$key] = '<style' . $m[1] . '>' . $m[2] . '</style>';
                return $key;
            },
            $content
        );

        // 保护 <script> 标签内容
        $content = preg_replace_callback(
            '/<script([^>]*)>(.*?)<\/script>/is',
            function ($m) use (&$placeholders, &$counter) {
                $key = '%%PROTECTED_BLOCK_' . $counter++ . '%%';
                $placeholders[$key] = '<script' . $m[1] . '>' . $m[2] . '</script>';
                return $key;
            },
            $content
        );

        // 保护内联 style 属性中的 CSS（如 style="color: red; @media ..."）
        $content = preg_replace_callback(
            '/style\s*=\s*(["\\\'])(.*?)\\1/s',
            function ($m) use (&$placeholders, &$counter) {
                $key = '%%PROTECTED_BLOCK_' . $counter++ . '%%';
                $placeholders[$key] = 'style=' . $m[1] . $m[2] . $m[1];
                return $key;
            },
            $content
        );

        return [
            'content' => $content,
            'placeholders' => $placeholders
        ];
    }

    /**
     * 处理 @extends 和 @section/@parent
     */
    private function compileExtends($content)
    {
        if (preg_match('/@extends\s*\([\'"]([^\'"]+)[\'"]\)/', $content, $match)) {
            $layout = $match[1];
            preg_match_all('/@section\s*\([\'"]([^\'"]+)[\'"]\)\s*(.*?)\s*@endsection/s', $content, $sections, PREG_SET_ORDER);
            $sectionsMap = [];
            foreach ($sections as $sec) {
                $sectionsMap[$sec[1]] = $sec[2];
            }
            $layoutContent = $this->fetchLayout($layout);
            $layoutContent = preg_replace_callback(
                '/@yield\s*\([\'"]([^\'"]+)[\'"]\)/',
                function ($m) use ($sectionsMap) {
                    $sectionName = $m[1];
                    $content = isset($sectionsMap[$sectionName]) ? $sectionsMap[$sectionName] : '';
                    return $content;
                },
                $layoutContent
            );
            return $layoutContent;
        }
        return $content;
    }

    private function fetchLayout($layout)
    {
        $viewBase = $this->getModulePath() . 'View';
        $layoutFile = $viewBase . '/' . str_replace('.', '/', $layout) . '.html';
        if (!file_exists($layoutFile)) {
            throw new \Exception("布局模板不存在: $layoutFile");
        }
        $content = file_get_contents($layoutFile);
        return $this->compile($content);
    }

    private function compileInclude($content)
    {
        return preg_replace_callback(
            '/@include\s*\([\'"]([^\'"]+)[\'"]\)/',
            function ($m) {
                $sub = $m[1];
                $viewBase = $this->getModulePath() . 'View';
                $subFile = $viewBase . '/' . str_replace('.', '/', $sub) . '.html';
                if (!file_exists($subFile)) {
                    return "<!-- Include not found: $sub -->";
                }
                $subContent = file_get_contents($subFile);
                return $this->compile($subContent);
            },
            $content
        );
    }

    private function compileIf($content)
    {
        $patterns = [
            '/@if\s*\(([^()]*(?:\((?>[^()]*|(?R))*\)[^()]*)*)\)/' => '<?php if ($1): ?>',
            '/@elseif\s*\(([^()]*(?:\((?>[^()]*|(?R))*\)[^()]*)*)\)/' => '<?php elseif ($1): ?>',
            '/@else/' => '<?php else: ?>',
            '/@endif/' => '<?php endif; ?>',
        ];
        foreach ($patterns as $pattern => $replacement) {
            $content = preg_replace($pattern, $replacement, $content);
        }
        return $content;
    }

    private function compileForeach($content)
    {
        $content = preg_replace('/@foreach\s*\(([^()]*(?:\((?>[^()]*|(?R))*\)[^()]*)*)\)/', '<?php foreach ($1): ?>', $content);
        $content = preg_replace('/@endforeach/', '<?php endforeach; ?>', $content);
        $content = preg_replace('/@forelse\s*\(([^()]*(?:\((?>[^()]*|(?R))*\)[^()]*)*)\)/', '<?php if (count($1) > 0): foreach ($1): ?>', $content);
        $content = preg_replace('/@empty/', '<?php endforeach; else: ?>', $content);
        $content = preg_replace('/@endforelse/', '<?php endif; ?>', $content);
        return $content;
    }

    private function compileFor($content)
    {
        $content = preg_replace('/@for\s*\((.+?)\)/', '<?php for ($1): ?>', $content);
        $content = preg_replace('/@endfor/', '<?php endfor; ?>', $content);
        return $content;
    }

    private function compileVariables($content)
    {
        // 处理 {{! $var }} 不转义
        $content = preg_replace_callback(
            '/\{\{\!\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?:(?:\.[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*(?:\[\'[^\']+\'])*)*\s*\}\}/',
            function ($m) {
                $var = $this->parseVariablePath($m[1], substr($m[0], strpos($m[0], '$') + 1, strpos($m[0], '}') - strpos($m[0], '$') - 1));
                return "<?php echo $var; ?>";
            },
            $content
        );

        // 处理 {{ $var }} 根据 autoEscape 决定是否转义
        if ($this->autoEscape) {
            $content = preg_replace_callback(
                '/\{\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?:(?:\.[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*(?:\[\'[^\']+\'])*)*\s*\}\}/',
                function ($m) {
                    $var = $this->parseVariablePath($m[1], substr($m[0], strpos($m[0], '$') + 1, strpos($m[0], '}') - strpos($m[0], '$') - 1));
                    return "<?php echo htmlspecialchars($var, ENT_QUOTES, 'UTF-8'); ?>";
                },
                $content
            );
        } else {
            $content = preg_replace_callback(
                '/\{\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?:(?:\.[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*(?:\[\'[^\']+\'])*)*\s*\}\}/',
                function ($m) {
                    $var = $this->parseVariablePath($m[1], substr($m[0], strpos($m[0], '$') + 1, strpos($m[0], '}') - strpos($m[0], '$') - 1));
                    return "<?php echo $var; ?>";
                },
                $content
            );
        }

        return $content;
    }

    private function parseVariablePath($base, $fullPath)
    {
        $var = '$' . $base;
        preg_match_all("/(?:\\.([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*))|(?:\\['([^']+)'\\])/", $fullPath, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
            $key = $match[1] !== '' ? $match[1] : $match[2];
            // 修复：多段链式访问（如 $a.b.c）。逐段生成安全的 null 兜底表达式，
            // 避免此前 `??` 优先级问题导致只返回首段、后续键被忽略的错误行为
            $var = '(is_array(' . $var . ') ? (' . $var . '[' . var_export($key, true) . '] ?? null) : (is_object(' . $var . ') ? (' . $var . '->' . $key . ' ?? null) : null))';
        }
        return $var;
    }

    private function compileYield($content)
    {
        return preg_replace('/@yield\s*\([\'"]([^\'"]+)[\'"]\)/', '<?php echo $__yield_$1 ?? ""; ?>', $content);
    }

    private function compileRawPhp($content)
    {
        // 只替换模板语法中的 @，不替换 CSS/JS 中的 @
        // 但因为我们已经在 compile 中保护了 CSS/JS，这里的替换是安全的
        $content = preg_replace('/@([a-zA-Z_]+)/', '<?php echo \'@$1\'; ?>', $content);
        return $content;
    }

    /**
     * HTML 压缩（优化版）
     */
    private function minifyHtml($html)
    {
        $preserveTags = self::$config['preserve_tags'];
        $placeholders = [];

        // 保护指定标签的内容
        foreach ($preserveTags as $tag) {
            $html = preg_replace_callback(
                "/<($tag)([^>]*)>(.*?)<\/\\1>/is",
                function ($m) use (&$placeholders) {
                    $key = '%%PLACEHOLDER_' . count($placeholders) . '%%';
                    $placeholders[$key] = $m[0];
                    return $key;
                },
                $html
            );
        }

        // 保护内联 CSS/JS（style 属性、on* 事件属性）
        $html = preg_replace_callback(
            '/(style|on[a-z]+)\s*=\s*(["\\\'])(.*?)\\2/s',
            function ($m) use (&$placeholders) {
                $key = '%%PLACEHOLDER_' . count($placeholders) . '%%';
                $placeholders[$key] = $m[0];
                return $key;
            },
            $html
        );

        // 压缩常规 HTML
        $search = [
            '/\>[^\S ]+/s',     // 标签 > 后的空白
            '/[^\S ]+\</s',     // 标签 < 前的空白
            '/(\s)+/s',         // 多个空格合并为一个
            '/<!--(.|\s)*?-->/' // 删除 HTML 注释
        ];
        $replace = ['>', '<', '\\1', ''];
        $html = preg_replace($search, $replace, $html);

        // 恢复保护的内容
        foreach ($placeholders as $key => $value) {
            $html = str_replace($key, $value, $html);
        }

        return $html;
    }

    private function injectAssetMeta($html)
    {
        $meta = self::$config['asset_meta'];
        if (empty($meta) || !isset($meta['name']) || !isset($meta['content'])) {
            $meta = [
                'name'    => 'generator',
                'content' => 'XiaoPHP V2.1.3',
            ];
        }

        $tag = sprintf(
            '<meta name="%s" content="%s" />',
            htmlspecialchars($meta['name'], ENT_QUOTES, 'UTF-8'),
            htmlspecialchars($meta['content'], ENT_QUOTES, 'UTF-8')
        );

        if (stripos($html, '</head>') !== false) {
            $html = str_ireplace('</head>', $tag . "\n</head>", $html);
        } else {
            if (stripos($html, '<body') !== false) {
                $html = str_ireplace('<body', $tag . "\n<body", $html);
            } else {
                $html = $tag . "\n" . $html;
            }
        }

        return $html;
    }

    /**
     * 静态方法：HTML 转义
     */
    public static function e($string)
    {
        return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
    }

    /**
     * 静态方法：原始输出（不转义）
     */
    public static function raw($string)
    {
        return $string;
    }
}