<?php
require_once 'config.php';
requireEncryptPermission();

$user = getEncryptUser();
$result = '';
$error = '';
$uploaded_filename = '';
$batch_result = [];

// 支持的语言列表
$supported_langs = [
    'php' => ['name' => 'PHP', 'ext' => 'php', 'icon' => '🐘', 'desc' => '适合PHP网站源码加密'],
    'python' => ['name' => 'Python', 'ext' => 'py', 'icon' => '🐍', 'desc' => '适合Python脚本/项目加密'],
    'javascript' => ['name' => 'JavaScript', 'ext' => 'js', 'icon' => '📜', 'desc' => '适合Node.js/前端代码混淆'],
    'lua' => ['name' => 'Lua', 'ext' => 'lua', 'icon' => '🔷', 'desc' => '适合Lua脚本加密'],
    'ruby' => ['name' => 'Ruby', 'ext' => 'rb', 'icon' => '💎', 'desc' => '适合Ruby脚本加密'],
];

$current_lang = isset($_POST['lang']) ? $_POST['lang'] : (isset($_GET['lang']) ? $_GET['lang'] : 'php');
if (!isset($supported_langs[$current_lang])) {
    $current_lang = 'php';
}

// 确保临时目录存在
$temp_dir = __DIR__ . '/temp/';
if (!is_dir($temp_dir)) {
    mkdir($temp_dir, 0755, true);
}

// 清理旧的临时文件（超过1小时）
foreach (glob($temp_dir . '*.zip') as $file) {
    if (filemtime($file) < time() - 3600) {
        unlink($file);
    }
}
foreach (glob($temp_dir . '*.php') as $file) {
    if (filemtime($file) < time() - 3600) {
        unlink($file);
    }
}
foreach (glob($temp_dir . '*.py') as $file) {
    if (filemtime($file) < time() - 3600) {
        unlink($file);
    }
}
foreach (glob($temp_dir . '*.js') as $file) {
    if (filemtime($file) < time() - 3600) {
        unlink($file);
    }
}
foreach (glob($temp_dir . '*.lua') as $file) {
    if (filemtime($file) < time() - 3600) {
        unlink($file);
    }
}
foreach (glob($temp_dir . '*.rb') as $file) {
    if (filemtime($file) < time() - 3600) {
        unlink($file);
    }
}

// ==================== PHP 加密引擎（原有功能，保持不变）====================
function simpleXor($data, $key) {
    $result = '';
    for ($i = 0; $i < strlen($data); $i++) {
        $result .= chr(ord($data[$i]) ^ ord($key[$i % strlen($key)]));
    }
    return strrev(base64_encode($result));
}

// 增强版加密函数（带域名绑定）
function encryptPHPCode($code, $level = 'high', $bind_domain = '', $bind_type = 'exact') {
    // 1. 移除PHP标签
    $code = preg_replace('/^<\?php/', '', $code);
    $code = trim($code);
    $code = preg_replace('/\?>$/', '', $code);
    $code = trim($code);
    
    // 2. 移除注释
    $code = preg_replace('/\/\/.*$/m', '', $code);
    $code = preg_replace('/\/\*.*?\*\//s', '', $code);
    $code = preg_replace('/#.*$/m', '', $code);
    
    // 3. 字符串保护
    $strings = [];
    $code = preg_replace_callback('/"([^"\\\\]*(\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(\\\\.[^\'\\\\]*)*)\'/', function($matches) use (&$strings) {
        $key = '__STR_' . md5($matches[0]) . '__';
        $strings[$key] = $matches[0];
        return $key;
    }, $code);
    
    // 4. 压缩代码
    if ($level === 'high') {
        $code = preg_replace('/\s+/', ' ', $code);
        $code = preg_replace('/\s*([{};=+\-*\/&|!<>.,?:])\s*/', '$1', $code);
        $code = preg_replace('/;\s*;/', ';', $code);
        $code = preg_replace('/\)\s*{/', '){', $code);
        $code = preg_replace('/}\s*else/', '}else', $code);
        $code = preg_replace('/}\s*elseif/', '}elseif', $code);
    } else {
        $code = preg_replace('/\s+/', ' ', $code);
    }
    
    // 5. 变量混淆
    $varMap = [];
    $varCounter = 0;
    $reservedVars = ['$_GET', '$_POST', '$_SESSION', '$_SERVER', '$GLOBALS', '$this', '$_COOKIE', '$_FILES', '$_REQUEST', '$argv', '$argc'];
    $shortNames = ['$a', '$b', '$c', '$d', '$e', '$f', '$g', '$h', '$i', '$j', '$k', '$l', '$m', '$n', '$o', '$p', '$q', '$r', '$s', '$t', '$u', '$v', '$w', '$x', '$y', '$z'];
    
    $code = preg_replace_callback('/\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', function($matches) use (&$varMap, &$varCounter, $reservedVars, $shortNames) {
        $var = $matches[0];
        if (in_array($var, $reservedVars) || strpos($var, '$__') === 0) {
            return $var;
        }
        if (!isset($varMap[$var])) {
            if ($varCounter < count($shortNames)) {
                $varMap[$var] = $shortNames[$varCounter++];
            } else {
                $varMap[$var] = '$v' . substr(md5($varCounter++), 0, 6);
            }
        }
        return $varMap[$var];
    }, $code);
    
    // 6. 函数名混淆
    $funcMap = [];
    $funcCounter = 0;
    $reservedFunctions = ['array', 'count', 'isset', 'empty', 'unset', 'defined', 'define', 'include', 'require', 'include_once', 'require_once', 'echo', 'print', 'die', 'exit', 'return', 'function', 'if', 'else', 'elseif', 'for', 'foreach', 'while', 'switch', 'case', 'break', 'continue', 'default', 'class', 'new', 'extends', 'implements', 'public', 'private', 'protected', 'static', 'const', 'var'];
    
    $code = preg_replace_callback('/function\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/', function($matches) use (&$funcMap, &$funcCounter, $reservedFunctions) {
        $funcName = $matches[1];
        if (!in_array($funcName, $reservedFunctions) && !isset($funcMap[$funcName])) {
            $funcMap[$funcName] = '_f' . substr(md5($funcCounter++), 0, 6);
        }
        return 'function ' . ($funcMap[$funcName] ?? $funcName) . '(';
    }, $code);
    
    $code = preg_replace_callback('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\(/', function($matches) use ($funcMap, $reservedFunctions) {
        $funcName = $matches[1];
        if (!in_array($funcName, $reservedFunctions) && isset($funcMap[$funcName])) {
            return $funcMap[$funcName] . '(';
        }
        return $matches[0];
    }, $code);
    
    // 7. 恢复字符串
    foreach ($strings as $key => $value) {
        $code = str_replace($key, $value, $code);
    }
    
    // 8. 添加随机垃圾代码
    if ($level === 'high') {
        $garbageFunctions = [
            'if(1==2){$a=1;}',
            '$_t=time();$_r=rand(1,100);',
            '$__x = "nothing";',
            '1==2 ? $a=1 : $a=2;',
            'for($i=0;$i<0;$i++){}',
        ];
        $garbage = '';
        $count = rand(1, 3);
        for ($i = 0; $i < $count; $i++) {
            $garbage .= $garbageFunctions[array_rand($garbageFunctions)] . "\n";
        }
        $code = $garbage . $code;
    }
    
    // 9. Base64编码
    $encoded = base64_encode($code);
    
    // 10. 生成加密代码
    $encryptKey = substr(md5(date('Ymd') . 'salt'), 0, 8);
    $encoded_xor = simpleXor($encoded, $encryptKey);
    
    // 域名验证代码
    $domain_check = '';
    if (!empty($bind_domain)) {
        if ($bind_type === 'wildcard') {
            // 泛域名匹配
            $pattern = str_replace('.', '\.', $bind_domain);
            $pattern = str_replace('*', '.*', $pattern);
            $domain_check = '
// 域名验证
$__host = $_SERVER["HTTP_HOST"] ?? "";
$__host = preg_replace("/:\d+$/", "", $__host);
if (!preg_match("/^' . $pattern . '$/i", $__host)) {
    die("<h2>授权无效</h2><p>此加密文件仅授权在 ' . htmlspecialchars($bind_domain) . ' 域名下运行。</p>");
}
';
        } else {
            // 精确匹配
            $domain_check = '
// 域名验证
$__host = $_SERVER["HTTP_HOST"] ?? "";
$__host = preg_replace("/:\d+$/", "", $__host);
if (strtolower($__host) !== strtolower("' . $bind_domain . '")) {
    die("<h2>授权无效</h2><p>此加密文件仅授权在 ' . htmlspecialchars($bind_domain) . ' 域名下运行。</p>");
}
';
        }
    }
    
    $encrypted = '<?php
/*
 * 加密时间: ' . date('Y-m-d H:i:s') . '
 * 加密用户: ' . ($_SESSION['encrypt_username'] ?? 'unknown') . '
 * 绑定域名: ' . ($bind_domain ?: '无限制') . '
 */
' . $domain_check . '
$__k = "' . $encryptKey . '";
$__d = "' . $encoded_xor . '";
$__d = str_rot13(strrev($__d));
for($__i=0;$__i<strlen($__d);$__i++){ $__d[$__i] = chr(ord($__d[$__i]) ^ ord($__k[$__i%strlen($__k)])); }
$__d = base64_decode($__d);
if ($__d === false) die("加密文件损坏");
eval($__d);
?>';
    return $encrypted;
}

// ==================== Python 加密引擎 ====================
function encryptPythonCode($code, $level = 'high') {
    // 1. 移除注释
    $code = preg_replace('/#.*$/m', '', $code);
    $code = preg_replace('/\'\'\'[\s\S]*?\'\'\'/', '', $code);
    $code = preg_replace('/\"\"\"[\s\S]*?\"\"\"/', '', $code);
    
    // 2. 移除空行
    $code = preg_replace("/\n\s*\n/", "\n", $code);
    
    // 3. 变量混淆
    $varMap = [];
    $varCounter = 0;
    $shortNames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $reservedVars = ['self', 'cls', 'args', 'kwargs', '__init__', '__main__'];
    
    $code = preg_replace_callback('/\b([a-zA-Z_][a-zA-Z0-9_]*)\b(?=\s*=|\s*\()/', function($matches) use (&$varMap, &$varCounter, $shortNames, $reservedVars) {
        $var = $matches[1];
        if (in_array($var, $reservedVars) || strlen($var) <= 2) {
            return $var;
        }
        if (!isset($varMap[$var])) {
            if ($varCounter < count($shortNames)) {
                $varMap[$var] = $shortNames[$varCounter++];
            } else {
                $varMap[$var] = '_v' . substr(md5($varCounter++), 0, 4);
            }
        }
        return $varMap[$var];
    }, $code);
    
    // 4. 替换变量引用
    foreach ($varMap as $old => $new) {
        $code = preg_replace('/\b' . preg_quote($old, '/') . '\b/', $new, $code);
    }
    
    // 5. 字符串编码
    $strings = [];
    $code = preg_replace_callback('/"([^"\\\\]*(\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(\\\\.[^\'\\\\]*)*)\'/', function($matches) use (&$strings) {
        $key = '__STR_' . md5($matches[0]) . '__';
        $encoded_str = base64_encode($matches[0]);
        $strings[$key] = "base64.b64decode('$encoded_str').decode('utf-8')";
        return $key;
    }, $code);
    
    // 6. 恢复字符串
    foreach ($strings as $key => $value) {
        $code = str_replace($key, $value, $code);
    }
    
    // 7. 压缩代码
    if ($level === 'high') {
        $code = preg_replace('/\s+/', ' ', $code);
        $code = preg_replace('/\s*([=+\-*\/%&|<>!])\s*/', '$1', $code);
    }
    
    // 8. 生成加密代码
    $encoded = base64_encode($code);
    $key = substr(md5(date('Ymd')), 0, 8);
    $encrypted = base64_encode($encoded);
    
    $encrypted_code = 'import base64
import marshal
import types

def __decrypt():
    __k = "' . $key . '"
    __d = "' . $encrypted . '"
    __d = base64.b64decode(__d).decode()
    __d = __d[::-1]
    __r = ""
    for i in range(len(__d)):
        __r += chr(ord(__d[i]) ^ ord(__k[i % len(__k)]))
    __c = base64.b64decode(__r)
    exec(compile(__c, "<encrypted>", "exec"))

__decrypt()
';
    return $encrypted_code;
}

// ==================== JavaScript 加密引擎 ====================
function encryptJSCode($code, $level = 'high') {
    // 1. 移除注释
    $code = preg_replace('/\/\/.*$/m', '', $code);
    $code = preg_replace('/\/\*[\s\S]*?\*\//', '', $code);
    
    // 2. 变量混淆
    $varMap = [];
    $varCounter = 0;
    $shortNames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $reservedVars = ['window', 'document', 'console', 'Math', 'Object', 'Array', 'String', 'Number', 'Boolean', 'Function', 'undefined', 'null', 'this', 'arguments'];
    
    $code = preg_replace_callback('/\b(var|let|const)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/', function($matches) use (&$varMap, &$varCounter, $shortNames, $reservedVars) {
        $var = $matches[2];
        if (in_array($var, $reservedVars)) {
            return $matches[0];
        }
        if (!isset($varMap[$var])) {
            if ($varCounter < count($shortNames)) {
                $varMap[$var] = $shortNames[$varCounter++];
            } else {
                $varMap[$var] = '_' . substr(md5($varCounter++), 0, 4);
            }
        }
        return $matches[1] . ' ' . $varMap[$var];
    }, $code);
    
    // 3. 替换变量引用
    foreach ($varMap as $old => $new) {
        $code = preg_replace('/\b' . preg_quote($old, '/') . '\b(?![a-zA-Z0-9_$])/', $new, $code);
    }
    
    // 4. 字符串编码
    $strings = [];
    $code = preg_replace_callback('/"([^"\\\\]*(\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(\\\\.[^\'\\\\]*)*)\'/', function($matches) use (&$strings) {
        $key = '__STR_' . md5($matches[0]) . '__';
        $encoded_str = base64_encode($matches[0]);
        $strings[$key] = "atob('$encoded_str')";
        return $key;
    }, $code);
    
    // 5. 恢复字符串
    foreach ($strings as $key => $value) {
        $code = str_replace($key, $value, $code);
    }
    
    // 6. 压缩代码
    if ($level === 'high') {
        $code = preg_replace('/\s+/', ' ', $code);
        $code = preg_replace('/\s*([=+\-*\/%&|<>!;{}:?,.])\s*/', '$1', $code);
    }
    
    // 7. 生成加密代码
    $key = substr(md5(date('Ymd')), 0, 8);
    $encoded = base64_encode($code);
    $encrypted = base64_encode($encoded);
    
    $encrypted_code = '(function(){
    var __k = "' . $key . '";
    var __d = "' . $encrypted . '";
    __d = atob(__d);
    __d = __d.split("").reverse().join("");
    var __r = "";
    for(var i=0;i<__d.length;i++){
        __r += String.fromCharCode(__d.charCodeAt(i) ^ __k.charCodeAt(i%__k.length));
    }
    eval(atob(__r));
})();
';
    return $encrypted_code;
}

// ==================== Lua 加密引擎 ====================
function encryptLuaCode($code, $level = 'high') {
    // 1. 移除注释
    $code = preg_replace('/--.*$/m', '', $code);
    $code = preg_replace('/--\[\[[\s\S]*?\]\]/', '', $code);
    
    // 2. 移除空行
    $code = preg_replace("/\n\s*\n/", "\n", $code);
    
    // 3. 变量混淆
    $varMap = [];
    $varCounter = 0;
    $shortNames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $reservedVars = ['self', '_G', '_VERSION', 'arg', 'print', 'require', 'pairs', 'ipairs', 'table', 'string', 'math', 'io', 'os'];
    
    $code = preg_replace_callback('/\b(local\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\b(?=\s*=|\s*function\s*\()/', function($matches) use (&$varMap, &$varCounter, $shortNames, $reservedVars) {
        $var = $matches[2];
        if (in_array($var, $reservedVars) || strlen($var) <= 2) {
            return $matches[0];
        }
        if (!isset($varMap[$var])) {
            if ($varCounter < count($shortNames)) {
                $varMap[$var] = $shortNames[$varCounter++];
            } else {
                $varMap[$var] = '_' . substr(md5($varCounter++), 0, 4);
            }
        }
        return (isset($matches[1]) ? $matches[1] : '') . $varMap[$var];
    }, $code);
    
    // 4. 替换变量引用
    foreach ($varMap as $old => $new) {
        $code = preg_replace('/\b' . preg_quote($old, '/') . '\b(?!\w)/', $new, $code);
    }
    
    // 5. 字符串编码
    $strings = [];
    $code = preg_replace_callback('/"([^"\\\\]*(\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(\\\\.[^\'\\\\]*)*)\'/', function($matches) use (&$strings) {
        $key = '__STR_' . md5($matches[0]) . '__';
        $encoded_str = base64_encode($matches[0]);
        $strings[$key] = "(function() return (loadstring or load)((function(s) local r='' for i=1,#s do r=r..string.char(string.byte(s,i)-1) end return r end)((loadstring or load)('return ...')(string.char(('" . $encoded_str . "'):gsub('..',function(c) return string.char(tonumber(c,16)+1) end)))) end)()";
        return $key;
    }, $code);
    
    // 8. 生成加密代码
    $key = substr(md5(date('Ymd')), 0, 8);
    $encoded = base64_encode($code);
    $encrypted = base64_encode($encoded);
    
    // 使用 Heredoc 语法，避免引号冲突
    $encrypted_code = <<<LUA
local __k="{$key}"
local __d="{$encrypted}"
local function __b64d(s)
    local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    s=s:gsub("[^"..b.."=]", "")
    return (s:gsub(".", function(x)
        if x=="=" then return "" end
        local r,f="",(b:find(x)-1)
        for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and "1" or "0") end
        return r;
    end):gsub("%d%d%d?%d?%d?%d?%d?%d?", function(x)
        if #x<8 then return "" end
        local c=0
        for i=1,8 do c=c*2+tonumber(x:sub(i,i)) end
        return string.char(c)
    end))
end
local function __xor(s,k)
    local r=""
    for i=1,#s do
        r=r..string.char(string.byte(s,i)~ string.byte(k,(i-1)%#k+1))
    end
    return r
end
__d=__b64d(__d)
__d=string.reverse(__d)
__d=__xor(__d,__k)
__d=__b64d(__d)
local __f=loadstring or load
__f(__d)()
LUA;
    return $encrypted_code;
}
// ==================== Ruby 加密引擎 ====================
function encryptRubyCode($code, $level = 'high') {
    // 1. 移除注释
    $code = preg_replace('/#.*$/m', '', $code);
    $code = preg_replace('/^=begin[\s\S]*?^=end/m', '', $code);
    
    // 2. 移除空行
    $code = preg_replace("/\n\s*\n/", "\n", $code);
    
    // 3. 变量混淆
    $varMap = [];
    $varCounter = 0;
    $shortNames = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $reservedVars = ['self', 'true', 'false', 'nil', '__FILE__', '__LINE__', 'ENV', 'ARGV', 'STDOUT', 'STDIN', 'STDERR'];
    
    $code = preg_replace_callback('/@?@@?\$?([a-zA-Z_][a-zA-Z0-9_]*)\b(?=\s*=|\s*def\s+)/', function($matches) use (&$varMap, &$varCounter, $shortNames, $reservedVars) {
        $var = $matches[1];
        if (in_array($var, $reservedVars) || strlen($var) <= 2) {
            return $matches[0];
        }
        if (!isset($varMap[$var])) {
            if ($varCounter < count($shortNames)) {
                $varMap[$var] = $shortNames[$varCounter++];
            } else {
                $varMap[$var] = '_' . substr(md5($varCounter++), 0, 4);
            }
        }
        return str_replace($var, $varMap[$var], $matches[0]);
    }, $code);
    
    // 4. 替换变量引用
    foreach ($varMap as $old => $new) {
        $code = preg_replace('/\b' . preg_quote($old, '/') . '\b/', $new, $code);
    }
    
    // 5. 字符串编码
    $strings = [];
    $code = preg_replace_callback('/"([^"\\\\]*(\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(\\\\.[^\'\\\\]*)*)\'/', function($matches) use (&$strings) {
        $key = '__STR_' . md5($matches[0]) . '__';
        $encoded_str = base64_encode($matches[0]);
        $strings[$key] = "Base64.decode64('$encoded_str')";
        return $key;
    }, $code);
    
    // 6. 恢复字符串
    foreach ($strings as $key => $value) {
        $code = str_replace($key, $value, $code);
    }
    
    // 7. 压缩代码
    if ($level === 'high') {
        $code = preg_replace('/\s+/', ' ', $code);
        $code = preg_replace('/\s*([=+\-*\/%&|<>])\s*/', '$1', $code);
    }
    
    // 8. 生成加密代码
    $key = substr(md5(date('Ymd')), 0, 8);
    $encoded = base64_encode($code);
    $encrypted = base64_encode($encoded);
    
    $encrypted_code = 'require "base64"
__k = "' . $key . '"
__d = "' . $encrypted . '"
__d = Base64.decode64(__d)
__d = __d.reverse
__r = ""
__d.each_char.with_index do |c,i|
    __r << (c.ord ^ __k[i % __k.length].ord).chr
end
__c = Base64.decode64(__r)
eval(__c)
';
    return $encrypted_code;
}

// 根据语言类型调用对应的加密函数
function encryptCode($code, $lang, $level = 'high', $bind_domain = '', $bind_type = 'exact') {
    switch ($lang) {
        case 'python':
            return encryptPythonCode($code, $level);
        case 'javascript':
            return encryptJSCode($code, $level);
        case 'lua':
            return encryptLuaCode($code, $level);
        case 'ruby':
            return encryptRubyCode($code, $level);
        case 'php':
        default:
            return encryptPHPCode($code, $level, $bind_domain, $bind_type);
    }
}

// 获取文件扩展名
function getFileExtension($lang) {
    switch ($lang) {
        case 'python': return 'py';
        case 'javascript': return 'js';
        case 'lua': return 'lua';
        case 'ruby': return 'rb';
        case 'php':
        default: return 'php';
    }
}

// ==================== 处理批量加密 ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['code_files'])) {
    $files = $_FILES['code_files'];
    $encrypt_level = $_POST['encrypt_level'] ?? 'high';
    $bind_domain = trim($_POST['bind_domain'] ?? '');
    $bind_type = $_POST['bind_type'] ?? 'exact';
    $lang = $_POST['lang'] ?? 'php';
    $success_files = [];
    $fail_files = [];
    
    $allowed_exts = [
        'php' => ['php'],
        'python' => ['py', 'pyw'],
        'javascript' => ['js', 'mjs', 'cjs'],
        'lua' => ['lua'],
        'ruby' => ['rb', 'rbw'],
    ];
    $allowed = $allowed_exts[$lang] ?? ['php'];
    
    for ($i = 0; $i < count($files['name']); $i++) {
        if ($files['error'][$i] !== UPLOAD_ERR_OK) {
            $fail_files[] = $files['name'][$i] . ' (上传失败)';
            continue;
        }
        
        $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) {
            $fail_files[] = $files['name'][$i] . ' (不支持的文件类型，需要 ' . implode('/', $allowed) . ')';
            continue;
        }
        if ($files['size'][$i] > 5 * 1024 * 1024) {
            $fail_files[] = $files['name'][$i] . ' (超过5MB限制)';
            continue;
        }
        
        $content = file_get_contents($files['tmp_name'][$i]);
        $original_name = $files['name'][$i];
        $original_size = $files['size'][$i];
        
        try {
            $encrypted = encryptCode($content, $lang, $encrypt_level, $bind_domain, $bind_type);
            $encrypted_size = strlen($encrypted);
            
            // 保存加密文件
            $file_ext = getFileExtension($lang);
            $encrypted_name = pathinfo($original_name, PATHINFO_FILENAME) . '_encrypted.' . $file_ext;
            $encrypted_path = $temp_dir . $encrypted_name;
            file_put_contents($encrypted_path, $encrypted);
            
            $success_files[] = [
                'original' => $original_name,
                'encrypted' => $encrypted_name,
                'size' => $original_size,
                'encrypted_size' => $encrypted_size,
                'path' => $encrypted_path
            ];
            
            // 记录历史（增加语言字段）
            $db->query("INSERT INTO encrypt_history (user_id, original_name, file_size, encrypted_size, bind_domain, bind_type, language) VALUES ({$user['id']}, '" . addslashes($original_name) . "', $original_size, $encrypted_size, '" . addslashes($bind_domain) . "', '$bind_type', '$lang')");
            
        } catch (Exception $e) {
            $fail_files[] = $original_name . ' (加密失败)';
        }
    }
    
    if (!empty($success_files)) {
        // 创建 ZIP 压缩包
        $zip = new ZipArchive();
        $zip_filename = 'encrypted_files_' . date('YmdHis') . '.zip';
        $zip_path = $temp_dir . $zip_filename;
        
        if ($zip->open($zip_path, ZipArchive::CREATE) === TRUE) {
            foreach ($success_files as $file) {
                $zip->addFile($file['path'], $file['encrypted']);
            }
            $zip->close();
            
            // 设置下载头
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . $zip_filename . '"');
            header('Content-Length: ' . filesize($zip_path));
            readfile($zip_path);
            
            // 清理临时文件
            foreach ($success_files as $file) {
                @unlink($file['path']);
            }
            @unlink($zip_path);
            exit;
        } else {
            $error = '创建压缩包失败';
        }
    } else {
        $error = '没有成功加密任何文件';
    }
}

// ==================== 处理单文件加密 ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['code_file']) && !isset($_FILES['code_files'])) {
    $file = $_FILES['code_file'];
    $lang = $_POST['lang'] ?? 'php';
    
    $allowed_exts = [
        'php' => ['php'],
        'python' => ['py', 'pyw'],
        'javascript' => ['js', 'mjs', 'cjs'],
        'lua' => ['lua'],
        'ruby' => ['rb', 'rbw'],
    ];
    $allowed = $allowed_exts[$lang] ?? ['php'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error = '文件上传失败';
    } elseif (!in_array($ext, $allowed)) {
        $error = '不支持的文件类型，需要 ' . implode('/', $allowed);
    } elseif ($file['size'] > 5 * 1024 * 1024) {
        $error = '文件大小不能超过 5MB';
    } else {
        $content = file_get_contents($file['tmp_name']);
        $original_size = $file['size'];
        $uploaded_filename = htmlspecialchars($file['name']);
        $encrypt_level = $_POST['encrypt_level'] ?? 'high';
        $bind_domain = trim($_POST['bind_domain'] ?? '');
        $bind_type = $_POST['bind_type'] ?? 'exact';
        
        $encrypted = encryptCode($content, $lang, $encrypt_level, $bind_domain, $bind_type);
        $encrypted_size = strlen($encrypted);
        
        $db->query("INSERT INTO encrypt_history (user_id, original_name, file_size, encrypted_size, bind_domain, bind_type, language) VALUES ({$user['id']}, '{$file['name']}', $original_size, $encrypted_size, '" . addslashes($bind_domain) . "', '$bind_type', '$lang')");
        
        $result = $encrypted;
    }
}
?>
<?php include 'header.php'; ?>
<div class="encrypt-container">
    <div class="upload-card" style="background: var(--bg-primary); border-radius: 20px; padding: 30px; border: 1px solid var(--border-color);">
        <h2>🔐 多语言代码加密工具</h2>
        <p>支持 PHP、Python、JavaScript、Lua、Ruby 代码加密保护</p>
        
        <!-- 语言选择器 -->
        <div style="display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; border-bottom: 1px solid var(--border-color); padding-bottom: 15px;">
            <?php foreach ($supported_langs as $lang_key => $lang_info): ?>
            <button type="button" class="lang-btn <?php echo $current_lang === $lang_key ? 'active' : ''; ?>" data-lang="<?php echo $lang_key; ?>" style="padding: 10px 20px; border-radius: 10px; border: 1px solid var(--border-color); cursor: pointer; background: <?php echo $current_lang === $lang_key ? 'linear-gradient(135deg, #667eea, #764ba2)' : 'var(--bg-secondary)'; ?>; color: <?php echo $current_lang === $lang_key ? 'white' : 'var(--text-primary)'; ?>;">
                <span style="font-size: 18px;"><?php echo $lang_info['icon']; ?></span>
                <?php echo $lang_info['name']; ?>
            </button>
            <?php endforeach; ?>
        </div>
        
        <!-- 当前语言提示 -->
        <div style="background: rgba(102,126,234,0.1); border-radius: 10px; padding: 10px 15px; margin-bottom: 20px;">
            <span>📌 当前语言：<strong><?php echo $supported_langs[$current_lang]['name']; ?></strong> - <?php echo $supported_langs[$current_lang]['desc']; ?></span>
        </div>
        
        <!-- 模式切换 -->
        <div style="display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px;">
            <button type="button" id="singleModeBtn" class="mode-btn active" style="padding: 8px 20px; border-radius: 8px; border: none; cursor: pointer; background: var(--primary-color); color: white;">单文件加密</button>
            <button type="button" id="batchModeBtn" class="mode-btn" style="padding: 8px 20px; border-radius: 8px; border: 1px solid var(--border-color); cursor: pointer; background: var(--bg-secondary);">批量加密</button>
        </div>
        
        <?php if ($error): ?>
            <div class="alert alert-error" style="background: rgba(220,53,69,0.1); border: 1px solid #dc3545; border-radius: 12px; padding: 15px; margin: 15px 0; color: #dc3545;">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>
        
        <!-- 单文件加密模式 -->
        <div id="singleMode" style="display: block;">
            <?php if ($result): ?>
                <div class="result-card" style="margin-top: 20px;">
                    <h3>✅ 加密成功</h3>
                    <div style="background: rgba(40,167,69,0.1); border: 1px solid #28a745; border-radius: 12px; padding: 15px; margin: 15px 0;">
                        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                            <span style="font-size: 24px;">📄</span>
                            <div>
                                <strong style="color: #28a745;">原始文件：</strong>
                                <span style="font-family: monospace; font-size: 14px;"><?php echo $uploaded_filename; ?></span>
                            </div>
                        </div>
                    </div>
                    <div style="display: flex; gap: 10px; margin-bottom: 15px; flex-wrap: wrap;">
                        <button class="btn-copy" onclick="copyToClipboard()" style="background: var(--primary-color); color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer;">📋 复制代码</button>
                        <button class="btn-download" onclick="downloadFile()" style="background: #28a745; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer;">💾 下载文件</button>
                    </div>
                    <textarea id="encryptedCodeRaw" style="display: none;"><?php echo htmlspecialchars($result); ?></textarea>
                    <pre id="encryptedCodeDisplay" style="background: var(--bg-secondary); padding: 15px; border-radius: 12px; overflow-x: auto; font-size: 12px; max-height: 400px; overflow-y: auto;"><?php echo htmlspecialchars($result); ?></pre>
                </div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data" id="singleUploadForm" style="margin-top: 20px;">
                <input type="hidden" name="lang" value="<?php echo $current_lang; ?>">
                <div class="upload-area" id="uploadArea" style="border: 2px dashed var(--border-color); border-radius: 16px; padding: 40px; text-align: center; cursor: pointer; transition: all 0.3s;">
                    <div style="font-size: 48px;"><?php echo $supported_langs[$current_lang]['icon']; ?></div>
                    <p>点击或拖拽上传 <?php echo $supported_langs[$current_lang]['name']; ?> 文件</p>
                    <p style="font-size: 12px; color: var(--text-secondary);">支持 .<?php echo implode(', .', array_map(function($ext) use ($current_lang) {
                        $exts = ['php' => ['php'], 'python' => ['py', 'pyw'], 'javascript' => ['js', 'mjs', 'cjs'], 'lua' => ['lua'], 'ruby' => ['rb', 'rbw']];
                        return implode(', .', $exts[$current_lang]);
                    }, [$current_lang])); ?> 文件，最大 5MB</p>
                    <div id="selectedFile" style="margin-top: 10px; font-size: 13px; color: var(--primary-color); display: none;"></div>
                </div>
                <input type="file" name="code_file" id="fileInput" style="display: none;">
                
                <div style="margin-top: 20px;">
                    <label style="margin-right: 20px;">
                        <input type="radio" name="encrypt_level" value="low" checked> 普通加密
                    </label>
                    <label>
                        <input type="radio" name="encrypt_level" value="high"> 高强度加密（推荐）
                    </label>
                </div>
                
                <!-- 域名绑定选项（仅PHP支持） -->
                <?php if ($current_lang === 'php'): ?>
                <div style="margin-top: 20px; padding: 15px; background: var(--bg-secondary); border-radius: 12px;">
                    <h4 style="margin-bottom: 10px;">🔗 域名绑定（可选）</h4>
                    <div class="form-group" style="margin-bottom: 10px;">
                        <input type="text" name="bind_domain" id="bind_domain" placeholder="例如：example.com 或 *.example.com" style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid var(--border-color);">
                        <small style="color: var(--text-muted);">留空则不限制域名。支持泛域名，如 *.example.com 匹配所有子域名</small>
                    </div>
                    <div>
                        <label style="margin-right: 20px;">
                            <input type="radio" name="bind_type" value="exact" checked> 精确匹配（仅限该域名）
                        </label>
                        <label>
                            <input type="radio" name="bind_type" value="wildcard"> 泛域名（匹配所有子域名）
                        </label>
                    </div>
                </div>
                <?php else: ?>
                <div style="margin-top: 20px; padding: 15px; background: var(--bg-secondary); border-radius: 12px; opacity: 0.6;">
                    <h4 style="margin-bottom: 10px;">🔗 域名绑定</h4>
                    <p style="font-size: 13px; color: var(--text-muted);">域名绑定功能仅支持 PHP 语言</p>
                    <input type="hidden" name="bind_domain" value="">
                    <input type="hidden" name="bind_type" value="exact">
                </div>
                <?php endif; ?>
                
                <button type="submit" class="btn btn-primary" style="margin-top: 20px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; padding: 12px 30px; border-radius: 8px; cursor: pointer;">🔒 开始加密</button>
            </form>
        </div>
        
        <!-- 批量加密模式 -->
        <div id="batchMode" style="display: none;">
            <form method="POST" enctype="multipart/form-data" id="batchUploadForm">
                <input type="hidden" name="lang" value="<?php echo $current_lang; ?>">
                <div class="upload-area" id="batchUploadArea" style="border: 2px dashed var(--border-color); border-radius: 16px; padding: 40px; text-align: center; cursor: pointer; transition: all 0.3s;">
                    <div style="font-size: 48px;">📦</div>
                    <p>点击或拖拽上传多个 <?php echo $supported_langs[$current_lang]['name']; ?> 文件</p>
                    <p style="font-size: 12px; color: var(--text-secondary);">支持批量上传，最多 20 个文件，每个最大 5MB</p>
                    <div id="batchSelectedFiles" style="margin-top: 10px; font-size: 13px; color: var(--primary-color); display: none;"></div>
                </div>
                <input type="file" name="code_files[]" id="batchFileInput" accept=".<?php echo implode(',.', array_map(function($ext) use ($current_lang) {
                    $exts = ['php' => ['php'], 'python' => ['py', 'pyw'], 'javascript' => ['js', 'mjs', 'cjs'], 'lua' => ['lua'], 'ruby' => ['rb', 'rbw']];
                    return implode(',.', $exts[$current_lang]);
                }, [$current_lang])); ?>" multiple style="display: none;">
                
                <div style="margin-top: 20px;">
                    <label style="margin-right: 20px;">
                        <input type="radio" name="encrypt_level" value="low" checked> 普通加密
                    </label>
                    <label>
                        <input type="radio" name="encrypt_level" value="high"> 高强度加密（推荐）
                    </label>
                </div>
                
                <!-- 批量加密域名绑定选项（仅PHP支持） -->
                <?php if ($current_lang === 'php'): ?>
                <div style="margin-top: 20px; padding: 15px; background: var(--bg-secondary); border-radius: 12px;">
                    <h4 style="margin-bottom: 10px;">🔗 域名绑定（可选）</h4>
                    <div class="form-group" style="margin-bottom: 10px;">
                        <input type="text" name="bind_domain" id="batch_bind_domain" placeholder="例如：example.com 或 *.example.com" style="width: 100%; padding: 10px; border-radius: 8px; border: 1px solid var(--border-color);">
                        <small style="color: var(--text-muted);">留空则不限制域名。支持泛域名，如 *.example.com 匹配所有子域名</small>
                    </div>
                    <div>
                        <label style="margin-right: 20px;">
                            <input type="radio" name="bind_type" value="exact" checked> 精确匹配（仅限该域名）
                        </label>
                        <label>
                            <input type="radio" name="bind_type" value="wildcard"> 泛域名（匹配所有子域名）
                        </label>
                    </div>
                </div>
                <?php else: ?>
                <div style="margin-top: 20px; padding: 15px; background: var(--bg-secondary); border-radius: 12px; opacity: 0.6;">
                    <h4 style="margin-bottom: 10px;">🔗 域名绑定</h4>
                    <p style="font-size: 13px; color: var(--text-muted);">域名绑定功能仅支持 PHP 语言</p>
                    <input type="hidden" name="bind_domain" value="">
                    <input type="hidden" name="bind_type" value="exact">
                </div>
                <?php endif; ?>
                
                <button type="submit" class="btn btn-primary" id="batchSubmitBtn" style="margin-top: 20px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; padding: 12px 30px; border-radius: 8px; cursor: pointer;">📦 批量加密并下载</button>
            </form>
            
            <div id="batchProgress" style="display: none; margin-top: 20px;">
                <div style="background: var(--bg-secondary); border-radius: 12px; padding: 20px;">
                    <h4>加密进度</h4>
                    <div style="background: #e5e7eb; border-radius: 10px; overflow: hidden; height: 20px; margin: 10px 0;">
                        <div id="progressBar" style="width: 0%; background: linear-gradient(135deg, #667eea, #764ba2); height: 100%; transition: width 0.3s;"></div>
                    </div>
                    <p id="progressText" style="color: var(--text-secondary);">准备中...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.mode-btn {
    transition: all 0.2s;
}
.mode-btn.active {
    background: linear-gradient(135deg, #667eea, #764ba2) !important;
    color: white !important;
    border: none !important;
}
.lang-btn {
    transition: all 0.2s;
}
.lang-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
</style>

<script>
    // 模式切换
    const singleMode = document.getElementById('singleMode');
    const batchMode = document.getElementById('batchMode');
    const singleModeBtn = document.getElementById('singleModeBtn');
    const batchModeBtn = document.getElementById('batchModeBtn');
    
    singleModeBtn.addEventListener('click', () => {
        singleMode.style.display = 'block';
        batchMode.style.display = 'none';
        singleModeBtn.classList.add('active');
        batchModeBtn.classList.remove('active');
        singleModeBtn.style.background = 'var(--primary-color)';
        singleModeBtn.style.color = 'white';
        batchModeBtn.style.background = 'var(--bg-secondary)';
        batchModeBtn.style.color = 'var(--text-primary)';
        batchModeBtn.style.border = '1px solid var(--border-color)';
    });
    
    batchModeBtn.addEventListener('click', () => {
        singleMode.style.display = 'none';
        batchMode.style.display = 'block';
        batchModeBtn.classList.add('active');
        singleModeBtn.classList.remove('active');
        batchModeBtn.style.background = 'var(--primary-color)';
        batchModeBtn.style.color = 'white';
        singleModeBtn.style.background = 'var(--bg-secondary)';
        singleModeBtn.style.color = 'var(--text-primary)';
        singleModeBtn.style.border = '1px solid var(--border-color)';
    });
    
    // 语言切换
    const langBtns = document.querySelectorAll('.lang-btn');
    langBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const lang = btn.dataset.lang;
            const currentUrl = new URL(window.location.href);
            currentUrl.searchParams.set('lang', lang);
            window.location.href = currentUrl.toString();
        });
    });
    
    // 单文件上传
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    const selectedFileDiv = document.getElementById('selectedFile');
    const currentLang = '<?php echo $current_lang; ?>';
    
    const allowedExts = {
        php: ['php'],
        python: ['py', 'pyw'],
        javascript: ['js', 'mjs', 'cjs'],
        lua: ['lua'],
        ruby: ['rb', 'rbw']
    };
    
    function showFileName(file) {
        const ext = file.name.split('.').pop().toLowerCase();
        const allowed = allowedExts[currentLang] || ['php'];
        
        if (file && allowed.includes(ext)) {
            selectedFileDiv.innerHTML = `✅ 已选择：${file.name}`;
            selectedFileDiv.style.display = 'block';
            selectedFileDiv.style.color = '#28a745';
        } else if (file) {
            selectedFileDiv.innerHTML = `❌ 请选择 ${allowed.join('/')} 文件`;
            selectedFileDiv.style.display = 'block';
            selectedFileDiv.style.color = '#dc3545';
        } else {
            selectedFileDiv.style.display = 'none';
        }
    }
    
    if (uploadArea) {
        uploadArea.onclick = () => fileInput.click();
        uploadArea.ondragover = (e) => { 
            e.preventDefault(); 
            uploadArea.style.borderColor = 'var(--primary-color)';
            uploadArea.style.background = 'rgba(102,126,234,0.05)';
        };
        uploadArea.ondragleave = () => { 
            uploadArea.style.borderColor = 'var(--border-color)';
            uploadArea.style.background = 'transparent';
        };
        uploadArea.ondrop = (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = 'var(--border-color)';
            uploadArea.style.background = 'transparent';
            const file = e.dataTransfer.files[0];
            const ext = file.name.split('.').pop().toLowerCase();
            const allowed = allowedExts[currentLang] || ['php'];
            if (file && allowed.includes(ext)) {
                fileInput.files = e.dataTransfer.files;
                showFileName(file);
                document.getElementById('singleUploadForm').submit();
            } else {
                alert(`请上传 ${allowed.join('/')} 文件`);
            }
        };
    }
    
    if (fileInput) {
        fileInput.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                showFileName(file);
            }
        };
    }
    
    // 批量上传
    const batchUploadArea = document.getElementById('batchUploadArea');
    const batchFileInput = document.getElementById('batchFileInput');
    const batchSelectedFiles = document.getElementById('batchSelectedFiles');
    const batchSubmitBtn = document.getElementById('batchSubmitBtn');
    const batchProgress = document.getElementById('batchProgress');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    
    function showBatchFiles(files) {
        if (files.length > 0) {
            let html = `✅ 已选择 ${files.length} 个文件：<br>`;
            for (let i = 0; i < Math.min(files.length, 5); i++) {
                html += `&nbsp;&nbsp;📄 ${files[i].name}<br>`;
            }
            if (files.length > 5) {
                html += `&nbsp;&nbsp;... 还有 ${files.length - 5} 个文件`;
            }
            batchSelectedFiles.innerHTML = html;
            batchSelectedFiles.style.display = 'block';
            batchSelectedFiles.style.color = '#28a745';
        } else {
            batchSelectedFiles.style.display = 'none';
        }
    }
    
    if (batchUploadArea) {
        batchUploadArea.onclick = () => batchFileInput.click();
        batchUploadArea.ondragover = (e) => { 
            e.preventDefault(); 
            batchUploadArea.style.borderColor = 'var(--primary-color)';
            batchUploadArea.style.background = 'rgba(102,126,234,0.05)';
        };
        batchUploadArea.ondragleave = () => { 
            batchUploadArea.style.borderColor = 'var(--border-color)';
            batchUploadArea.style.background = 'transparent';
        };
        batchUploadArea.ondrop = (e) => {
            e.preventDefault();
            batchUploadArea.style.borderColor = 'var(--border-color)';
            batchUploadArea.style.background = 'transparent';
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                batchFileInput.files = e.dataTransfer.files;
                showBatchFiles(files);
            }
        };
    }
    
    if (batchFileInput) {
        batchFileInput.onchange = (e) => {
            showBatchFiles(e.target.files);
        };
    }
    
    // 批量加密提交
    document.getElementById('batchUploadForm')?.addEventListener('submit', function(e) {
        const files = batchFileInput.files;
        if (files.length === 0) {
            e.preventDefault();
            alert('请选择要加密的文件');
            return;
        }
        if (files.length > 20) {
            e.preventDefault();
            alert('最多只能选择 20 个文件');
            return;
        }
        batchProgress.style.display = 'block';
        batchSubmitBtn.disabled = true;
        batchSubmitBtn.innerHTML = '加密中...';
        
        let processed = 0;
        const total = files.length;
        
        const interval = setInterval(() => {
            processed++;
            const percent = (processed / total) * 100;
            progressBar.style.width = percent + '%';
            progressText.innerHTML = `正在加密第 ${processed} / ${total} 个文件...`;
            if (processed >= total) {
                clearInterval(interval);
            }
        }, 500);
    });
    
    // 单文件复制下载函数
    function copyToClipboard() {
        const rawTextarea = document.getElementById('encryptedCodeRaw');
        let code = '';
        if (rawTextarea && rawTextarea.value) {
            code = rawTextarea.value;
        } else {
            const displayPre = document.getElementById('encryptedCodeDisplay');
            if (displayPre) {
                code = displayPre.innerText || displayPre.textContent || '';
            }
        }
        if (!code || code.length === 0) {
            alert('❌ 未找到要复制的代码');
            return;
        }
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(code).then(() => {
                alert('✅ 代码已复制（' + code.length + ' 字符）');
            }).catch(err => {
                fallbackCopy(code);
            });
        } else {
            fallbackCopy(code);
        }
    }
    
    function fallbackCopy(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.top = '-9999px';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();
        textarea.setSelectionRange(0, text.length);
        try {
            const success = document.execCommand('copy');
            if (success) {
                alert('✅ 代码已复制（' + text.length + ' 字符）');
            } else {
                alert('❌ 复制失败，请手动复制');
            }
        } catch (err) {
            alert('❌ 复制失败，请手动复制');
        }
        document.body.removeChild(textarea);
    }
    
    function downloadFile() {
        const rawTextarea = document.getElementById('encryptedCodeRaw');
        let code = '';
        if (rawTextarea && rawTextarea.value) {
            code = rawTextarea.value;
        } else {
            const displayPre = document.getElementById('encryptedCodeDisplay');
            if (displayPre) {
                code = displayPre.innerText || displayPre.textContent || '';
            }
        }
        if (!code) {
            alert('❌ 未找到要下载的代码');
            return;
        }
        const originalName = '<?php echo $uploaded_filename; ?>';
        const baseName = originalName.replace(/\.(php|py|js|lua|rb)$/, '');
        const ext = '<?php echo getFileExtension($current_lang); ?>';
        const blob = new Blob([code], {type: 'text/plain'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = (baseName || 'encrypted') + '_' + Date.now() + '.' + ext;
        a.click();
        URL.revokeObjectURL(url);
    }
</script>
<?php include 'footer.php'; ?>