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

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

// 支持的语言列表
$supported_langs = [
    'php' => ['name' => 'PHP', 'ext' => 'php', 'icon' => 'language-php', 'color' => '777bb4', 'desc' => '适合PHP网站源码加密'],
    'python' => ['name' => 'Python', 'ext' => 'py', 'icon' => 'language-python', 'color' => '3776ab', 'desc' => '适合Python脚本/项目加密'],
    'javascript' => ['name' => 'JavaScript', 'ext' => 'js', 'icon' => 'language-javascript', 'color' => 'f7df1e', 'desc' => '适合Node.js/前端代码混淆'],
    'lua' => ['name' => 'Lua', 'ext' => 'lua', 'icon' => 'language-lua', 'color' => '000080', 'desc' => '适合Lua脚本加密'],
    'ruby' => ['name' => 'Ruby', 'ext' => 'rb', 'icon' => 'language-ruby', 'color' => 'cc342d', '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-tool-container">
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:shield-lock.svg?color=%23667eea" width="28" height="28" style="vertical-align: middle; margin-right: 10px;" alt="">
            多语言代码加密工具
        </h2>
        <p class="page-desc">支持 PHP、Python、JavaScript、Lua、Ruby 代码加密保护</p>
    </div>

    <!-- 语言选择器 -->
    <div class="lang-selector">
        <?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; ?>">
            <img src="https://api.iconify.design/mdi:<?php echo $lang_info['icon']; ?>.svg?color=%23<?php echo $lang_info['color']; ?>" width="24" height="24" alt="">
            <span><?php echo $lang_info['name']; ?></span>
        </button>
        <?php endforeach; ?>
    </div>

    <!-- 当前语言提示 -->
    <div class="lang-tip">
        <img src="https://api.iconify.design/mdi:information.svg?color=%23667eea" width="18" height="18" alt="">
        <span>当前语言：<strong><?php echo $supported_langs[$current_lang]['name']; ?></strong> - <?php echo $supported_langs[$current_lang]['desc']; ?></span>
    </div>

    <!-- 模式切换 -->
    <div class="mode-selector">
        <button type="button" id="singleModeBtn" class="mode-btn active">
            <img src="https://api.iconify.design/mdi:file.svg?color=white" width="18" height="18" alt="">
            单文件加密
        </button>
        <button type="button" id="batchModeBtn" class="mode-btn">
            <img src="https://api.iconify.design/mdi:file-multiple.svg?color=%236b7280" width="18" height="18" alt="">
            批量加密
        </button>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-error">
            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" alt="">
            <?php echo htmlspecialchars($error); ?>
        </div>
    <?php endif; ?>

    <!-- 单文件加密模式 -->
    <div id="singleMode" class="encrypt-mode" style="display: block;">
        <?php if ($result): ?>
            <div class="result-card">
                <div class="result-header">
                    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="24" height="24" alt="">
                    <h3>加密成功</h3>
                </div>
                <div class="file-info">
                    <img src="https://api.iconify.design/mdi:file-document.svg?color=%23667eea" width="20" height="20" alt="">
                    <span><strong>原始文件：</strong><?php echo $uploaded_filename; ?></span>
                </div>
                <div class="result-actions">
                    <button class="btn btn-primary" onclick="copyToClipboard()">
                        <img src="https://api.iconify.design/mdi:content-copy.svg?color=white" width="18" height="18" alt="">
                        复制代码
                    </button>
                    <button class="btn btn-success" onclick="downloadFile()">
                        <img src="https://api.iconify.design/mdi:download.svg?color=white" width="18" height="18" alt="">
                        下载文件
                    </button>
                </div>
                <textarea id="encryptedCodeRaw" style="display: none;"><?php echo htmlspecialchars($result); ?></textarea>
                <pre id="encryptedCodeDisplay" class="code-preview"><?php echo htmlspecialchars($result); ?></pre>
            </div>
        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data" id="singleUploadForm" class="upload-form">
            <input type="hidden" name="lang" value="<?php echo $current_lang; ?>">
            <div class="upload-area" id="uploadArea">
                <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=%23667eea" width="48" height="48" alt="">
                <p>点击或拖拽上传 <?php echo $supported_langs[$current_lang]['name']; ?> 文件</p>
                <p class="upload-hint">支持 .<?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" class="selected-file"></div>
            </div>
            <input type="file" name="code_file" id="fileInput" style="display: none;">

            <div class="encrypt-options">
                <label class="radio-label">
                    <input type="radio" name="encrypt_level" value="low" checked>
                    <span>普通加密</span>
                </label>
                <label class="radio-label">
                    <input type="radio" name="encrypt_level" value="high">
                    <span>高强度加密 <span class="recommend">推荐</span></span>
                </label>
            </div>

            <!-- 域名绑定选项（仅PHP支持） -->
            <?php if ($current_lang === 'php'): ?>
            <div class="domain-bind-section">
                <div class="section-title">
                    <img src="https://api.iconify.design/mdi:link.svg?color=%23667eea" width="18" height="18" alt="">
                    域名绑定（可选）
                </div>
                <div class="form-group">
                    <input type="text" name="bind_domain" id="bind_domain" placeholder="例如：example.com 或 *.example.com">
                    <small>留空则不限制域名。支持泛域名，如 *.example.com 匹配所有子域名</small>
                </div>
                <div class="bind-type">
                    <label class="radio-label">
                        <input type="radio" name="bind_type" value="exact" checked>
                        <span>精确匹配</span>
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="bind_type" value="wildcard">
                        <span>泛域名匹配</span>
                    </label>
                </div>
            </div>
            <?php else: ?>
            <div class="domain-bind-section disabled">
                <div class="section-title">
                    <img src="https://api.iconify.design/mdi:link-off.svg?color=%239ca3af" width="18" height="18" alt="">
                    域名绑定
                </div>
                <p class="disabled-hint">域名绑定功能仅支持 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 btn-lg">
                <img src="https://api.iconify.design/mdi:shield-lock.svg?color=white" width="20" height="20" alt="">
                开始加密
            </button>
        </form>
    </div>

    <!-- 批量加密模式 -->
    <div id="batchMode" class="encrypt-mode" style="display: none;">
        <form method="POST" enctype="multipart/form-data" id="batchUploadForm" class="upload-form">
            <input type="hidden" name="lang" value="<?php echo $current_lang; ?>">
            <div class="upload-area" id="batchUploadArea">
                <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=%23667eea" width="48" height="48" alt="">
                <p>点击或拖拽上传多个 <?php echo $supported_langs[$current_lang]['name']; ?> 文件</p>
                <p class="upload-hint">支持批量上传，最多 20 个文件，每个最大 5MB</p>
                <div id="batchSelectedFiles" class="selected-file"></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 class="encrypt-options">
                <label class="radio-label">
                    <input type="radio" name="encrypt_level" value="low" checked>
                    <span>普通加密</span>
                </label>
                <label class="radio-label">
                    <input type="radio" name="encrypt_level" value="high">
                    <span>高强度加密 <span class="recommend">推荐</span></span>
                </label>
            </div>

            <?php if ($current_lang === 'php'): ?>
            <div class="domain-bind-section">
                <div class="section-title">
                    <img src="https://api.iconify.design/mdi:link.svg?color=%23667eea" width="18" height="18" alt="">
                    域名绑定（可选）
                </div>
                <div class="form-group">
                    <input type="text" name="bind_domain" id="batch_bind_domain" placeholder="例如：example.com 或 *.example.com">
                    <small>留空则不限制域名。支持泛域名，如 *.example.com 匹配所有子域名</small>
                </div>
                <div class="bind-type">
                    <label class="radio-label">
                        <input type="radio" name="bind_type" value="exact" checked>
                        <span>精确匹配</span>
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="bind_type" value="wildcard">
                        <span>泛域名匹配</span>
                    </label>
                </div>
            </div>
            <?php else: ?>
            <div class="domain-bind-section disabled">
                <div class="section-title">
                    <img src="https://api.iconify.design/mdi:link-off.svg?color=%239ca3af" width="18" height="18" alt="">
                    域名绑定
                </div>
                <p class="disabled-hint">域名绑定功能仅支持 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 btn-lg" id="batchSubmitBtn">
                <img src="https://api.iconify.design/mdi:archive.svg?color=white" width="20" height="20" alt="">
                批量加密并下载
            </button>
        </form>

        <div id="batchProgress" class="batch-progress" style="display: none;">
            <h4>
                <img src="https://api.iconify.design/mdi:progress-clock.svg?color=%23667eea" width="20" height="20" alt="">
                加密进度
            </h4>
            <div class="progress-bar">
                <div id="progressBar" class="progress-fill"></div>
            </div>
            <p id="progressText">准备中...</p>
        </div>
    </div>
</div>

<style>
/* 基础变量 - 明暗主题兼容 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

/* 深色主题变量 */
[data-theme="dark"] {
    --bg-primary: #1f2937;
    --bg-secondary: #374151;
    --text-primary: #f9fafb;
    --text-secondary: #d1d5db;
    --text-muted: #9ca3af;
    --border-color: #4b5563;
}

.encrypt-tool-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
    background: var(--bg-primary);
}

.page-header {
    text-align: center;
    margin-bottom: 24px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    font-weight: 700;
    color: var(--text-primary);
}
.page-desc {
    color: var(--text-secondary);
    margin-top: 8px;
}

/* 语言选择器 */
.lang-selector {
    display: flex;
    gap: 12px;
    justify-content: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
}
.lang-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    background: var(--bg-secondary);
    border: 2px solid var(--border-color);
    border-radius: 40px;
    cursor: pointer;
    transition: all 0.2s;
    font-weight: 500;
    color: var(--text-primary);
}
.lang-btn:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-md);
}
.lang-btn.active {
    background: linear-gradient(135deg, #667eea, #764ba2);
    border-color: transparent;
    color: white;
}
.lang-btn.active img {
    filter: brightness(0) invert(1);
}

/* 语言提示 */
.lang-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 20px;
    background: var(--bg-secondary);
    border-radius: 40px;
    margin-bottom: 24px;
    color: var(--text-secondary);
    border: 1px solid var(--border-color);
}
.lang-tip strong {
    color: var(--text-primary);
}

/* 模式切换 */
.mode-selector {
    display: flex;
    gap: 10px;
    margin-bottom: 24px;
    background: var(--bg-secondary);
    padding: 4px;
    border-radius: 40px;
    border: 1px solid var(--border-color);
}
.mode-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 20px;
    background: transparent;
    border: none;
    border-radius: 36px;
    cursor: pointer;
    font-weight: 500;
    color: var(--text-secondary);
    transition: all 0.2s;
}
.mode-btn.active {
    background: var(--primary-color);
    color: white;
}
.mode-btn.active img {
    filter: brightness(0) invert(1);
}
.mode-btn img {
    filter: none;
}

/* 提示消息 */
.alert {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 14px 20px;
    border-radius: 12px;
    margin-bottom: 24px;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

/* 上传区域 */
.encrypt-mode {
    background: var(--bg-primary);
}
.upload-form {
    background: var(--bg-primary);
    border-radius: 20px;
    padding: 28px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.upload-area {
    border: 2px dashed var(--border-color);
    border-radius: 16px;
    padding: 40px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
    background: var(--bg-primary);
}
.upload-area:hover {
    border-color: var(--primary-color);
    background: var(--bg-secondary);
}
.upload-area p {
    margin: 12px 0 8px;
    font-weight: 500;
    color: var(--text-primary);
}
.upload-hint {
    font-size: 12px;
    color: var(--text-muted);
}
.selected-file {
    margin-top: 12px;
    font-size: 14px;
    color: #10b981;
}

/* 加密选项 */
.encrypt-options {
    display: flex;
    gap: 24px;
    margin: 20px 0;
}
.radio-label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    color: var(--text-primary);
}
.radio-label input {
    accent-color: var(--primary-color);
    width: 18px;
    height: 18px;
}
.recommend {
    background: #f59e0b;
    color: white;
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
    margin-left: 6px;
}

/* 域名绑定 */
.domain-bind-section {
    background: var(--bg-secondary);
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 24px;
    border: 1px solid var(--border-color);
}
.domain-bind-section.disabled {
    opacity: 0.6;
}
.section-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 600;
    margin-bottom: 16px;
    color: var(--text-primary);
}
.form-group {
    margin-bottom: 16px;
}
.form-group input {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: 10px;
    background: var(--bg-primary);
    font-size: 14px;
    color: var(--text-primary);
}
.form-group input:focus {
    outline: none;
    border-color: var(--primary-color);
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}
.bind-type {
    display: flex;
    gap: 20px;
}
.disabled-hint {
    color: var(--text-muted);
    font-size: 13px;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 24px;
    border-radius: 10px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
}
.btn-primary:hover {
    background: var(--primary-hover);
}
.btn-success {
    background: #10b981;
    color: white;
}
.btn-success:hover {
    background: #059669;
}
.btn-lg {
    width: 100%;
    padding: 14px 24px;
    font-size: 16px;
}

/* 结果卡片 */
.result-card {
    margin-bottom: 28px;
}
.result-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
}
.result-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #10b981;
}
.file-info {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: var(--bg-secondary);
    border-radius: 10px;
    margin-bottom: 16px;
    color: var(--text-primary);
    border: 1px solid var(--border-color);
}
.result-actions {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
}
.code-preview {
    background: var(--bg-secondary);
    padding: 16px;
    border-radius: 12px;
    overflow-x: auto;
    font-size: 13px;
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid var(--border-color);
    color: var(--text-primary);
}

/* 批量进度 */
.batch-progress {
    margin-top: 24px;
    padding: 20px;
    background: var(--bg-primary);
    border-radius: 16px;
    border: 1px solid var(--border-color);
}
.batch-progress h4 {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    color: var(--text-primary);
}
.progress-bar {
    height: 8px;
    background: var(--border-color);
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 12px;
}
.progress-fill {
    height: 100%;
    width: 0%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    transition: width 0.3s;
}
#progressText {
    color: var(--text-secondary);
}

/* 响应式 */
@media (max-width: 768px) {
    .lang-selector {
        flex-direction: column;
    }
    .lang-btn {
        justify-content: center;
    }
    .mode-selector {
        flex-direction: column;
    }
    .result-actions {
        flex-direction: column;
    }
    .result-actions .btn {
        width: 100%;
    }
    .encrypt-options {
        flex-direction: column;
        gap: 12px;
    }
    .bind-type {
        flex-direction: column;
        gap: 10px;
    }
}
</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');
    // 更新图标颜色
    const singleImg = singleModeBtn.querySelector('img');
    const batchImg = batchModeBtn.querySelector('img');
    if (singleImg) singleImg.style.filter = 'brightness(0) invert(1)';
    if (batchImg) batchImg.style.filter = 'none';
});

batchModeBtn.addEventListener('click', () => {
    singleMode.style.display = 'none';
    batchMode.style.display = 'block';
    batchModeBtn.classList.add('active');
    singleModeBtn.classList.remove('active');
    // 更新图标颜色
    const singleImg = singleModeBtn.querySelector('img');
    const batchImg = batchModeBtn.querySelector('img');
    if (batchImg) batchImg.style.filter = 'brightness(0) invert(1)';
    if (singleImg) singleImg.style.filter = 'none';
});

// 语言切换
document.querySelectorAll('.lang-btn').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 = `<img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="16" height="16" alt=""> 已选择：${file.name}`;
        selectedFileDiv.style.display = 'block';
    } else if (file) {
        selectedFileDiv.innerHTML = `<img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="16" height="16" alt=""> 请选择 ${allowed.join('/')} 文件`;
        selectedFileDiv.style.display = 'block';
    } 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 = `<img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="16" height="16" alt=""> 已选择 ${files.length} 个文件：<br>`;
        for (let i = 0; i < Math.min(files.length, 5); i++) {
            html += `&nbsp;&nbsp;<img src="https://api.iconify.design/mdi:file.svg?color=%236b7280" width="14" height="14" alt=""> ${files[i].name}<br>`;
        }
        if (files.length > 5) {
            html += `&nbsp;&nbsp;... 还有 ${files.length - 5} 个文件`;
        }
        batchSelectedFiles.innerHTML = html;
        batchSelectedFiles.style.display = 'block';
    } 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 = '<span class="loading-spinner"></span> 加密中...';
    
    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 = rawTextarea?.value || document.getElementById('encryptedCodeDisplay')?.innerText || '';
    if (!code) { alert('未找到要复制的代码'); return; }
    
    navigator.clipboard?.writeText(code).then(() => {
        alert('代码已复制');
    }).catch(() => {
        const textarea = document.createElement('textarea');
        textarea.value = code;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        alert('代码已复制');
    });
}

function downloadFile() {
    const rawTextarea = document.getElementById('encryptedCodeRaw');
    let code = rawTextarea?.value || document.getElementById('encryptedCodeDisplay')?.innerText || '';
    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);
}

// 加载动画
const style = document.createElement('style');
style.textContent = `
    .loading-spinner {
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: white;
        animation: spin 0.6s linear infinite;
        margin-right: 8px;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
`;
document.head.appendChild(style);
</script>
<?php include 'footer.php'; ?>