<?php

use xmvc\Dump;

if (!DEBUG) {
    return R()->code(R_NO)->error('DEBUG模式下才有效');
}
if ($filename == '') {
    return;
}
if (substr($filename, -4) != '.php') {
    $filename .= '.php';
}
if ($filename == '' || !is_file($filename)) {
    return;
}
$contents = file_get_contents($filename);
$contents = str_replace("\r\n", "\n", $contents);
$codes = explode("\n", $contents);
$count = count($codes);
$line *= 1;
$begin = ($begin != 0) ? $line - $begin : 0;
$end   = ($end != 0) ? $line + $end : $count - 1;
$begin = ($begin < 0) ? 0 : $begin;
$end   = ($end > $count - 1) ? $count - 1 : $end;

if (empty($end)) {
    $end = $count - 1;
}
$phpStart = false; //找 <?php
$code_string = '';
for ($i = $begin * 1; $i <= $end; $i++) {
    $lstr = htmlspecialchars($codes[$i]);
    if (!$phpStart && strpos(trim($lstr), '<?php') !== false) {
        $lstr = str_replace('<?php', '&lt;?php', $lstr);
        $phpStart = true;
    }
    $lstr = strtr($lstr, [
        "\t" => '    ', //制作表转4个空格
        "&#039;" => "'", //还原单引号
    ]);
    $lstr = str_pad((string)($i + 1), 7, ' ', STR_PAD_LEFT) . '    ' . $lstr;
    if ($i == $line - 20) {
        $lstr = "<goto>" . $lstr . "</goto>"; //锚点行
    } elseif ($i == $line - 1) {
        $lstr = "<active>" . $lstr . "</active>"; //高亮行
    }
    if ($code_string != '') {
        $code_string .= "\r\n";
    }
    $code_string .= $lstr;
}
$code_string = ltrim($code_string, "\r\n");
$code_string = Dump::phpCodeColor($code_string);

$fileInfo = "<div style='background:#007ACC;color:#fff;padding-left:1em'><span style='font-size:.8em;font-weight:bold;color:#FFFF61'>文件:</span> " . relDir($filename) . " 行: " . $line . "</div>";
$code_string = "\r\n<pre class='phpcode'>\r\n" . $fileInfo . $code_string . "\r\n</pre>\r\n";
if (!$return) {
    echo "<html><head><title>" . $filename . "</title><style>
            pre.phpcode{
                white-space: pre;
                font-family: Consolas, monaco, Menlo, Courier, monospace;
                font-size:17px;
                line-height:22px;
                background:#fefefe;
                color:#222;
                font-weight:200px;
            }
            </style></head><body>" . $code_string . '</body></html>';
}
