<?php
/**
 * 浪神 · 控制台 v22
 * ------------------------------------------------------------
 * 一个文件干完五件事：
 *   1. 卡密：批量生成、自定义到期（天数 / 指定日期 / 永久 / 首次激活起算）、停用、解绑、导出
 *   2. 上传：分片上传，多大都能传（50MB 的 ipa、几百 MB 的 mp4 都行），不再受 php.ini 单次上限卡死
 *   3. 发布：选文件 + 版本号 + 说明 → 写 api/manifest.json，App 端自动收到，旧包自动清
 *   4. 验证接口：自动生成 api/verify.php，App 拿它校验卡密
 *   5. 设置：改口令、设备锁开关、接口自检
 *
 * 部署：放站点根目录 index.php（ek.x8iu.com/index.php），PHP 8.0+，不需要数据库。
 * 目录结构（自动创建）：
 *   index.php
 *   api/verify.php        验证接口
 *   api/manifest.json     云端更新清单
 *   api/files/            上传的文件（pak / ipa / mp4 都放这，可直链）
 *   data/config.json      口令、开关
 *   data/licenses.json    卡密数据
 *   data/tmp/             分片临时文件
 * ------------------------------------------------------------
 */

declare(strict_types=1);

// 有些空间没装 mbstring，这里给个兜底，别直接 500
if (!function_exists('mb_internal_encoding')) {
    function mb_internal_encoding(string $encoding = 'UTF-8'): bool { return true; }
    function mb_strlen(string $string, ?string $encoding = null): int { return strlen($string); }
    function mb_substr(string $string, int $start, ?int $length = null, ?string $encoding = null): string {
        return $length === null ? substr($string, $start) : substr($string, $start, $length);
    }
    function mb_stripos(string $haystack, string $needle, int $offset = 0, ?string $encoding = null) {
        return stripos($haystack, $needle, $offset);
    }
}
mb_internal_encoding('UTF-8');
date_default_timezone_set('Asia/Shanghai');

const LS_ROOT     = __DIR__;
const LS_DATA     = LS_ROOT . '/data';
const LS_TMP      = LS_DATA . '/tmp';
const LS_UPLOADS  = LS_ROOT . '/api/files';
const LS_MANIFEST = LS_ROOT . '/api/manifest.json';
const LS_VERIFY   = LS_ROOT . '/api/verify.php';
const LS_CONFIG   = LS_DATA . '/config.json';
const LS_LICENSE  = LS_DATA . '/licenses.json';
const LS_THEME    = LS_ROOT . '/api/license-theme.json';

const LS_CHUNK_MIN = 512 * 1024;

// 这些扩展名到服务器上会被当代码执行，落地时一律改尾缀
const LS_DANGER_EXT = ['php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phar',
                       'htaccess', 'htpasswd', 'sh', 'bash', 'cgi', 'pl', 'py', 'rb', 'jsp', 'asp'];

foreach ([LS_DATA, LS_TMP, LS_UPLOADS, LS_ROOT . '/api'] as $dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
}
// 目录不许列文件
foreach ([LS_DATA, LS_TMP, LS_UPLOADS] as $dir) {
    if (!is_file($dir . '/index.html')) {
        @file_put_contents($dir . '/index.html', '<!doctype html><title>403</title>');
    }
}
// 会话文件自己存一份，别指望空间的 /var/lib/php/sessions 一定可写
$lsSessDir = LS_DATA . '/sessions';
if (!is_dir($lsSessDir)) @mkdir($lsSessDir, 0755, true);
if (is_dir($lsSessDir) && is_writable($lsSessDir)) {
    @session_save_path($lsSessDir);
}
if (session_status() !== PHP_SESSION_ACTIVE) {
    @session_start();
}
if (!is_file($lsSessDir . '/index.html')) {
    @file_put_contents($lsSessDir . '/index.html', '<!doctype html><title>403</title>');
}

if (!is_file(LS_UPLOADS . '/.htaccess')) {
    @file_put_contents(LS_UPLOADS . '/.htaccess',
        "Options -Indexes\n" .
        "<FilesMatch \"\\.(php|phtml|phar|pl|py|cgi|sh)$\">\n  Require all denied\n</FilesMatch>\n");
}

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function human_size($bytes): string {
    $bytes = (float)$bytes;
    if ($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576)    return round($bytes / 1048576, 1) . ' MB';
    if ($bytes >= 1024)       return round($bytes / 1024, 1) . ' KB';
    return (int)$bytes . ' B';
}

function read_json(string $path, array $fallback = []): array {
    if (!is_file($path)) return $fallback;
    $raw = @file_get_contents($path);
    if ($raw === false || $raw === '') return $fallback;
    $data = json_decode($raw, true);
    return is_array($data) ? $data : $fallback;
}

function write_json(string $path, array $data): bool {
    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    if ($json === false) return false;
    $tmp = $path . '.tmp';
    if (@file_put_contents($tmp, $json) === false) return false;
    return @rename($tmp, $path);
}

// ---------------- 卡密窗口样式（App 端 api/license-theme.json） ----------------

function ls_theme_default(): array {
    return [
        'version'        => 0,
        'title'          => '浪神',
        'subtitle'       => '清残留 防封号 玩得稳',
        'section'        => '授权验证',
        'fieldLabel'     => '请输入浪神卡密',
        'placeholder'    => '请输入您的授权码',
        'button'         => '立即验证',
        'footer'         => '卡密可在官方渠道获取',
        'copyright'      => '浪神 2026 版权 @浪神所有',
        'primary'        => '#29EB85',
        'secondary'      => '#12A38F',
        'accent'         => '#8F70F5',
        'inputText'      => '#1A1A1A',
        'dim'            => 0.62,
        'corner'         => 28,
        'showShield'     => true,
        'buttonGradient' => true,
        'background'     => '',
        'logo'           => '',
    ];
}

/// 读：把存的文件按默认值补齐，缺字段、类型不对都不会让 App 那边崩
function ls_theme_read(): array {
    $theme = ls_theme_default();
    $saved = read_json(LS_THEME, []);
    if (isset($saved['theme']) && is_array($saved['theme'])) $saved = $saved['theme'];
    foreach ($theme as $k => $def) {
        if (!array_key_exists($k, $saved)) continue;
        if (is_bool($def))        $theme[$k] = (bool)$saved[$k];
        elseif (is_int($def))     $theme[$k] = (int)$saved[$k];
        elseif (is_float($def))   $theme[$k] = (float)$saved[$k];
        else                      $theme[$k] = (string)$saved[$k];
    }
    return $theme;
}

/// 写：App 直接 GET 这个文件，所以带 ok 方便肉眼确认
function ls_theme_write(array $theme): bool {
    $theme['updated'] = date('Y-m-d H:i:s');
    $payload = ['ok' => true] + $theme;
    return write_json(LS_THEME, $payload);
}

/// 删掉一张自己发过的图（只认 api/files 里 theme- 开头的）
function ls_theme_unlink(string $rel): void {
    $rel = trim($rel);
    if ($rel === '' || strpos($rel, 'api/files/theme-') !== 0) return;
    $path = LS_ROOT . '/' . $rel;
    if (is_file($path)) @unlink($path);
}

function rand_token(int $len = 16): string {
    $bytes = random_bytes(max(8, $len));
    return rtrim(strtr(base64_encode($bytes), '+/', 'ab'), '=');
}

function client_ip(): string {
    return (string)($_SERVER['REMOTE_ADDR'] ?? '');
}

function base_url(): string {
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $host = (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
    $dir = rtrim(str_replace('\\', '/', dirname((string)($_SERVER['SCRIPT_NAME'] ?? '/'))), '/');
    return ($https ? 'https' : 'http') . '://' . $host . $dir;
}

// ---------------- 配置 ----------------

$config = read_json(LS_CONFIG, []);
if (!isset($config['device_lock'])) $config['device_lock'] = true;
if (!isset($config['max_devices'])) $config['max_devices'] = 1;
$setupNeeded = empty($config['pass_hash']);

// ---------------- 验证接口：缺失就自动补一份 ----------------

function verify_source(): string {
    return <<<'PHPV'
<?php
/**
 * 浪神 · 卡密验证接口（App 调用）
 * 自动由后台生成，一般不用手改。
 * 入参：code=卡密  device=设备标识  返回：{"ok":true,"exp":到期时间戳,"msg":"..."}
 */
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$ROOT  = dirname(__DIR__);
$LIC   = $ROOT . '/data/licenses.json';
$CFG   = $ROOT . '/data/config.json';

function ls_out(array $payload): void {
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

$cfg = [];
if (is_file($CFG)) {
    $tmp = json_decode((string)file_get_contents($CFG), true);
    if (is_array($tmp)) $cfg = $tmp;
}
$deviceLock = array_key_exists('device_lock', $cfg) ? (bool)$cfg['device_lock'] : true;
$maxDevices = max(1, (int)($cfg['max_devices'] ?? 1));

$code   = strtoupper(trim((string)($_POST['code'] ?? $_GET['code'] ?? '')));
$device = trim((string)($_POST['device'] ?? $_GET['device'] ?? ''));
$device = preg_replace('/[^A-Za-z0-9\-_]/', '', $device);
if ($device === '') $device = 'unknown';

if ($code === '') ls_out(['ok' => false, 'msg' => '卡密不能为空']);
if (!is_file($LIC)) ls_out(['ok' => false, 'msg' => '后台还没生成过卡密']);

$fp = fopen($LIC, 'c+');
if ($fp === false) ls_out(['ok' => false, 'msg' => '服务器读取失败，稍后再试']);
flock($fp, LOCK_EX);
$raw = stream_get_contents($fp);
$lic = json_decode((string)$raw, true);
if (!is_array($lic)) $lic = [];

$now = time();
if (!isset($lic[$code]) || !is_array($lic[$code])) {
    flock($fp, LOCK_UN); fclose($fp);
    ls_out(['ok' => false, 'msg' => '卡密不存在，请核对后重试']);
}

$item = $lic[$code];

if (!empty($item['disabled'])) {
    flock($fp, LOCK_UN); fclose($fp);
    ls_out(['ok' => false, 'msg' => '这张卡密已被停用']);
}

$exp = (int)($item['exp'] ?? 0);
$days = (int)($item['days'] ?? 0);
$first = !empty($item['first_use']);

// 未激活：首次验证才开始算时间
if ($exp <= 0 && $days > 0 && $first) {
    $exp = $now + $days * 86400;
    $lic[$code]['exp'] = $exp;
    $lic[$code]['activated_at'] = $now;
} elseif ($exp <= 0 && $days > 0 && !$first) {
    $exp = $now + $days * 86400;
    $lic[$code]['exp'] = $exp;
    $lic[$code]['activated_at'] = $now;
}

if ($exp > 0 && $exp <= $now) {
    flock($fp, LOCK_UN); fclose($fp);
    ls_out(['ok' => false, 'msg' => '卡密已到期，请续费后重试']);
}

// ---------- 续费：把这张新卡密的时长加到原来那张卡上 ----------
$mode     = strtolower(trim((string)($_POST['mode'] ?? $_GET['mode'] ?? '')));
$baseCode = strtoupper(trim((string)($_POST['base'] ?? $_GET['base'] ?? '')));

if ($mode === 'renew' && $baseCode !== '' && $baseCode !== $code) {
    if (!isset($lic[$baseCode]) || !is_array($lic[$baseCode])) {
        flock($fp, LOCK_UN); fclose($fp);
        ls_out(['ok' => false, 'msg' => '找不到原来的卡密，请联系管理员处理']);
    }
    $grant = ($exp > 0) ? max(0, $exp - $now) : 0;
    if ($grant <= 0) $grant = max(0, (int)($item['days'] ?? 0)) * 86400;
    if ($grant <= 0) {
        flock($fp, LOCK_UN); fclose($fp);
        ls_out(['ok' => false, 'msg' => '这张卡密没有可用时长，不能用来续费']);
    }
    $oldExp = (int)($lic[$baseCode]['exp'] ?? 0);
    $newExp = max($now, $oldExp) + $grant;
    $lic[$baseCode]['exp'] = $newExp;
    $lic[$baseCode]['renewed_at'] = $now;
    $lic[$baseCode]['last_check'] = $now;
    $oldDevs = isset($lic[$baseCode]['devices']) && is_array($lic[$baseCode]['devices']) ? $lic[$baseCode]['devices'] : [];
    if (!in_array($device, $oldDevs, true)) $oldDevs[] = $device;
    $lic[$baseCode]['devices'] = array_values($oldDevs);
    // 用掉的那张续费卡：直接作废，防止二次使用
    $lic[$code]['disabled'] = true;
    $lic[$code]['consumed_by'] = $baseCode;
    $lic[$code]['consumed_at'] = $now;

    ftruncate($fp, 0);
    rewind($fp);
    fwrite($fp, (string)json_encode($lic, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);

    ls_out([
        'ok'  => true,
        'exp' => $newExp,
        'msg' => '续费成功',
        'plan' => (string)($lic[$baseCode]['plan'] ?? ''),
    ]);
}

// 设备绑定
if ($deviceLock) {
    $devices = isset($item['devices']) && is_array($item['devices']) ? $item['devices'] : [];
    if (!in_array($device, $devices, true)) {
        if (count($devices) >= $maxDevices) {
            flock($fp, LOCK_UN); fclose($fp);
            ls_out(['ok' => false, 'msg' => '这张卡密已在其他设备使用，换机请联系管理员解绑']);
        }
        $devices[] = $device;
        $lic[$code]['devices'] = array_values($devices);
    }
}

$lic[$code]['last_check'] = $now;
$lic[$code]['last_ip'] = (string)($_SERVER['REMOTE_ADDR'] ?? '');

ftruncate($fp, 0);
rewind($fp);
fwrite($fp, (string)json_encode($lic, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
fflush($fp);
flock($fp, LOCK_UN);
fclose($fp);

ls_out([
    'ok'  => true,
    'exp' => $exp,
    'msg' => '验证成功',
    'plan' => (string)($item['plan'] ?? ''),
]);
PHPV;
}

if (!is_file(LS_VERIFY)) {
    @file_put_contents(LS_VERIFY, verify_source());
}

// ---------------- 登录 / 首次设置口令 ----------------

$flash = '';
$flashBad = false;

$action = (string)($_POST['action'] ?? $_GET['action'] ?? '');

if ($action === 'logout') {
    $_SESSION = [];
    session_destroy();
    header('Location: ' . strtok((string)$_SERVER['REQUEST_URI'], '?'));
    exit;
}

if ($setupNeeded && $_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'setup') {
    $pass = (string)($_POST['password'] ?? '');
    $pass2 = (string)($_POST['password2'] ?? '');
    if (mb_strlen($pass) < 6) {
        $flash = '口令至少 6 位'; $flashBad = true;
    } elseif ($pass !== $pass2) {
        $flash = '两次输入不一致'; $flashBad = true;
    } else {
        $config['pass_hash'] = password_hash($pass, PASSWORD_DEFAULT);
        $config['created'] = time();
        write_json(LS_CONFIG, $config);
        $_SESSION['ok'] = true;
        header('Location: ' . base_url() . '/');
        exit;
    }
}

if (!$setupNeeded && $_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'login') {
    $pass = (string)($_POST['password'] ?? '');
    if (password_verify($pass, (string)$config['pass_hash'])) {
        $_SESSION['ok'] = true;
        $_SESSION['csrf'] = rand_token(24);
        header('Location: ' . base_url() . '/');
        exit;
    }
    $flash = '口令不对'; $flashBad = true;
}

$logged = !empty($_SESSION['ok']) && !$setupNeeded;
if ($logged && empty($_SESSION['csrf'])) $_SESSION['csrf'] = rand_token(24);
$csrf = (string)($_SESSION['csrf'] ?? '');

function check_csrf(string $csrf): void {
    if (!hash_equals($csrf, (string)($_POST['csrf'] ?? ''))) {
        http_response_code(400);
        echo '会话已过期，刷新页面重试';
        exit;
    }
}

// ---------------- 卡密：生成 ----------------

function gen_code(string $prefix = 'LS'): string {
    $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $pick = static function (int $n) use ($alphabet): string {
        $out = '';
        for ($i = 0; $i < $n; $i++) $out .= $alphabet[random_int(0, strlen($alphabet) - 1)];
        return $out;
    };
    return $prefix . '-' . $pick(4) . '-' . $pick(4) . '-' . $pick(4);
}

function lic_state(array $item): string {
    if (!empty($item['disabled'])) return 'disabled';
    $exp = (int)($item['exp'] ?? 0);
    if ($exp > 0) return $exp > time() ? 'valid' : 'expired';
    if ((int)($item['days'] ?? 0) > 0) return 'unused';
    return 'forever';
}

function lic_state_text(array $item): string {
    switch (lic_state($item)) {
        case 'disabled': return '已停用';
        case 'expired':  return '已到期';
        case 'unused':   return '未激活';
        case 'valid':    return '有效';
        default:         return '永久';
    }
}

function lic_exp_text(array $item): string {
    $exp = (int)($item['exp'] ?? 0);
    if ($exp > 0) return date('Y-m-d H:i', $exp);
    if ((int)($item['days'] ?? 0) > 0) return '未激活 · 首次验证起 ' . (int)$item['days'] . ' 天';
    return '永久有效';
}

function safe_filename(string $name): string {
    $name = str_replace(['\\', '/', "\0"], '', $name);
    $name = preg_replace('/[\x00-\x1F\x7F]/u', '', $name) ?? $name;
    $name = trim($name);
    if ($name === '' || $name === '.' || $name === '..') $name = 'file';
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if ($ext !== '' && in_array($ext, LS_DANGER_EXT, true)) {
        $name .= '.bin';
    }
    return $name;
}

if ($logged && $_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf($csrf);

    $lic = read_json(LS_LICENSE, []);

    // 生成卡密
    if ($action === 'gen') {
        $count = max(1, min(500, (int)($_POST['count'] ?? 1)));
        $mode  = (string)($_POST['duration'] ?? 'days');       // days | date | forever
        $days  = max(1, min(36500, (int)($_POST['days'] ?? 30)));
        $date  = (string)($_POST['date'] ?? '');
        $startFrom = (string)($_POST['start_from'] ?? 'first'); // first | now
        $note  = mb_substr(trim((string)($_POST['note'] ?? '')), 0, 60);
        $plan  = mb_substr(trim((string)($_POST['plan'] ?? '')), 0, 20);

        $made = [];
        for ($i = 0; $i < $count; $i++) {
            $code = gen_code();
            while (isset($lic[$code])) $code = gen_code();

            $item = [
                'created'  => time(),
                'note'     => $note,
                'plan'     => $plan,
                'disabled' => false,
                'devices'  => [],
                'exp'      => 0,
                'days'     => 0,
                'first_use' => false,
            ];

            if ($mode === 'forever') {
                $item['exp'] = 0;
                $item['days'] = 0;
            } elseif ($mode === 'date') {
                $ts = $date !== '' ? strtotime($date . ' 23:59:59') : false;
                if ($ts === false || $ts <= time()) {
                    $flash = '到期日期不对，要么写 2026-12-31 这种，要么选天数';
                    $flashBad = true;
                    break;
                }
                $item['exp'] = $ts;
                $item['days'] = max(1, (int)round(($ts - time()) / 86400));
            } else {
                $item['days'] = $days;
                if ($startFrom === 'now') {
                    $item['exp'] = time() + $days * 86400;
                } else {
                    $item['first_use'] = true;
                    $item['exp'] = 0;
                }
            }

            $lic[$code] = $item;
            $made[] = $code;
        }

        if (!$flashBad && count($made) > 0) {
            write_json(LS_LICENSE, $lic);
            $_SESSION['last_made'] = $made;
            $flash = '已生成 ' . count($made) . ' 张卡密';
            if (count($made) === 1) $flash .= '：' . $made[0];
        }
    }

    // 停用 / 启用
    if ($action === 'toggle') {
        $code = strtoupper(trim((string)($_POST['code'] ?? '')));
        if (isset($lic[$code])) {
            $lic[$code]['disabled'] = empty($lic[$code]['disabled']);
            write_json(LS_LICENSE, $lic);
            $flash = '已' . ($lic[$code]['disabled'] ? '停用 ' : '启用 ') . $code;
        }
    }

    // 解绑设备
    if ($action === 'unbind') {
        $code = strtoupper(trim((string)($_POST['code'] ?? '')));
        if (isset($lic[$code])) {
            $lic[$code]['devices'] = [];
            write_json(LS_LICENSE, $lic);
            $flash = '已解绑 ' . $code . ' 的设备，可在新设备登录';
        }
    }

    // 删除
    if ($action === 'delete') {
        $code = strtoupper(trim((string)($_POST['code'] ?? '')));
        if (isset($lic[$code])) {
            unset($lic[$code]);
            write_json(LS_LICENSE, $lic);
            $flash = '已删除 ' . $code;
        }
    }

    // 批量停用 / 删除
    if ($action === 'bulk') {
        $op = (string)($_POST['op'] ?? '');
        $codes = $_POST['codes'] ?? [];
        $n = 0;
        if (is_array($codes)) {
            foreach ($codes as $c) {
                $code = strtoupper(trim((string)$c));
                if (!isset($lic[$code])) continue;
                if ($op === 'disable') { $lic[$code]['disabled'] = true; $n++; }
                elseif ($op === 'enable') { $lic[$code]['disabled'] = false; $n++; }
                elseif ($op === 'delete') { unset($lic[$code]); $n++; }
            }
        }
        write_json(LS_LICENSE, $lic);
        $flash = '批量处理完成：' . $n . ' 张';
    }

    // 续期
    if ($action === 'renew') {
        $code = strtoupper(trim((string)($_POST['code'] ?? '')));
        $addDays = max(1, min(3650, (int)($_POST['add_days'] ?? 30)));
        if (isset($lic[$code])) {
            $base = max(time(), (int)($lic[$code]['exp'] ?? 0));
            $lic[$code]['exp'] = $base + $addDays * 86400;
            $lic[$code]['days'] = (int)($lic[$code]['days'] ?? 0) + $addDays;
            write_json(LS_LICENSE, $lic);
            $flash = $code . ' 已续 ' . $addDays . ' 天，到期 ' . date('Y-m-d H:i', $lic[$code]['exp']);
        }
    }

    // 设置
    if ($action === 'settings') {
        $config['device_lock'] = !empty($_POST['device_lock']);
        $config['max_devices'] = max(1, min(10, (int)($_POST['max_devices'] ?? 1)));
        if (!empty($_POST['new_password'])) {
            $np = (string)$_POST['new_password'];
            if (mb_strlen($np) < 6) {
                $flash = '新口令至少 6 位'; $flashBad = true;
            } else {
                $config['pass_hash'] = password_hash($np, PASSWORD_DEFAULT);
                $flash = '口令已更新，下次登录用新的';
            }
        }
        write_json(LS_CONFIG, $config);
        if (!$flash) $flash = '设置已保存';
    }

    // ---------------- 卡密窗口样式 ----------------

    // 文案 / 配色 / 版式
    if ($action === 'theme_save') {
        $t = ls_theme_read();

        foreach (['title','subtitle','section','fieldLabel','placeholder','button','footer','copyright'] as $k) {
            $v = trim((string)($_POST[$k] ?? ''));
            if ($v !== '') $t[$k] = mb_substr($v, 0, 60);
        }
        foreach (['primary','secondary','accent','inputText'] as $k) {
            $v = trim((string)($_POST[$k] ?? ''));
            // 只收 #RRGGBB，格式不对就保持原值（否则 App 端整页会变透明）
            if (preg_match('/^#[0-9A-Fa-f]{6}$/', $v)) $t[$k] = strtoupper($v);
        }
        $t['dim']            = max(0.15, min(0.95, (float)($_POST['dim'] ?? $t['dim'])));
        $t['corner']         = max(8, min(40, (int)($_POST['corner'] ?? $t['corner'])));
        $t['showShield']     = !empty($_POST['showShield']);
        $t['buttonGradient'] = !empty($_POST['buttonGradient']);
        $t['version']        = (int)$t['version'] + 1;

        if (ls_theme_write($t)) {
            $flash = '卡密窗口样式已保存（第 ' . (int)$t['version'] . ' 版），App 下次进卡密页自动换成这套';
        } else {
            $flash = '写 api/license-theme.json 失败，检查 api 目录权限'; $flashBad = true;
        }
    }

    // 上传背景图 / 标志图
    if ($action === 'theme_img') {
        $slot = (string)($_POST['slot'] ?? 'background') === 'logo' ? 'logo' : 'background';
        $file = $_FILES['file'] ?? null;

        if (!$file || (int)($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            $err = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);
            $flash = $err === UPLOAD_ERR_INI_SIZE
                ? '图片超过服务器单次上传上限，先压小一点（建议 2MB 内、宽 1600 以内）'
                : '没收到图片，重新选一张再传';
            $flashBad = true;
        } elseif ((int)$file['size'] > 20 * 1024 * 1024) {
            $flash = '图片太大（上限 20MB），压一下再传'; $flashBad = true;
        } else {
            $info = @getimagesize($file['tmp_name']);
            if (!$info || !in_array((int)$info[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG], true)) {
                $flash = '只收 JPG / PNG 图片'; $flashBad = true;
            } else {
                $ext  = (int)$info[2] === IMAGETYPE_PNG ? 'png' : 'jpg';
                $name = 'theme-' . ($slot === 'logo' ? 'logo' : 'bg') . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(3)) . '.' . $ext;
                $dest = LS_UPLOADS . '/' . $name;

                if (@move_uploaded_file($file['tmp_name'], $dest)) {
                    @chmod($dest, 0644);
                    $t = ls_theme_read();
                    ls_theme_unlink((string)$t[$slot]);          // 删掉上一张，别把站点塞满
                    $t[$slot] = 'api/files/' . $name;
                    $t['version'] = (int)$t['version'] + 1;
                    if (ls_theme_write($t)) {
                        $flash = ($slot === 'logo' ? '标志图' : '背景图') . ' 已换好（第 ' . (int)$t['version'] . ' 版），'
                               . 'App 下次进卡密页自动拉这张 · ' . human_size((int)$file['size']);
                    } else {
                        $flash = '图片传上去了，但写 api/license-theme.json 失败，检查 api 目录权限'; $flashBad = true;
                    }
                } else {
                    $flash = '保存失败，api/files 目录不可写（宝塔里把属主设成 www、权限 755）'; $flashBad = true;
                }
            }
        }
    }

    // 清掉背景图 / 标志图
    if ($action === 'theme_img_clear') {
        $slot = (string)($_POST['slot'] ?? 'background') === 'logo' ? 'logo' : 'background';
        $t = ls_theme_read();
        ls_theme_unlink((string)$t[$slot]);
        $t[$slot] = '';
        $t['version'] = (int)$t['version'] + 1;
        $flash = ($slot === 'logo' ? '标志图已清掉，回到默认盾牌' : '背景图已清掉，回到启动视频定格那一版');
        if (!ls_theme_write($t)) { $flash = '写 api/license-theme.json 失败'; $flashBad = true; }
    }

    // 恢复出厂
    if ($action === 'theme_reset') {
        $old = ls_theme_read();
        ls_theme_unlink((string)$old['background']);
        ls_theme_unlink((string)$old['logo']);
        $t = ls_theme_default();
        $t['version'] = (int)$old['version'] + 1;
        if (ls_theme_write($t)) {
            $flash = '已恢复默认样式（第 ' . (int)$t['version'] . ' 版）';
        } else {
            $flash = '写 api/license-theme.json 失败'; $flashBad = true;
        }
    }

    // 上传：初始化
    if ($action === 'upload_init') {
        header('Content-Type: application/json; charset=utf-8');
        $name = safe_filename((string)($_POST['name'] ?? ''));
        $size = (int)($_POST['size'] ?? 0);
        $chunks = max(1, (int)($_POST['chunks'] ?? 1));
        $id = bin2hex(random_bytes(8));
        $meta = ['id' => $id, 'name' => $name, 'size' => $size, 'chunks' => $chunks,
                 'received' => 0, 'created' => time()];
        write_json(LS_TMP . '/' . $id . '.json', $meta);
        @touch(LS_TMP . '/' . $id . '.part');
        echo json_encode(['ok' => true, 'id' => $id], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 上传：收一片
    if ($action === 'upload_chunk') {
        header('Content-Type: application/json; charset=utf-8');
        $id = preg_replace('/[^a-f0-9]/', '', (string)($_POST['id'] ?? ''));
        $index = (int)($_POST['index'] ?? 0);
        $metaPath = LS_TMP . '/' . $id . '.json';
        $partPath = LS_TMP . '/' . $id . '.part';

        if ($id === '' || !is_file($metaPath)) {
            echo json_encode(['ok' => false, 'msg' => '上传会话失效，重新传'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        if (!isset($_FILES['chunk']) || (int)$_FILES['chunk']['error'] !== UPLOAD_ERR_OK) {
            echo json_encode(['ok' => false, 'msg' => '这一片没传上来（可能超过 php.ini 限制）'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $meta = read_json($metaPath, []);
        if ($index === 0) @file_put_contents($partPath, '');
        $data = (string)file_get_contents((string)$_FILES['chunk']['tmp_name']);
        if (@file_put_contents($partPath, $data, FILE_APPEND) === false) {
            echo json_encode(['ok' => false, 'msg' => '服务器写不进 data/tmp，检查权限'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $meta['received'] = (int)($meta['received'] ?? 0) + 1;
        write_json($metaPath, $meta);
        echo json_encode(['ok' => true, 'got' => $meta['received'], 'chunks' => $meta['chunks']],
            JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 上传：合并
    if ($action === 'upload_finish') {
        header('Content-Type: application/json; charset=utf-8');
        $id = preg_replace('/[^a-f0-9]/', '', (string)($_POST['id'] ?? ''));
        $metaPath = LS_TMP . '/' . $id . '.json';
        $partPath = LS_TMP . '/' . $id . '.part';
        if ($id === '' || !is_file($metaPath) || !is_file($partPath)) {
            echo json_encode(['ok' => false, 'msg' => '上传会话失效，重新传'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $meta = read_json($metaPath, []);
        $name = safe_filename((string)($meta['name'] ?? 'file'));
        $dest = LS_UPLOADS . '/' . $name;
        if (is_file($dest)) {
            $ext = pathinfo($name, PATHINFO_EXTENSION);
            $stem = pathinfo($name, PATHINFO_FILENAME);
            $name = $stem . '-' . date('mdHis') . ($ext !== '' ? '.' . $ext : '');
            $dest = LS_UPLOADS . '/' . $name;
        }
        $ok = @rename($partPath, $dest);
        if (!$ok) $ok = @copy($partPath, $dest) && @unlink($partPath);
        @unlink($metaPath);
        if (!$ok) {
            echo json_encode(['ok' => false, 'msg' => '合并失败，检查 api/files 目录权限'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        echo json_encode([
            'ok' => true,
            'name' => $name,
            'size' => (int)@filesize($dest),
            'url' => base_url() . '/api/files/' . rawurlencode($name),
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 删除文件
    if ($action === 'file_delete') {
        $name = safe_filename((string)($_POST['name'] ?? ''));
        $path = LS_UPLOADS . '/' . $name;
        if ($name !== '' && is_file($path)) {
            @unlink($path);
            $flash = '已删除文件 ' . $name;
        }
    }

    // 发布清单
    if ($action === 'publish') {
        $version = trim((string)($_POST['version'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));
        $picked = $_POST['picked'] ?? [];
        $extraRemove = trim((string)($_POST['remove'] ?? ''));
        $ipa = trim((string)($_POST['ipa'] ?? ''));

        if ($version === '' || !is_array($picked) || count($picked) === 0) {
            $flash = '版本号和要带的文件都不能空'; $flashBad = true;
        } else {
            $items = [];
            foreach ($picked as $n) {
                $name = safe_filename((string)$n);
                $path = LS_UPLOADS . '/' . $name;
                if (!is_file($path)) continue;
                $items[] = [
                    'name' => $name,
                    'size' => (int)filesize($path),
                    'sha256' => hash_file('sha256', $path),
                    'url' => 'files/' . rawurlencode($name),
                ];
            }
            if (count($items) === 0) {
                $flash = '选的文件都不在磁盘上，重新传一次'; $flashBad = true;
            } else {
                $old = read_json(LS_MANIFEST, []);
                $oldNames = array_map(fn($f) => (string)($f['name'] ?? ''), $old['files'] ?? []);
                $newNames = array_map(fn($f) => (string)$f['name'], $items);
                $autoRemove = array_values(array_filter(array_diff($oldNames, $newNames), fn($n) => $n !== ''));

                foreach (preg_split('/[\s,，]+/u', $extraRemove) ?: [] as $extra) {
                    $extra = trim((string)$extra);
                    if ($extra === '') continue;
                    $extra = safe_filename($extra);
                    if (!in_array($extra, $autoRemove, true)) $autoRemove[] = $extra;
                }

                $manifest = [
                    'version' => $version,
                    'notes' => $notes,
                    'published' => gmdate('Y-m-d\TH:i:s\Z'),
                    'files' => $items,
                ];
                if ($ipa !== '') $manifest['ipa'] = $ipa;
                if (count($autoRemove) > 0) $manifest['remove'] = array_values($autoRemove);

                if (write_json(LS_MANIFEST, $manifest)) {
                    $flash = '已发布 ' . $version . '：' . count($items) . ' 个文件'
                        . (count($autoRemove) ? '，自动清理旧包 ' . count($autoRemove) . ' 个' : '');
                } else {
                    $flash = '写 api/manifest.json 失败，检查 api 目录权限'; $flashBad = true;
                }
            }
        }
    }

    // 接口自检
    if ($action === 'selftest') {
        header('Content-Type: application/json; charset=utf-8');
        $reach = rtrim(base_url(), '/') . '/api/verify.php';
        $ctx = stream_context_create(['http' => ['timeout' => 8, 'ignore_errors' => true]]);
        $resp = @file_get_contents($reach . '?code=__SELFTEST__&device=selftest', false, $ctx);
        echo json_encode([
            'ok' => $resp !== false,
            'endpoint' => $reach,
            'reply' => $resp === false ? '接口打不开' : mb_substr((string)$resp, 0, 200),
            'file_exists' => is_file(LS_VERIFY),
            'writable' => is_writable(LS_DATA),
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

// ---------------- 列表数据 ----------------

$licenses = read_json(LS_LICENSE, []);
krsort($licenses);

$search = trim((string)($_GET['q'] ?? ''));
$filter = (string)($_GET['st'] ?? 'all');
$rows = [];
$stat = ['all' => 0, 'valid' => 0, 'unused' => 0, 'expired' => 0, 'disabled' => 0, 'forever' => 0];
foreach ($licenses as $code => $item) {
    if (!is_array($item)) continue;
    $state = lic_state($item);
    $stat['all']++;
    if (isset($stat[$state])) $stat[$state]++;

    if ($filter !== 'all' && $state !== $filter) continue;
    if ($search !== '') {
        $hay = $code . ' ' . (string)($item['note'] ?? '') . ' ' . (string)($item['plan'] ?? '')
             . ' ' . implode(' ', (array)($item['devices'] ?? []));
        if (mb_stripos($hay, $search) === false) continue;
    }
    $rows[] = ['code' => (string)$code] + $item + ['_state' => $state];
}

$files = [];
foreach (glob(LS_UPLOADS . '/*') ?: [] as $f) {
    if (!is_file($f)) continue;
    $base = basename($f);
    if ($base === 'index.html' || $base === '.htaccess') continue;
    $files[] = [
        'name' => $base,
        'size' => (int)filesize($f),
        'mtime' => (int)filemtime($f),
        'url' => base_url() . '/api/files/' . rawurlencode($base),
    ];
}
usort($files, fn($a, $b) => $b['mtime'] <=> $a['mtime']);

$manifest = read_json(LS_MANIFEST, []);
$publishedNames = array_map(fn($f) => (string)($f['name'] ?? ''), (array)($manifest['files'] ?? []));
$lastMade = $_SESSION['last_made'] ?? [];
unset($_SESSION['last_made']);

$verifyURL = rtrim(base_url(), '/') . '/api/verify.php';

// 第一次打开后台就把默认样式落成文件，App 那边一上来就有东西可拉，不会 404
if (!is_file(LS_THEME)) {
    ls_theme_write(ls_theme_default());
}

$theme = ls_theme_read();
$themeURL = rtrim(base_url(), '/') . '/api/license-theme.json';
$themeBgURL = $theme['background'] !== '' ? rtrim(base_url(), '/') . '/' . ltrim((string)$theme['background'], '/') : '';
$themeLogoURL = $theme['logo'] !== '' ? rtrim(base_url(), '/') . '/' . ltrim((string)$theme['logo'], '/') : '';
$nowText = date('Y-m-d H:i');
$serverOk = is_writable(LS_DATA) && is_writable(LS_UPLOADS);
$chunkHint = human_size(max(LS_CHUNK_MIN, 2 * 1024 * 1024));
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>浪神 · 控制台</title>
<style>
  :root{
    --bg:#04090b; --bg2:#061214; --card:#0a1614; --card2:#0c1c1a;
    --line:#15342c; --line2:#1d4a3d;
    --fg:#e6fff4; --dim:#78a094; --acc:#38f5a5; --acc2:#19c8e8;
    --warn:#f0c53a; --bad:#ff6b6b; --ok:#38f5a5;
  }
  *{box-sizing:border-box}
  body{
    margin:0;padding:16px 14px 60px;background:
      radial-gradient(1100px 500px at 12% -10%,rgba(56,245,165,.10),transparent 60%),
      radial-gradient(900px 500px at 100% 0%,rgba(25,200,232,.08),transparent 55%),
      var(--bg);
    color:var(--fg);
    font:15px/1.55 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft Yahei",sans-serif;
    -webkit-text-size-adjust:100%;
  }
  .wrap{max-width:1040px;margin:0 auto}
  a{color:var(--acc2);text-decoration:none}
  .topbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:6px}
  .brand{font-size:19px;font-weight:800;letter-spacing:.5px;display:flex;align-items:center;gap:8px}
  .dot{width:9px;height:9px;border-radius:50%;background:var(--acc);
       box-shadow:0 0 10px var(--acc),0 0 22px rgba(56,245,165,.6)}
  .meta{font-size:11.5px;color:var(--dim);margin-left:auto}
  .logout{font-size:12px;color:var(--dim);border:1px solid var(--line);padding:5px 10px;border-radius:8px}
  .sub{font-size:12px;color:var(--dim);margin:4px 0 14px}
  .card{
    background:linear-gradient(180deg,var(--card2),var(--card));
    border:1px solid var(--line);border-radius:16px;padding:15px;margin-bottom:13px;
    box-shadow:0 0 0 1px rgba(56,245,165,.03),0 10px 30px -18px rgba(0,0,0,.9);
  }
  .card h2{font-size:13.5px;margin:0 0 12px;color:var(--acc);letter-spacing:.6px;
           display:flex;align-items:center;gap:8px}
  .card h2 .n{background:rgba(56,245,165,.14);color:var(--acc);border-radius:7px;
              font-size:11px;padding:2px 7px;font-weight:700}
  label{display:block;font-size:11.5px;color:var(--dim);margin:0 0 5px}
  input[type=text],input[type=password],input[type=number],input[type=date],select,textarea{
    width:100%;padding:10px 12px;border-radius:10px;border:1px solid var(--line);
    background:#05100f;color:var(--fg);font-size:14px;outline:none;font-family:inherit;
  }
  input:focus,select:focus,textarea:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(56,245,165,.10)}
  textarea{resize:vertical;min-height:70px}
  .row{margin-bottom:11px}
  .grid2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
  .grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
  @media(max-width:560px){.grid2,.grid3{grid-template-columns:1fr}}
  button{
    cursor:pointer;border:0;border-radius:10px;padding:11px 18px;font-size:14px;font-weight:800;
    background:linear-gradient(90deg,var(--acc),var(--acc2));color:#03120d;font-family:inherit;
    letter-spacing:.3px;
  }
  button:active{opacity:.85}
  button:disabled{opacity:.45;cursor:not-allowed}
  button.ghost{background:#0d1f1c;color:var(--fg);border:1px solid var(--line2);font-weight:700}
  button.mini{padding:5px 7px;font-size:11px;border-radius:7px;font-weight:700;white-space:nowrap}
  button.mini.danger{background:#2a1417;color:#ff9d9d;border:1px solid #46222a}
  button.mini.on{background:#12332a;color:var(--acc);border:1px solid #1e5643}
  .flash{padding:11px 14px;border-radius:11px;margin-bottom:13px;font-size:13px;
         background:#07281e;color:#8bf0c4;border:1px solid #15483a}
  .flash.bad{background:#2a1214;color:#ff9b9b;border-color:#482023}
  .tabs{display:flex;gap:8px;margin:2px 0 14px;overflow-x:auto;padding-bottom:2px}
  .tabs button{
    background:#081512;color:var(--dim);border:1px solid var(--line);font-weight:700;
    font-size:13px;padding:9px 16px;border-radius:999px;white-space:nowrap;
  }
  .tabs button.on{background:rgba(56,245,165,.12);color:var(--acc);border-color:var(--line2);
                  box-shadow:0 0 14px -4px rgba(56,245,165,.5)}
  .stats{display:grid;grid-template-columns:repeat(5,1fr);gap:8px;margin-bottom:14px}
  @media(max-width:560px){.stats{grid-template-columns:repeat(3,1fr)}}
  .stat{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:10px}
  .stat .v{font-size:19px;font-weight:800;letter-spacing:.5px}
  .stat .k{font-size:11px;color:var(--dim)}
  .stat.v .v{color:var(--acc)}
  .stat.u .v{color:var(--acc2)}
  .stat.e .v{color:var(--warn)}
  .stat.d .v{color:var(--bad)}
  table{width:100%;border-collapse:collapse;font-size:12.5px}
  th,td{text-align:left;padding:9px 8px;border-bottom:1px solid #0f2822;vertical-align:middle}
  th{color:var(--dim);font-weight:600;font-size:11px;letter-spacing:.4px;white-space:nowrap}
  td.code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;color:var(--acc)}
  .tag{display:inline-block;font-size:10.5px;padding:2px 8px;border-radius:999px;font-weight:700}
  .tag.valid{background:#0e2c22;color:var(--ok)}
  .tag.unused{background:#0d2331;color:var(--acc2)}
  .tag.expired{background:#2c2410;color:var(--warn)}
  .tag.disabled{background:#2a1417;color:var(--bad)}
  .tag.forever{background:#1b1330;color:#b79cff}
  .tbl-wrap{overflow-x:auto;margin:0 -4px}
  td.note{max-width:170px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
  td.exp{white-space:nowrap}
  .ops{display:flex;gap:5px;flex-wrap:wrap}
  .hint{font-size:11.5px;color:var(--dim);margin-top:9px;line-height:1.65}
  .hint code{background:#06120f;border:1px solid var(--line);padding:1px 5px;border-radius:5px;
             font-size:11px;color:var(--acc)}
  .drop{border:2px dashed var(--line2);border-radius:14px;padding:24px 14px;text-align:center;
        color:var(--dim);font-size:13px;transition:.15s;cursor:pointer}
  .drop.on{border-color:var(--acc);color:var(--acc);background:rgba(56,245,165,.06)}
  .queue{margin-top:12px;display:flex;flex-direction:column;gap:9px}
  .qitem{background:#061412;border:1px solid var(--line);border-radius:10px;padding:9px 11px}
  .qhead{display:flex;gap:8px;font-size:12px;margin-bottom:6px}
  .qhead .nm{flex:1;word-break:break-all;color:var(--fg)}
  .qhead .st{color:var(--dim);white-space:nowrap}
  .bar{height:6px;border-radius:99px;background:#0c2620;overflow:hidden}
  .bar i{display:block;height:100%;width:0;border-radius:99px;
         background:linear-gradient(90deg,var(--acc),var(--acc2));transition:width .2s}
  .filelist{display:flex;flex-direction:column;gap:0}
  .frow{display:flex;align-items:center;gap:10px;padding:10px 2px;border-bottom:1px solid #0f2822}
  .frow:last-child{border-bottom:0}
  .frow .nm{flex:1;font-size:12.5px;word-break:break-all}
  .frow .sz{font-size:11px;color:var(--dim);white-space:nowrap}
  .chk{width:18px;height:18px;accent-color:#38f5a5;flex:0 0 auto}
  .mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px;
        color:var(--acc);word-break:break-all}
  .kv{display:flex;gap:10px;font-size:12.5px;padding:5px 0;border-bottom:1px solid #0f2822}
  .kv:last-child{border-bottom:0}
  .kv .k{color:var(--dim);width:96px;flex:0 0 auto}
  .kv .v{flex:1;word-break:break-all}
  .switch{display:flex;align-items:center;gap:9px;font-size:13px}
  .switch input{width:20px;height:20px;accent-color:#38f5a5}
  .hide{display:none!important}
  .made{background:#06120f;border:1px dashed var(--line2);border-radius:10px;padding:10px;
         font-family:ui-monospace,Menlo,monospace;font-size:12px;color:var(--acc);
         white-space:pre-wrap;word-break:break-all;margin-top:9px}
  .center{max-width:420px;margin:8vh auto 0}
  .big{font-size:22px;font-weight:800;margin:0 0 4px}
</style>
</head>
<body>
<div class="wrap">

<?php if ($setupNeeded): ?>
  <div class="center">
    <div class="brand"><span class="dot"></span>浪神 · 控制台</div>
    <div class="sub">第一次使用，先设一个后台口令（至少 6 位）</div>
    <?php if ($flash): ?><div class="flash <?= $flashBad ? 'bad' : '' ?>"><?= h($flash) ?></div><?php endif; ?>
    <div class="card">
      <form method="post">
        <input type="hidden" name="action" value="setup">
        <div class="row"><label>设置口令</label><input type="password" name="password" autofocus autocomplete="new-password"></div>
        <div class="row"><label>再输一次</label><input type="password" name="password2" autocomplete="new-password"></div>
        <button type="submit" style="width:100%">保存并进入</button>
      </form>
      <div class="hint">口令存在 <code>data/config.json</code>（哈希，不是明文）。忘了就把这个文件删掉重设。</div>
    </div>
  </div>

<?php elseif (!$logged): ?>
  <div class="center">
    <div class="brand"><span class="dot"></span>浪神 · 控制台</div>
    <div class="sub">只有拿得到口令的人能进来</div>
    <?php if ($flash): ?><div class="flash <?= $flashBad ? 'bad' : '' ?>"><?= h($flash) ?></div><?php endif; ?>
    <div class="card">
      <form method="post">
        <input type="hidden" name="action" value="login">
        <div class="row"><label>口令</label><input type="password" name="password" autofocus autocomplete="current-password"></div>
        <button type="submit" style="width:100%">进入</button>
      </form>
    </div>
  </div>

<?php else: ?>

  <div class="topbar">
    <div class="brand"><span class="dot"></span>浪神 · 控制台</div>
    <div class="meta"><?= h($nowText) ?> · 目录可写 <?= $serverOk ? '正常' : '异常' ?></div>
    <a class="logout" href="?action=logout">退出</a>
  </div>
  <div class="sub">卡密验证接口：<span class="mono"><?= h($verifyURL) ?></span></div>

  <?php if ($flash): ?><div class="flash <?= $flashBad ? 'bad' : '' ?>"><?= h($flash) ?></div><?php endif; ?>
  <?php if (!$serverOk): ?>
    <div class="flash bad">api/files 或 data 目录不可写，上传和发布都会失败。在宝塔里把站点目录权限设成 755、属主 www。</div>
  <?php endif; ?>

  <div class="stats">
    <div class="stat v"><div class="v"><?= (int)$stat['valid'] ?></div><div class="k">有效</div></div>
    <div class="stat u"><div class="v"><?= (int)$stat['unused'] ?></div><div class="k">未激活</div></div>
    <div class="stat e"><div class="v"><?= (int)$stat['expired'] ?></div><div class="k">已到期</div></div>
    <div class="stat d"><div class="v"><?= (int)$stat['disabled'] ?></div><div class="k">已停用</div></div>
    <div class="stat"><div class="v"><?= (int)$stat['all'] ?></div><div class="k">全部</div></div>
  </div>

  <div class="tabs">
    <button class="on" data-tab="lic">卡密</button>
    <button data-tab="files">文件</button>
    <button data-tab="pub">发布</button>
    <button data-tab="theme">卡密窗口</button>
    <button data-tab="set">设置</button>
  </div>

  <!-- ================= 卡密 ================= -->
  <section id="tab-lic">
    <div class="card">
      <h2><span class="n">1</span>生成卡密</h2>
      <form method="post" id="genform">
        <input type="hidden" name="action" value="gen">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <div class="grid3">
          <div class="row">
            <label>数量（1–500）</label>
            <input type="number" name="count" value="1" min="1" max="500">
          </div>
          <div class="row">
            <label>有效期</label>
            <select name="duration" id="durSel">
              <option value="days">按天数</option>
              <option value="date">指定到期日期</option>
              <option value="forever">永久</option>
            </select>
          </div>
          <div class="row">
            <label>开始算时间</label>
            <select name="start_from">
              <option value="first">首次激活起算（推荐）</option>
              <option value="now">生成即起算</option>
            </select>
          </div>
        </div>
        <div class="grid3">
          <div class="row" id="daysRow">
            <label>天数</label>
            <input type="number" name="days" value="30" min="1" max="36500">
          </div>
          <div class="row hide" id="dateRow">
            <label>到期日期（当天 23:59 失效）</label>
            <input type="date" name="date" value="<?= h(date('Y-m-d', time() + 30 * 86400)) ?>">
          </div>
          <div class="row">
            <label>套餐名（可空）</label>
            <input type="text" name="plan" placeholder="月卡 / 季卡 / 永久">
          </div>
          <div class="row">
            <label>备注（可空）</label>
            <input type="text" name="note" placeholder="卖给谁 / 渠道">
          </div>
        </div>
        <button type="submit">生成</button>
      </form>

      <?php if (count($lastMade) > 0): ?>
        <div class="made" id="madeBox"><?= h(implode("\n", $lastMade)) ?></div>
        <div style="margin-top:9px;display:flex;gap:8px;flex-wrap:wrap">
          <button type="button" class="ghost mini" onclick="copyText(document.getElementById('madeBox').innerText,this)">复制这批卡密</button>
          <span class="hint" style="margin:0">刚生成的这批已存好，刷新也不会丢</span>
        </div>
      <?php endif; ?>
      <div class="hint">
        格式 <code>LS-XXXX-XXXX-XXXX</code>，去掉了容易看错的 I O 0 1。<br>
        选「首次激活起算」的话，卡密在用户第一次验证时才开始倒计时，卖出去放着也不亏。
      </div>
    </div>

    <div class="card">
      <h2><span class="n">2</span>卡密列表</h2>
      <form method="get" class="grid2" style="margin-bottom:12px">
        <div class="row" style="margin:0">
          <input type="text" name="q" value="<?= h($search) ?>" placeholder="搜卡密 / 备注 / 设备号">
        </div>
        <div class="row" style="margin:0;display:flex;gap:8px">
          <select name="st">
            <option value="all" <?= $filter === 'all' ? 'selected' : '' ?>>全部状态</option>
            <option value="valid" <?= $filter === 'valid' ? 'selected' : '' ?>>有效</option>
            <option value="unused" <?= $filter === 'unused' ? 'selected' : '' ?>>未激活</option>
            <option value="expired" <?= $filter === 'expired' ? 'selected' : '' ?>>已到期</option>
            <option value="disabled" <?= $filter === 'disabled' ? 'selected' : '' ?>>已停用</option>
            <option value="forever" <?= $filter === 'forever' ? 'selected' : '' ?>>永久</option>
          </select>
          <button type="submit" class="ghost">筛选</button>
        </div>
      </form>

      <?php if (count($rows) === 0): ?>
        <div class="hint">还没有卡密，上面生成一批。</div>
      <?php else: ?>
      <form method="post" id="bulkform">
        <input type="hidden" name="action" value="bulk">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <div class="tbl-wrap">
        <table>
          <thead>
            <tr>
              <th style="width:26px"><input type="checkbox" class="chk" id="checkAll"></th>
              <th>卡密</th><th>状态</th><th>到期</th><th>设备</th><th>备注</th><th>操作</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($rows as $r): $st = $r['_state']; $devs = (array)($r['devices'] ?? []); ?>
            <tr>
              <td><input type="checkbox" class="chk rowchk" name="codes[]" value="<?= h($r['code']) ?>"></td>
              <td class="code"><?= h($r['code']) ?></td>
              <td><span class="tag <?= h($st) ?>"><?= h(lic_state_text($r)) ?></span></td>
              <td class="exp" style="font-size:11.5px;color:#a9c9bd"><?= h(lic_exp_text($r)) ?></td>
              <td style="font-size:11px;color:var(--dim)"><?= count($devs) === 0 ? '—' : h(implode(', ', array_map(fn($d) => mb_substr((string)$d, 0, 8), $devs))) ?></td>
              <td class="note" style="font-size:11.5px;color:var(--dim)"><?= h((string)($r['note'] ?? '')) ?><?= ($r['plan'] ?? '') !== '' ? ' · ' . h((string)$r['plan']) : '' ?></td>
              <td>
                <div class="ops">
                  <button type="button" class="mini <?= !empty($r['disabled']) ? '' : 'on' ?>"
                          data-act="toggle" data-code="<?= h($r['code']) ?>"><?= !empty($r['disabled']) ? '启用' : '停用' ?></button>
                  <?php if (count($devs) > 0): ?>
                  <button type="button" class="mini" data-act="unbind" data-code="<?= h($r['code']) ?>">解绑</button>
                  <?php endif; ?>
                  <button type="button" class="mini" data-act="copy" data-code="<?= h($r['code']) ?>">复制</button>
                  <button type="button" class="mini danger" data-act="delete" data-code="<?= h($r['code']) ?>">删</button>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:11px;align-items:center">
          <select name="op" style="width:auto;flex:1;min-width:130px">
            <option value="disable">批量停用</option>
            <option value="enable">批量启用</option>
            <option value="delete">批量删除</option>
          </select>
          <button type="submit" class="ghost" onclick="return confirmBulk()">执行</button>
          <span class="hint" style="margin:0">共 <?= count($rows) ?> 条</span>
        </div>
      </form>
      <?php endif; ?>
    </div>
  </section>

  <!-- ================= 文件 ================= -->
  <section id="tab-files" class="hide">
    <div class="card">
      <h2><span class="n">1</span>上传文件</h2>
      <div class="drop" id="drop">
        把文件拖进来，或点这里选（可多选）<br>
        <span style="font-size:11.5px">pak / sig / ipa / mp4 / zip 都行，单个多大都能传</span>
        <input type="file" id="fileinput" multiple style="display:none">
      </div>
      <div class="queue" id="queue"></div>
      <div class="hint">
        走的是分片上传：每片 <?= h($chunkHint) ?>，绕过 php.ini 的单次请求上限——上次「传不上去」就是卡在这儿。<br>
        传上去的文件放在 <code>api/files/</code>，可以直接下、也可以拿去发布。
      </div>
    </div>

    <div class="card">
      <h2><span class="n">2</span>已传的文件 <span class="n"><?= count($files) ?></span></h2>
      <?php if (count($files) === 0): ?>
        <div class="hint">还没有文件。</div>
      <?php else: ?>
        <div class="filelist">
        <?php foreach ($files as $f): ?>
          <div class="frow">
            <div class="nm"><?= h($f['name']) ?><br><span class="sz"><?= h(human_size($f['size'])) ?> · <?= h(date('m-d H:i', $f['mtime'])) ?></span></div>
            <button type="button" class="mini" onclick="copyText('<?= h($f['url']) ?>',this)">复制链接</button>
            <button type="button" class="mini danger" onclick="delFile('<?= h($f['name']) ?>')">删</button>
          </div>
        <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
  </section>

  <!-- ================= 发布 ================= -->
  <section id="tab-pub" class="hide">
    <div class="card">
      <h2><span class="n">现</span>线上清单</h2>
      <?php if (empty($manifest['version'])): ?>
        <div class="hint">还没发布过。App 端现在拉 <code>api/manifest.json</code> 会拿到空，点「检查更新」就是「已最新」。</div>
      <?php else: ?>
        <div class="kv"><div class="k">版本</div><div class="v"><?= h((string)$manifest['version']) ?></div></div>
        <div class="kv"><div class="k">发布</div><div class="v"><?= h((string)($manifest['published'] ?? '')) ?></div></div>
        <div class="kv"><div class="k">文件</div><div class="v"><?= h(implode('、', $publishedNames)) ?></div></div>
        <?php if (!empty($manifest['notes'])): ?>
        <div class="kv"><div class="k">说明</div><div class="v"><?= nl2br(h((string)$manifest['notes'])) ?></div></div>
        <?php endif; ?>
      <?php endif; ?>
    </div>

    <div class="card">
      <h2><span class="n">发</span>发布新版本</h2>
      <?php if (count($files) === 0): ?>
        <div class="hint">先去「文件」页传东西。</div>
      <?php else: ?>
      <form method="post">
        <input type="hidden" name="action" value="publish">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <div class="grid2">
          <div class="row">
            <label>版本号（换了 App 才认新）</label>
            <input type="text" name="version" placeholder="1.2.6" value="<?= h((string)($manifest['version'] ?? '')) ?>">
          </div>
          <div class="row">
            <label>要清掉的旧文件名（空格分隔，可空）</label>
            <input type="text" name="remove" placeholder="old.pak">
          </div>
        </div>
        <div class="row">
          <label>更新说明（App 里会显示）</label>
          <textarea name="notes" placeholder="这一版改了什么"><?= h((string)($manifest['notes'] ?? '')) ?></textarea>
        </div>
        <div class="row">
          <label>本版要带的文件（勾上）</label>
          <div class="filelist">
          <?php foreach ($files as $f): $isPub = in_array($f['name'], $publishedNames, true); ?>
            <div class="frow">
              <input type="checkbox" class="chk" name="picked[]" value="<?= h($f['name']) ?>" <?= $isPub ? 'checked' : '' ?>>
              <div class="nm"><?= h($f['name']) ?><br><span class="sz"><?= h(human_size($f['size'])) ?></span></div>
            </div>
          <?php endforeach; ?>
          </div>
        </div>
        <button type="submit">发布</button>
        <div class="hint">
          发布只写 <code>api/manifest.json</code>，文件原地不动。清单里没有的旧包会自动进 <code>remove</code>，App 导入时顺手删掉。<br>
          App 里内置地址是 <code>https://ek.x8iu.com</code>，清单就是 <code>/api/manifest.json</code>，所以后台必须放在站点根目录。
        </div>
      </form>
      <?php endif; ?>
    </div>
  </section>

  <!-- ================= 设置 ================= -->
  <section id="tab-set" class="hide">
    <div class="card">
      <h2><span class="n">1</span>卡密策略</h2>
      <form method="post">
        <input type="hidden" name="action" value="settings">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <div class="row">
          <label class="switch"><input type="checkbox" name="device_lock" <?= !empty($config['device_lock']) ? 'checked' : '' ?>> 一码一设备（关掉就能多台共用）</label>
        </div>
        <div class="row">
          <label>最多同时绑几台设备</label>
          <input type="number" name="max_devices" min="1" max="10" value="<?= (int)$config['max_devices'] ?>">
        </div>
        <div class="row">
          <label>换口令（不动就留空）</label>
          <input type="password" name="new_password" placeholder="至少 6 位" autocomplete="new-password">
        </div>
        <button type="submit">保存设置</button>
      </form>
    </div>

    <div class="card">
      <h2><span class="n">2</span>接口自检</h2>
      <div class="kv"><div class="k">验证地址</div><div class="v mono"><?= h($verifyURL) ?></div></div>
      <div class="kv"><div class="k">App 里填</div><div class="v mono"><?= h(rtrim(base_url(), '/')) ?></div></div>
      <div class="kv"><div class="k">清单地址</div><div class="v mono"><?= h(rtrim(base_url(), '/')) ?>/api/manifest.json</div></div>
      <div style="margin-top:11px;display:flex;gap:8px;flex-wrap:wrap">
        <button type="button" class="ghost" onclick="selftest()">跑一遍自检</button>
        <button type="button" class="ghost" onclick="copyText('<?= h(rtrim(base_url(), '/')) ?>')">复制地址</button>
      </div>
      <div id="selfout" class="made hide"></div>
      <div class="hint">
        PHP 版本 <?= h(PHP_VERSION) ?> · 上传上限 <?= h((string)ini_get('upload_max_filesize')) ?> ·
        POST 上限 <?= h((string)ini_get('post_max_size')) ?>（分片上传不受这个限制）<br>
        接口返回 <code>{"ok":false,"msg":"卡密不存在，请核对后重试"}</code> 这种就说明通了。
      </div>
    </div>

    <div class="card">
      <h2><span class="n">3</span>数据在哪</h2>
      <div class="kv"><div class="k">卡密</div><div class="v mono">data/licenses.json</div></div>
      <div class="kv"><div class="k">口令</div><div class="v mono">data/config.json</div></div>
      <div class="kv"><div class="k">文件</div><div class="v mono">api/files/</div></div>
      <div class="kv"><div class="k">卡密数</div><div class="v"><?= (int)$stat['all'] ?> 张</div></div>
      <div class="hint">换服务器就把整个站点目录打包搬走，卡密和文件都在里面。备份 <code>data/</code> 和 <code>api/</code> 这两个目录就够了。</div>
    </div>
  <!-- ================= 卡密窗口 ================= -->
  <section id="tab-theme" class="hide">
    <style>
      .phoneWrap{display:flex;gap:18px;flex-wrap:wrap;align-items:flex-start;margin-top:6px}
      .phone{position:relative;width:264px;height:540px;border-radius:30px;overflow:hidden;background:#05070c;
             border:1px solid rgba(140,170,200,.28);box-shadow:0 18px 44px rgba(0,0,0,.45);flex:0 0 auto}
      .pvBg{position:absolute;inset:0;background-size:cover;background-position:center;background-color:#0a1220}
      .pvMask{position:absolute;inset:0;background:linear-gradient(rgba(0,0,0,.34),rgba(0,0,0,.62) 55%,rgba(0,0,0,.92))}
      .pvBox{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;
             padding:18px;text-align:center;color:#fff}
      .pvLogo{width:56px;height:64px;border-radius:14px;display:flex;align-items:center;justify-content:center;
              font-size:24px;font-weight:800;color:#fff;overflow:hidden;margin-bottom:10px}
      .pvLogo img{width:100%;height:100%;object-fit:contain}
      .pvTitle{font-size:23px;font-weight:900;letter-spacing:.5px}
      .pvSub{font-size:10px;opacity:.6;margin-top:5px}
      .pvSection{font-size:11px;font-weight:700;opacity:.72;margin-top:18px}
      .pvFieldLabel{font-size:9px;opacity:.66;margin-top:10px;align-self:flex-start;margin-left:6px}
      .pvInput{width:100%;margin-top:5px;height:34px;border-radius:18px;background:rgba(255,255,255,.95);
               display:flex;align-items:center;padding:0 12px;font-size:10px;font-weight:600}
      .pvBtn{width:100%;margin-top:12px;height:36px;border-radius:18px;display:flex;align-items:center;justify-content:center;
             font-size:11.5px;font-weight:800;color:#fff}
      .pvFooter{font-size:9px;opacity:.45;margin-top:12px}
      .pvCopy{position:absolute;bottom:14px;left:0;right:0;font-size:8px;opacity:.34}
      .swatchRow{display:flex;gap:14px;flex-wrap:wrap}
      .swatchRow .row{min-width:130px}
      input[type=color]{width:100%;height:38px;padding:2px;border-radius:8px;border:1px solid rgba(140,170,200,.28);background:transparent}
      .imgPrev{width:100%;max-height:150px;object-fit:cover;border-radius:10px;border:1px solid rgba(140,170,200,.22);margin-top:8px}
    </style>

    <div class="card">
      <h2><span class="n">现</span>现在 App 里长这样</h2>
      <div class="hint">
        当前第 <b><?= (int)$theme['version'] ?></b> 版。App 每次进卡密页自动拉
        <code style="word-break:break-all"><?= h($themeURL) ?></code>，你在后台改完保存，用户下次打开就换了，不用重新发版、也不用重新编译。<br>
        拉不到（断网 / 服务器停了）就用 App 上次缓存的那套，不会把人挡在门外；一次都没拉到过就用内置默认样式。
      </div>
      <div class="phoneWrap">
        <div class="phone" id="pv">
          <div class="pvBg" id="pvBg" style="<?= $themeBgURL !== '' ? 'background-image:url(' . h($themeBgURL) . ')' : '' ?>"></div>
          <div class="pvMask" id="pvMask"></div>
          <div class="pvBox">
            <div class="pvLogo" id="pvLogo" style="background:<?= h((string)$theme['primary']) ?>;display:<?= (!empty($theme['showShield']) || $themeLogoURL !== '') ? 'flex' : 'none' ?>">
              <?php if ($themeLogoURL !== ''): ?>
                <img src="<?= h($themeLogoURL) ?>" alt="">
              <?php else: ?>
                ✓
              <?php endif; ?>
            </div>
            <div class="pvTitle" id="pvTitle"><?= h((string)$theme['title']) ?></div>
            <div class="pvSub" id="pvSub"><?= h((string)$theme['subtitle']) ?></div>
            <div class="pvSection" id="pvSection"><?= h((string)$theme['section']) ?></div>
            <div class="pvFieldLabel" id="pvFieldLabel"><?= h((string)$theme['fieldLabel']) ?></div>
            <div class="pvInput" id="pvInput" style="border-radius:<?= (int)$theme['corner'] - 1 ?>px">
              <span id="pvInputText" style="opacity:.55;color:<?= h((string)$theme['inputText']) ?>"><?= h((string)$theme['placeholder']) ?></span>
            </div>
            <div class="pvBtn" id="pvBtn" style="border-radius:<?= (int)$theme['corner'] ?>px"><?= h((string)$theme['button']) ?></div>
            <div class="pvFooter" id="pvFooter"><?= h((string)$theme['footer']) ?></div>
            <div class="pvCopy" id="pvCopy"><?= h((string)$theme['copyright']) ?></div>
          </div>
        </div>
        <div style="flex:1 1 260px;min-width:240px">
          <div class="kv"><div class="k">清单地址</div><div class="v mono" style="word-break:break-all"><?= h($themeURL) ?></div></div>
          <div class="kv"><div class="k">背景图</div><div class="v mono"><?= $theme['background'] !== '' ? h((string)$theme['background']) : '未设置（用启动视频定格）' ?></div></div>
          <div class="kv"><div class="k">标志图</div><div class="v mono"><?= $theme['logo'] !== '' ? h((string)$theme['logo']) : '未设置（用内置盾牌）' ?></div></div>
          <div class="kv"><div class="k">最近保存</div><div class="v"><?= h((string)($theme['updated'] ?? '还没改过')) ?></div></div>
        </div>
      </div>
    </div>

    <div class="card">
      <h2><span class="n">1</span>背景图 / 标志图</h2>
      <div class="grid2">
        <form method="post" enctype="multipart/form-data">
          <input type="hidden" name="action" value="theme_img">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="slot" value="background">
          <div class="row">
            <label>卡密窗口背景图（JPG / PNG）</label>
            <input type="file" name="file" accept="image/jpeg,image/png" required>
          </div>
          <div style="display:flex;gap:8px;flex-wrap:wrap">
            <button type="submit">上传背景图</button>
          </div>
          <?php if ($themeBgURL !== ''): ?>
            <img class="imgPrev" src="<?= h($themeBgURL) ?>" alt="">
          <?php endif; ?>
          <div class="hint">建议竖图（1242×2688 或 1080×1920），2MB 内最稳。手机铺满，iPad / 横屏自动改成「完整居中 + 模糊铺底」，不会拉变形。</div>
        </form>

        <div>
          <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="action" value="theme_img">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
            <input type="hidden" name="slot" value="logo">
            <div class="row">
              <label>顶部标志图（PNG 透明底最好）</label>
              <input type="file" name="file" accept="image/jpeg,image/png" required>
            </div>
            <button type="submit">上标志图</button>
            <?php if ($themeLogoURL !== ''): ?>
              <img class="imgPrev" src="<?= h($themeLogoURL) ?>" style="max-height:96px;object-fit:contain" alt="">
            <?php endif; ?>
            <div class="hint">不传就用内置那个盾牌勾。传了会自动盖掉盾牌。</div>
          </form>

          <form method="post" style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap">
            <input type="hidden" name="action" value="theme_img_clear">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
            <input type="hidden" name="slot" value="background">
            <button type="submit" class="ghost mini">清掉背景图</button>
          </form>
          <form method="post" style="margin-top:8px">
            <input type="hidden" name="action" value="theme_img_clear">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
            <input type="hidden" name="slot" value="logo">
            <button type="submit" class="ghost mini">清掉标志图</button>
          </form>
        </div>
      </div>
    </div>

    <form method="post">
      <input type="hidden" name="action" value="theme_save">
      <input type="hidden" name="csrf" value="<?= h($csrf) ?>">

      <div class="card">
        <h2><span class="n">2</span>文案</h2>
        <div class="grid2">
          <div class="row"><label>大标题</label><input type="text" name="title" value="<?= h((string)$theme['title']) ?>" maxlength="30"></div>
          <div class="row"><label>副标题</label><input type="text" name="subtitle" value="<?= h((string)$theme['subtitle']) ?>" maxlength="40"></div>
          <div class="row"><label>小标题（授权验证）</label><input type="text" name="section" value="<?= h((string)$theme['section']) ?>" maxlength="30"></div>
          <div class="row"><label>输入框上方文字</label><input type="text" name="fieldLabel" value="<?= h((string)$theme['fieldLabel']) ?>" maxlength="30"></div>
          <div class="row"><label>输入框占位文字</label><input type="text" name="placeholder" value="<?= h((string)$theme['placeholder']) ?>" maxlength="30"></div>
          <div class="row"><label>按钮文字</label><input type="text" name="button" value="<?= h((string)$theme['button']) ?>" maxlength="16"></div>
          <div class="row"><label>按钮下方提示</label><input type="text" name="footer" value="<?= h((string)$theme['footer']) ?>" maxlength="40"></div>
          <div class="row"><label>最底部版权</label><input type="text" name="copyright" value="<?= h((string)$theme['copyright']) ?>" maxlength="40"></div>
        </div>
        <div class="hint">留空不会清掉，按你上次的值保留。想改哪个填哪个。</div>
      </div>

      <div class="card">
        <h2><span class="n">3</span>配色与版式</h2>
        <div class="swatchRow">
          <div class="row"><label>主色（盾牌 / 按钮起点）</label><input type="color" name="primary" value="<?= h((string)$theme['primary']) ?>" data-pv="primary"></div>
          <div class="row"><label>深色（渐变终点 / 光标）</label><input type="color" name="secondary" value="<?= h((string)$theme['secondary']) ?>" data-pv="secondary"></div>
          <div class="row"><label>强调色（按钮右端）</label><input type="color" name="accent" value="<?= h((string)$theme['accent']) ?>" data-pv="accent"></div>
          <div class="row"><label>输入框文字色</label><input type="color" name="inputText" value="<?= h((string)$theme['inputText']) ?>" data-pv="inputText"></div>
        </div>
        <div class="grid2" style="margin-top:12px">
          <div class="row">
            <label>背景压暗（<span id="dimNow"><?= h(number_format((float)$theme['dim'], 2)) ?></span>，太白看不清字就加大）</label>
            <input type="range" name="dim" min="0.15" max="0.95" step="0.01" value="<?= h((string)$theme['dim']) ?>" data-pv="dim">
          </div>
          <div class="row">
            <label>圆角（<span id="cornerNow"><?= (int)$theme['corner'] ?></span>）</label>
            <input type="range" name="corner" min="8" max="40" step="1" value="<?= (int)$theme['corner'] ?>" data-pv="corner">
          </div>
        </div>
        <div class="row" style="margin-top:8px">
          <label class="switch"><input type="checkbox" name="showShield" <?= !empty($theme['showShield']) ? 'checked' : '' ?> data-pv="showShield"> 显示顶部盾牌（传了标志图会盖掉它）</label>
        </div>
        <div class="row">
          <label class="switch"><input type="checkbox" name="buttonGradient" <?= !empty($theme['buttonGradient']) ? 'checked' : '' ?> data-pv="buttonGradient"> 按钮用渐变（关掉 = 纯主色）</label>
        </div>
        <button type="submit">保存，App 下次进卡密页自动换</button>
      </div>
    </form>

    <div class="card">
      <h2><span class="n">4</span>恢复默认</h2>
      <form method="post" onsubmit="return confirm('恢复成内置那套（霓虹绿 + 启动视频定格 + 盾牌），背景图和标志图会一起清掉。确定？')">
        <input type="hidden" name="action" value="theme_reset">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <button type="submit" class="ghost">恢复默认样式</button>
      </form>
      <div class="hint">恢复后版本号照样 +1，App 下次进来就会退回默认那套。</div>
    </div>
  </section>

  <script>
  const CSRF = <?= json_encode($csrf) ?>;
  const VERIFY_URL = <?= json_encode($verifyURL) ?>;

  // ---- tab ----
  document.querySelectorAll('.tabs button').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.tabs button').forEach(b => b.classList.remove('on'));
      btn.classList.add('on');
      ['lic','files','pub','theme','set'].forEach(t => {
        document.getElementById('tab-' + t).classList.toggle('hide', t !== btn.dataset.tab);
      });
      window.scrollTo({top: 0, behavior: 'smooth'});
    });
  });

  // 地址后加 #theme / #files 之类，打开就直接落在那一页（收藏起来更快）
  (function () {
    const want = (location.hash || '').replace('#', '');
    if (!want) return;
    const btn = document.querySelector('.tabs button[data-tab="' + want + '"]');
    if (btn) btn.click();
  })();

  // ---- 时长选择 ----
  const durSel = document.getElementById('durSel');
  if (durSel) {
    const sync = () => {
      const v = durSel.value;
      document.getElementById('daysRow').classList.toggle('hide', v !== 'days');
      document.getElementById('dateRow').classList.toggle('hide', v !== 'date');
    };
    durSel.addEventListener('change', sync);
    sync();
  }

  // ---- 复制 ----
  function copyText(text, el) {
    const done = () => { if (el) { const old = el.innerText; el.innerText = '已复制'; setTimeout(() => el.innerText = old, 1200); } };
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text).then(done).catch(() => fallback());
    } else { fallback(); }
    function fallback() {
      const ta = document.createElement('textarea');
      ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
      document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); done(); } catch (e) { alert(text); }
      ta.remove();
    }
  }

  // ---- 行内操作 ----
  async function act(action, code, extra) {
    const fd = new FormData();
    fd.append('action', action);
    fd.append('code', code);
    fd.append('csrf', CSRF);
    if (extra) for (const k in extra) fd.append(k, extra[k]);
    const r = await fetch(location.pathname, {method: 'POST', body: fd});
    if (!r.ok) { alert('操作失败：' + r.status); return; }
    location.reload();
  }

  document.querySelectorAll('button[data-act]').forEach(btn => {
    btn.addEventListener('click', () => {
      const a = btn.dataset.act, code = btn.dataset.code;
      if (a === 'copy') { copyText(code, btn); return; }
      if (a === 'delete' && !confirm('删掉 ' + code + '？删了就找不回来')) return;
      act(a, code);
    });
  });

  // ---- 全选 + 批量 ----
  const checkAll = document.getElementById('checkAll');
  if (checkAll) {
    checkAll.addEventListener('change', () => {
      document.querySelectorAll('.rowchk').forEach(c => c.checked = checkAll.checked);
    });
  }
  function confirmBulk() {
    const n = document.querySelectorAll('.rowchk:checked').length;
    if (n === 0) { alert('先勾几条'); return false; }
    return confirm('对 ' + n + ' 张卡密执行？');
  }

  // ---- 上传（分片） ----
  const CHUNK = <?= (int)max(LS_CHUNK_MIN, 2 * 1024 * 1024) ?>;
  const drop = document.getElementById('drop');
  const fileinput = document.getElementById('fileinput');
  const queue = document.getElementById('queue');

  drop.addEventListener('click', () => fileinput.click());
  drop.addEventListener('dragover', e => { e.preventDefault(); drop.classList.add('on'); });
  drop.addEventListener('dragleave', () => drop.classList.remove('on'));
  drop.addEventListener('drop', e => {
    e.preventDefault(); drop.classList.remove('on');
    if (e.dataTransfer.files.length) handleFiles(e.dataTransfer.files);
  });
  fileinput.addEventListener('change', () => {
    if (fileinput.files.length) handleFiles(fileinput.files);
    fileinput.value = '';
  });

  function fmtSize(n) {
    if (n >= 1073741824) return (n / 1073741824).toFixed(2) + ' GB';
    if (n >= 1048576) return (n / 1048576).toFixed(1) + ' MB';
    if (n >= 1024) return (n / 1024).toFixed(1) + ' KB';
    return n + ' B';
  }

  async function handleFiles(files) {
    for (const file of Array.from(files)) {
      const item = document.createElement('div');
      item.className = 'qitem';
      item.innerHTML = '<div class="qhead"><span class="nm"></span><span class="st">准备中</span></div>' +
                       '<div class="bar"><i></i></div>';
      item.querySelector('.nm').textContent = file.name + ' · ' + fmtSize(file.size);
      queue.appendChild(item);
      try {
        await uploadOne(file, item);
      } catch (err) {
        item.querySelector('.st').textContent = '失败：' + err.message;
        item.querySelector('.st').style.color = '#ff9b9b';
      }
    }
    setTimeout(() => location.reload(), 900);
  }

  async function uploadOne(file, item) {
    const st = item.querySelector('.st');
    const bar = item.querySelector('.bar i');
    const total = Math.max(1, Math.ceil(file.size / CHUNK));

    const initFd = new FormData();
    initFd.append('action', 'upload_init');
    initFd.append('csrf', CSRF);
    initFd.append('name', file.name);
    initFd.append('size', file.size);
    initFd.append('chunks', total);
    const initRes = await fetch(location.pathname, {method: 'POST', body: initFd});
    const init = await initRes.json();
    if (!init.ok) throw new Error(init.msg || '初始化失败');

    for (let i = 0; i < total; i++) {
      const blob = file.slice(i * CHUNK, Math.min(file.size, (i + 1) * CHUNK));
      const fd = new FormData();
      fd.append('action', 'upload_chunk');
      fd.append('csrf', CSRF);
      fd.append('id', init.id);
      fd.append('index', i);
      fd.append('chunk', blob, 'blob');
      let ok = false, lastMsg = '';
      for (let attempt = 0; attempt < 3 && !ok; attempt++) {
        try {
          const r = await fetch(location.pathname, {method: 'POST', body: fd});
          const j = await r.json();
          ok = !!j.ok; lastMsg = j.msg || '';
        } catch (e) { lastMsg = e.message; }
        if (!ok) await new Promise(res => setTimeout(res, 400 * (attempt + 1)));
      }
      if (!ok) throw new Error(lastMsg || '第 ' + (i + 1) + ' 片没传上去');
      const pct = Math.round(((i + 1) / total) * 100);
      bar.style.width = pct + '%';
      st.textContent = pct + '% · ' + fmtSize(Math.min(file.size, (i + 1) * CHUNK));
    }

    st.textContent = '合并中…';
    const finFd = new FormData();
    finFd.append('action', 'upload_finish');
    finFd.append('csrf', CSRF);
    finFd.append('id', init.id);
    const finRes = await fetch(location.pathname, {method: 'POST', body: finFd});
    const fin = await finRes.json();
    if (!fin.ok) throw new Error(fin.msg || '合并失败');
    bar.style.width = '100%';
    st.textContent = '完成 · ' + fmtSize(fin.size);
  }

  async function delFile(name) {
    if (!confirm('删掉文件 ' + name + '？')) return;
    const fd = new FormData();
    fd.append('action', 'file_delete');
    fd.append('csrf', CSRF);
    fd.append('name', name);
    await fetch(location.pathname, {method: 'POST', body: fd});
    location.reload();
  }

  // ---- 自检 ----
  async function selftest() {
    const box = document.getElementById('selfout');
    box.classList.remove('hide');
    box.textContent = '正在测…';
    const fd = new FormData();
    fd.append('action', 'selftest');
    fd.append('csrf', CSRF);
    try {
      const r = await fetch(location.pathname, {method: 'POST', body: fd});
      const j = await r.json();
      box.textContent = '接口：' + j.endpoint + '\n' +
        '文件存在：' + (j.file_exists ? '是' : '否') + '\n' +
        'data 可写：' + (j.writable ? '是' : '否') + '\n' +
        '返回：' + j.reply;
    } catch (e) {
      box.textContent = '自检没跑通：' + e.message;
    }
  }

  // ---- 卡密窗口预览：改哪就跟着变哪 ----
  (function () {
    const q = id => document.getElementById(id);
    const scope = document.getElementById('tab-theme');
    if (!scope) return;

    const val = n => {
      const el = scope.querySelector('[name="' + n + '"]');
      return el ? el.value : '';
    };
    const on = n => {
      const el = scope.querySelector('[name="' + n + '"]');
      return el ? !!el.checked : false;
    };
    const setText = (id, v) => {
      const el = q(id);
      if (el && v !== '') el.textContent = v;
    };

    function pvSync() {
      const primary  = val('primary') || '#29EB85';
      const accent   = val('accent') || '#8F70F5';
      const ink      = val('inputText') || '#1A1A1A';
      const dim      = parseFloat(val('dim') || '0.62');
      const corner   = parseInt(val('corner') || '28', 10);

      setText('pvTitle', val('title'));
      setText('pvSub', val('subtitle'));
      setText('pvSection', val('section'));
      setText('pvFieldLabel', val('fieldLabel'));
      setText('pvInputText', val('placeholder'));
      setText('pvBtn', val('button'));
      setText('pvFooter', val('footer'));
      setText('pvCopy', val('copyright'));

      const btn = q('pvBtn');
      if (btn) {
        btn.style.borderRadius = corner + 'px';
        btn.style.background = on('buttonGradient')
          ? 'linear-gradient(90deg,' + primary + ',' + accent + ')'
          : primary;
      }
      const input = q('pvInput');
      if (input) input.style.borderRadius = Math.max(0, corner - 1) + 'px';
      const inputText = q('pvInputText');
      if (inputText) inputText.style.color = ink;

      const mask = q('pvMask');
      if (mask) {
        mask.style.background = 'linear-gradient(rgba(0,0,0,' + (dim * 0.55).toFixed(3) + '),'
          + 'rgba(0,0,0,' + dim.toFixed(3) + ') 55%,rgba(0,0,0,' + Math.min(0.96, dim * 1.42).toFixed(3) + '))';
      }

      const logo = q('pvLogo');
      if (logo) {
        logo.style.background = primary;
        const hasImg = !!logo.querySelector('img');
        logo.style.display = (on('showShield') || hasImg) ? 'flex' : 'none';
      }

      const dn = q('dimNow'), cn = q('cornerNow');
      if (dn) dn.textContent = dim.toFixed(2);
      if (cn) cn.textContent = corner;
    }

    scope.querySelectorAll('input').forEach(el => {
      el.addEventListener('input', pvSync);
      el.addEventListener('change', pvSync);
    });
    pvSync();
  })();
  </script>

<?php endif; ?>
</div>
</body>
</html>
