<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


session_start();
ob_start();

define('ROOT_PATH', dirname(__DIR__) . '/');

// ========== 独立JSON接口（无需后续加载）==========
// 授权激活/更换（必须在session检查之前，因为AJAX不经过include流程）
if (isset($_GET['act']) && $_GET['act'] === 'auth' && isset($_GET['action']) && $_GET['action'] === 'activate') {
    require_once dirname(__DIR__) . '/core/db/db.php';
    require_once dirname(__DIR__) . '/core/lib/license.php';
    require_once dirname(__DIR__) . '/core/lib/license_guard.php';
    require_once dirname(__DIR__) . '/core/lib/module_loader.php';
    $db = \Core\Db\DB::getInstance();
    header('Content-Type: application/json');
    $raw = file_get_contents('php://input');
    $payload = json_decode($raw, true) ?: [];
    $key = trim($payload['license_key'] ?? '');
    $domain = trim($payload['domain'] ?? '');
    if (empty($key)) {
        echo json_encode(['code' => 400, 'msg' => '授权KEY不能为空']);
        exit;
    }
    // 调用授权平台API验证
    $licenseCenterApi = 'http://yutou.wtbidc.cn/license-center/api.php';
    $ch = curl_init($licenseCenterApi . '?action=check');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['license_key' => $key, 'domain' => $domain]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $resp = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr = curl_error($ch);
    $curlErrno = curl_errno($ch);
    curl_close($ch);
    if (!$resp || $httpCode !== 200) {
        echo json_encode(['code' => 500, 'msg' => '无法连接到授权平台', 'debug' => ['http'=>$httpCode, 'curl_err'=>$curlErr, 'curl_errno'=>$curlErrno, 'resp'=>substr($resp,0,100)]]);
        exit;
    }
    $result = json_decode($resp, true);
    if (!isset($result['code']) || intval($result['code']) !== 200) {
        $errMsg = isset($result['msg']) ? $result['msg'] : '授权验证失败';
        echo json_encode(['code' => 403, 'msg' => $errMsg]);
        exit;
    }
    $level = isset($result['level']) ? intval($result['level']) : 1;
    $expireRaw = isset($result['expire']) ? $result['expire'] : null;
    // null = 永久授权，写入 NULL 而非 '0000-00-00'（strict mode 拒绝无效日期）
    $expireTime = (is_string($expireRaw) && !empty($expireRaw)) ? $expireRaw : null;
    $updateData = [
        'license_code' => $key,
        'license_domain' => $domain,
        'license_level' => $level,
        'license_expire' => $expireTime,
        'license_status' => 1,
        'update_time' => time()
    ];
    $existing = $db->fetch("SELECT id FROM {$db->table('license')} LIMIT 1");
    if ($existing) {
        $db->update('license', $updateData, 'id = ?', [$existing['id']]);
    } else {
        $updateData['create_time'] = time();
        $db->insert('license', $updateData);
    }
    $licenseObj = new \Core\Lib\License();
    $moduleLoader = new \Core\Lib\ModuleLoader($licenseObj);
    $moduleSync = $moduleLoader->syncAuthorizedModules();
    echo json_encode(['code' => 200, 'msg' => '激活成功！', 'level' => $level, 'module_sync' => $moduleSync]);
    exit;
}

if (isset($_GET['act']) && $_GET['act'] === 'auth' && isset($_GET['action']) && $_GET['action'] === 'reset') {
    require_once dirname(__DIR__) . '/core/db/db.php';
    $db = \Core\Db\DB::getInstance();
    header('Content-Type: application/json');

    $tbl = $db->table('license');
    $db->query("DELETE FROM {$tbl} WHERE 1=1");

    $freeCode = 'FREE-' . strtoupper(substr(md5($_SERVER['HTTP_HOST']), 0, 8));
    $siteId = 'EC' . date('Ymd') . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    $now = time();

    $db->insert('license', [
        'license_code' => $freeCode,
        'license_domain' => $domain,
        'license_level' => 1,
        'license_expire' => null,
        'site_id' => $siteId,
        'bind_count' => 1,
        'max_domains' => 1,
        'license_status' => 1,
        'create_time' => $now,
        'update_time' => $now,
    ]);

    echo json_encode(['code' => 200, 'msg' => '已恢复为当前域名的免费授权']);
    exit;
}

if (!isset($_SESSION['admin_id']) || empty($_SESSION['admin_id'])) {
    header('Location: /admin/login.php');
    exit;
}

require_once dirname(__DIR__) . '/core/db/db.php';
require_once dirname(__DIR__) . '/core/lib/license.php';
require_once dirname(__DIR__) . '/core/lib/license_guard.php';
require_once dirname(__DIR__) . '/core/lib/module_loader.php';
require_once dirname(__DIR__) . '/core/lib/template_loader.php';
require_once dirname(__DIR__) . '/core/lib/common.php';

$db = \Core\Db\DB::getInstance();
$license = new \Core\Lib\License();
$moduleLoader = new \Core\Lib\ModuleLoader($license);
$templateLoader = new \Core\Lib\TemplateLoader($license);

$act = isset($_GET['act']) ? $_GET['act'] : 'dashboard';

// Handle toggle action early (no HTML output)
if ($act === 'channel' && isset($_GET['action']) && $_GET['action'] === 'toggle') {
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $isShow = intval($_POST['is_show'] ?? 0);
    $db->update('channel', ['is_show' => $isShow, 'update_time' => time()], 'id = ?', [$id]);
    echo json_encode(['code' => 200, 'msg' => '更新成功']);
    exit;
}
if ($act === 'article' && isset($_GET['action']) && $_GET['action'] === 'toggle') {
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->update('article', ['status' => $status, 'update_time' => time()], 'id = ?', [$id]);
    echo json_encode(['code' => 200, 'msg' => '更新成功']);
    exit;
}
if ($act === 'product' && isset($_GET['action']) && $_GET['action'] === 'toggle') {
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->update('product', ['status' => $status, 'update_time' => time()], 'id = ?', [$id]);
    echo json_encode(['code' => 200, 'msg' => '更新成功']);
    exit;
}
if ($act === 'image' && isset($_GET['action']) && $_GET['action'] === 'toggle') {
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->update('image', ['status' => $status, 'update_time' => time()], 'id = ?', [$id]);
    echo json_encode(['code' => 200, 'msg' => '更新成功']);
    exit;
}
if ($act === 'download' && isset($_GET['action']) && $_GET['action'] === 'toggle') {
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status = intval($_POST['status'] ?? 0);
    $db->update('download', ['status' => $status, 'update_time' => time()], 'id = ?', [$id]);
    echo json_encode(['code' => 200, 'msg' => '更新成功']);
    exit;
}
if ($act === 'upload') {
    $csrfOk = verifyAdminCsrfToken();
    if (!$csrfOk) {
        $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
        if ($referer !== '' && $host !== '' && strpos($referer, $host) !== false && strpos($referer, '/admin/') !== false && isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id'])) {
            $csrfOk = true;
        }
    }
    if (!$csrfOk) {
        requireAdminCsrfToken(true);
    }
    require_once dirname(__DIR__) . '/core/lib/common.php';
    $uploadType = isset($_POST['upload_type']) ? $_POST['upload_type'] : 'image';
    if ($uploadType === 'video') {
        header('Content-Type: application/json');
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['file'])) {
            echo json_encode(['code' => 400, 'msg' => '没有上传文件']);
            exit;
        }
        $file = $_FILES['file'];
        if ($file['error'] !== UPLOAD_ERR_OK) {
            echo json_encode(['code' => 400, 'msg' => '文件上传失败']);
            exit;
        }
        $allowedExt = ['mp4', 'webm', 'ogg', 'avi', 'mov', 'mkv', 'wmv', 'flv'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt)) {
            echo json_encode(['code' => 400, 'msg' => '不支持的视频格式']);
            exit;
        }
        $uploadDir = dirname(__DIR__) . '/uploads/video/' . date('Ym') . '/';
        if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); }
        $newName = uniqid() . '_' . time() . '.' . $ext;
        $destPath = $uploadDir . $newName;
        if (move_uploaded_file($file['tmp_name'], $destPath)) {
            $siteUrl = rtrim(getSiteConfig('site_url', 'http://' . $_SERVER['HTTP_HOST']), '/');
            echo json_encode(['code' => 200, 'msg' => '上传成功', 'data' => ['url' => $siteUrl . '/uploads/video/' . date('Ym') . '/' . $newName]]);
        } else {
            echo json_encode(['code' => 500, 'msg' => '文件保存失败']);
        }
        exit;
    }
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $maxSize = 5 * 1024 * 1024;
    header('Content-Type: application/json');
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['file'])) {
        echo json_encode(['code' => 400, 'msg' => '没有上传文件']);
        exit;
    }
    $file = $_FILES['file'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['code' => 400, 'msg' => '文件上传失败']);
        exit;
    }
    if ($file['size'] > $maxSize) {
        echo json_encode(['code' => 400, 'msg' => '文件大小不能超过5MB']);
        exit;
    }
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    if (!in_array($mimeType, $allowedTypes)) {
        echo json_encode(['code' => 400, 'msg' => '只支持 JPG/PNG/GIF/WebP 格式']);
        exit;
    }
    $uploadDir = dirname(__DIR__) . '/uploads/' . date('Ymd') . '/';
    if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); }
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $newName = uniqid() . '_' . time() . '.' . strtolower($ext);
    $destPath = $uploadDir . $newName;
    if (move_uploaded_file($file['tmp_name'], $destPath)) {
        $siteUrl = rtrim(getSiteConfig('site_url', 'http://' . $_SERVER['HTTP_HOST']), '/');
        echo json_encode(['code' => 200, 'msg' => '上传成功', 'data' => ['url' => $siteUrl . '/uploads/' . date('Ymd') . '/' . $newName]]);
    } else {
        echo json_encode(['code' => 500, 'msg' => '文件保存失败']);
    }
    exit;
}
if ($act === 'template' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'switch_template' && !defined('YT_TEMPLATE_SWITCH_V2')) {
    define('YT_TEMPLATE_SWITCH_V2', true);
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $template_key = trim($_POST['template_key'] ?? '');
    if ($template_key === '') {
        echo json_encode(['code' => 400, 'msg' => '模板标识不能为空']);
        exit;
    }

    $templateInfo = $templateLoader->getRemoteTemplate($template_key);
    if (!is_array($templateInfo) && $template_key !== \Core\Lib\TemplateLoader::DEFAULT_TEMPLATE) {
        echo json_encode(['code' => 404, 'msg' => '授权平台中不存在该模板']);
        exit;
    }

    $syncResult = $templateLoader->ensureTemplateAvailable($template_key, is_array($templateInfo) ? $templateInfo : null);
    if (intval($syncResult['code'] ?? 500) !== 200) {
        echo json_encode($syncResult);
        exit;
    }

    $activateResult = $templateLoader->activateTemplate($template_key, $db);
    if (function_exists('addLog')) {
        addLog('切换模板: ' . $template_key);
    }

    $templateName = is_array($templateInfo) ? (string) ($templateInfo['name'] ?? $template_key) : $template_key;
    echo json_encode([
        'code' => 200,
        'msg' => '模板“' . $templateName . '”启用成功',
        'template' => $template_key,
        'sync' => $syncResult,
        'result' => $activateResult,
    ]);
    exit;
}
if ($act === 'template' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'switch_template') {
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $template_key = trim($_POST['template_key'] ?? '');
    if (empty($template_key)) {
        echo json_encode(['code' => 400, 'msg' => '模板标识不能为空']);
        exit;
    }
    // 检查当前站点授权级别
    $license = new \Core\Lib\License();
    $licenseInfo = $license->getStatus();
    $currentLevel = $licenseInfo['level'] ?? 1;
    // 从授权平台获取模板级别要求
    $apiBase = 'http://yutou.wtbidc.cn/license-center';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiBase . '/api.php?action=template_list');
    curl_setopt($ch, CURLOPT_TIMEOUT, 8);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['level' => $currentLevel]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $resp = curl_exec($ch);
    curl_close($ch);
    $levelNames = [1 => '免费版', 2 => '基础版', 3 => '专业版'];
    $templateInfo = null;
    if ($resp) {
        $result = json_decode($resp, true);
        if ($result && $result['code'] == 200) {
            foreach ($result['templates'] as $t) {
                if ($t['template_key'] === $template_key) {
                    $templateInfo = $t;
                    break;
                }
            }
        }
    }
    if (!$templateInfo) {
        // 模板在授权平台不存在
        echo json_encode(['code' => 400, 'msg' => '模板不存在于授权平台']);
        exit;
    }
    // 检查授权级别
    if (!$templateInfo['is_free'] && $templateInfo['required_level'] > $currentLevel) {
        echo json_encode(['code' => 403, 'msg' => '该模板需要【' . ($levelNames[$templateInfo['required_level']] ?? '更高版本') . '】才能使用，当前版本：' . ($levelNames[$currentLevel] ?? '未知')]);
        exit;
    }
    $templateDir = dirname(__DIR__) . '/template/' . $template_key;
    // 如果模板目录不存在，尝试从授权平台下载
    if (!is_dir($templateDir)) {
        $downloadUrl = $apiBase . '/api.php?action=template_download&key=' . urlencode($template_key);
        $zipData = @file_get_contents($downloadUrl);
        if ($zipData && strlen($zipData) > 0 && substr($zipData, 0, 4) === 'PK') {
            if (!is_dir($templateDir)) mkdir($templateDir, 0755, true);
            $zipFile = $templateDir . '/__download.zip';
            file_put_contents($zipFile, $zipData);
            $zip = new ZipArchive();
            if ($zip->open($zipFile) === true) {
                $zip->extractTo($templateDir);
                $zip->close();
                unlink($zipFile);
            } else {
                @unlink($zipFile);
                echo json_encode(['code' => 400, 'msg' => '模板包解压失败']);
                exit;
            }
        } else {
            echo json_encode(['code' => 400, 'msg' => '模板文件不存在于授权平台']);
            exit;
        }
    }
    $exists = $db->fetch("SELECT id FROM {$db->table('config')} WHERE config_key = 'site_template'");
    if ($exists) {
        $db->update('config', ['config_value' => $template_key], 'config_key = ?', ['site_template']);
    } else {
        $db->insert('config', ['config_key' => 'site_template', 'config_value' => $template_key, 'config_type' => 'text', 'config_group' => 'basic']);
    }
    echo json_encode(['code' => 200, 'msg' => '模板「' . $templateInfo['name'] . '」启用成功', 'template' => $template_key]);
    exit;
}
if ($act === 'template' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'install_template' && !defined('YT_TEMPLATE_INSTALL_V2')) {
    define('YT_TEMPLATE_INSTALL_V2', true);
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    echo json_encode([
        'code' => 403,
        'msg' => '已禁用本地离线模板安装，请通过模板中心在线授权下载模板',
    ]);
    exit;
}
if ($act === 'template' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'install_template') {
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $template_key = trim($_POST['template_key'] ?? '');
    if (empty($template_key)) {
        echo json_encode(['code' => 400, 'msg' => '模板标识不能为空']);
        exit;
    }
    if (!isset($_FILES['template_zip']) || $_FILES['template_zip']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['code' => 400, 'msg' => '没有上传文件或上传失败']);
        exit;
    }
    $uploadDir = dirname(__DIR__) . '/template/' . $template_key . '/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    // 清理旧模板文件
    if (is_dir($uploadDir)) {
        foreach (glob("$uploadDir*") as $f) {
            if (is_dir($f)) {
                foreach (glob("$f/*") as $sf) { @unlink($sf); }
                @rmdir($f);
            } else {
                @unlink($f);
            }
        }
    }
    // 解压
    $zipFile = $uploadDir . '__upload.zip';
    if (!move_uploaded_file($_FILES['template_zip']['tmp_name'], $zipFile)) {
        echo json_encode(['code' => 500, 'msg' => '文件保存失败']);
        exit;
    }
    $zip = new ZipArchive();
    if ($zip->open($zipFile) === true) {
        $zip->extractTo($uploadDir);
        $zip->close();
        unlink($zipFile);
    } else {
        unlink($zipFile);
        echo json_encode(['code' => 400, 'msg' => 'zip文件解压失败']);
        exit;
    }
    // 保存到配置
    $exists = $db->fetch("SELECT id FROM {$db->table('config')} WHERE config_key = 'site_template'");
    if ($exists) {
        $db->update('config', ['config_value' => $template_key], 'config_key = ?', ['site_template']);
    } else {
        $db->insert('config', ['config_key' => 'site_template', 'config_value' => $template_key, 'config_type' => 'text', 'config_group' => 'basic']);
    }
    echo json_encode(['code' => 200, 'msg' => '模板安装并启用成功', 'template' => $template_key]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>企业管理</title>
    <style>
    *{margin:0;padding:0;box-sizing:border-box;}
    body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;font-size:14px;color:#334155;background:#f1f5f9;line-height:1.6;}
    .page-container{max-width:1400px;margin:0 auto;padding:20px;}
    .page-header{background:#fff;border-radius:8px;padding:20px 24px;margin-bottom:20px;display:flex;justify-content:space-between;align-items:center;box-shadow:0 1px 3px rgba(0,0,0,0.08);border:1px solid #e2e8f0;}
    .page-title{display:flex;align-items:center;gap:12px;}
    .page-title h1{font-size:18px;font-weight:600;color:#1e293b;margin:0;}
    .page-title p{font-size:12px;color:#64748b;margin:0;}
    .page-icon{font-size:24px;}
    .page-actions{display:flex;gap:10px;}
    .btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:6px;font-size:14px;font-weight:500;text-decoration:none;cursor:pointer;border:none;transition:all 0.2s;}
    .btn-primary{background:#2563eb;color:#fff;}.btn-primary:hover{background:#1d4ed8;}
    .btn-secondary{background:#f1f5f9;color:#475569;border:1px solid #e2e8f0;}.btn-secondary:hover{background:#e2e8f0;}
    .btn-success{background:#10b981;color:#fff;}.btn-success:hover{background:#059669;}
    .btn-danger{background:#ef4444;color:#fff;}.btn-danger:hover{background:#dc2626;}
    .btn-gray{background:#64748b;color:#fff;}.btn-gray:hover{background:#475569;}
    .btn-sm{padding:5px 10px;font-size:12px;}.btn-lg{padding:12px 24px;font-size:15px;}
    .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin-bottom:20px;}
    .stat-card{background:#fff;border-radius:8px;padding:20px;display:flex;align-items:center;gap:16px;box-shadow:0 1px 3px rgba(0,0,0,0.08);border:1px solid #e2e8f0;}
    .stat-icon{width:48px;height:48px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:22px;}
    .stat-info{flex:1;}.stat-value{font-size:24px;font-weight:700;color:#1e293b;}.stat-label{font-size:13px;color:#64748b;margin-top:2px;}
    .content-card{background:#fff;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,0.08);border:1px solid #e2e8f0;overflow:hidden;}
    .data-table{width:100%;border-collapse:collapse;}.data-table th,.data-table td{padding:12px 16px;text-align:left;border-bottom:1px solid #e2e8f0;}
    .data-table th{background:#f8fafc;font-weight:600;color:#475569;font-size:13px;}
    .data-table tr:hover{background:#f8fafc;}.data-table tr:last-child td{border-bottom:none;}
    .id-cell{color:#94a3b8;font-size:12px;font-family:monospace;}
    .badge{display:inline-flex;align-items:center;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:500;}
    .badge-success{background:#ecfdf5;color:#10b981;}.badge-warning{background:#fffbeb;color:#f59e0b;}
    .badge-danger{background:#fef2f2;color:#ef4444;}.badge-gray{background:#f1f5f9;color:#64748b;}
    .badge-primary{background:#eff6ff;color:#2563eb;}
    .btn-group{display:flex;gap:6px;}
    .filter-bar{background:#fff;border-radius:8px;padding:16px;margin-bottom:16px;box-shadow:0 1px 3px rgba(0,0,0,0.08);border:1px solid #e2e8f0;}
    .filter-bar form{display:flex;gap:12px;flex-wrap:wrap;align-items:center;}
    .filter-bar input,.filter-bar select{padding:8px 12px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;outline:none;}
    .filter-bar input:focus,.filter-bar select:focus{border-color:#2563eb;}
    .filter-item{display:flex;align-items:center;gap:8px;}.filter-item label{font-size:13px;color:#64748b;}
    .pagination{display:flex;justify-content:center;gap:6px;padding:16px;}
    .pagination a{padding:6px 12px;border:1px solid #e2e8f0;border-radius:6px;color:#475569;text-decoration:none;font-size:13px;}
    .pagination a:hover{background:#f1f5f9;}.pagination a.active{background:#2563eb;color:#fff;border-color:#2563eb;}
    .empty-state{text-align:center;padding:60px 20px;color:#64748b;}
    .empty-icon{font-size:48px;margin-bottom:16px;}.empty-state h3{font-size:16px;color:#475569;margin-bottom:8px;}
    .empty-state p{font-size:14px;color:#94a3b8;}
    .form-section{background:#fff;border:1px solid #e2e8f0;border-radius:8px;margin-bottom:20px;}
    .form-section-header{padding:14px 20px;border-bottom:1px solid #e2e8f0;font-size:14px;font-weight:600;color:#1e293b;}
    .form-section-body{padding:20px;}
    .form-section-body .editor-wrapper{margin:-20px 0 0 0;}
    .form-section-body .editor-toolbar{margin-bottom:0;padding:12px;}
    .form-section-body .editor-toolbar{margin-bottom:0;}
    .form-group{margin-bottom:16px;}.form-group label{display:block;font-size:14px;font-weight:500;color:#475569;margin-bottom:6px;}
    .form-control{width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;outline:none;transition:border-color 0.2s;}
    .form-control:focus{border-color:#2563eb;}
    .form-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;}
    .form-actions{background:#fff;padding:20px;border-radius:8px;display:flex;gap:12px;}
    .required{color:#ef4444;}
    textarea.form-control{resize:vertical;min-height:100px;}select.form-control{background:#fff;}
    .upload-preview{width:200px;height:150px;border:2px dashed #e2e8f0;border-radius:8px;display:flex;align-items:center;justify-content:center;overflow:hidden;margin-top:10px;}
    .upload-preview img{width:100%;height:100%;object-fit:cover;}
    .upload-preview .placeholder{text-align:center;color:#94a3b8;}.upload-preview .placeholder .icon{font-size:32px;margin-bottom:4px;}
    .upload-preview.has-image{border-color:#2563eb;}
    .rich-editor-container{border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;}
    .rich-editor-toolbar{display:flex;flex-wrap:wrap;gap:4px;padding:10px;background:#f8fafc;border-bottom:1px solid #e2e8f0;}
    .toolbar-btn{width:32px;height:32px;border:1px solid #e2e8f0;border-radius:4px;background:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;}
    .toolbar-btn:hover{background:#f1f5f9;border-color:#2563eb;}.toolbar-btn.active{background:#2563eb;color:#fff;border-color:#2563eb;}
    .rich-editor-content{min-height:300px;padding:16px;outline:none;overflow:auto;background:#fff;}.rich-editor-content:focus{outline:none;}
    .editor-wrapper{border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;background:#fff;}
    .editor-toolbar{display:flex;flex-wrap:wrap;gap:4px;padding:10px;background:#f8fafc;border-bottom:1px solid #e2e8f0;}
    .editor-toolbar button{width:32px;height:32px;border:1px solid #e2e8f0;border-radius:4px;background:#fff;cursor:pointer;font-size:13px;font-weight:600;}
    .editor-toolbar button:hover{background:#e2e8f0;}
    .editor-toolbar .upload-btn{width:auto;padding:0 12px;height:32px;background:#2563eb;color:#fff;border:none;border-radius:4px;font-size:12px;cursor:pointer;display:flex;align-items:center;}
    .toolbar-divider{width:1px;height:24px;background:#e2e8f0;margin:0 4px;}
    .editor-content{min-height:300px;padding:16px;outline:none;overflow:auto;background:#fff;}
    .fade-in{animation:fadeIn 0.3s ease;}
    @keyframes fadeIn{from{opacity:0;transform:translateY(10px);}to{opacity:1;transform:translateY(0);}}
    @media(max-width:768px){
        body{font-size:13px;overflow-x:hidden;}
        .page-container{padding:12px;max-width:100%;}
        .page-header{flex-direction:column;gap:12px;align-items:flex-start;padding:14px 16px;}
        .page-actions,.btn-group,.form-actions{width:100%;flex-wrap:wrap;}
        .page-actions .btn,.btn-group .btn,.form-actions .btn{width:100%;justify-content:center;}
        .stats-grid{grid-template-columns:1fr;}
        .content-card{overflow-x:hidden;}
        .data-table{min-width:720px;}
        .filter-bar{padding:12px;}
        .filter-bar form{flex-direction:column;align-items:stretch;}
        .filter-item{width:100%;flex-direction:column;align-items:stretch;gap:6px;}
        .filter-bar input,.filter-bar select{width:100%;}
        .form-row{grid-template-columns:1fr;}
        .form-section-body,.form-actions{padding:14px;}
        .upload-preview{width:100%;max-width:200px;height:140px;}
        .pagination{justify-content:flex-start;overflow-x:auto;}
    }
    </style>
    <link rel="stylesheet" href="/public/css/rich-editor.css">
    <script src="/public/ueditor/editor.js"></script>
</head>
<body>
<div class="page-container fade-in">
<?php

switch ($act) {
    case 'content':
        include 'modules/content.php';
        break;
    case 'content_list':
        header('Content-Type: text/html; charset=utf-8');
        include 'modules/content_list.php';
        exit;
    case 'dashboard':
        include 'modules/dashboard.php';
        break;
    case 'channel':
        include 'modules/channel.php';
        break;
    case 'article':
        include 'modules/article.php';
        break;
    case 'product':
        include 'modules/product.php';
        break;
    case 'page':
        include 'modules/page.php';
        break;
    case 'image':
        include 'modules/image.php';
        break;
    case 'download':
        include 'modules/download.php';
        break;
    case 'video':
        include 'modules/video.php';
        break;
    case 'recruit':
        include 'modules/recruit.php';
        break;
    case 'member':
        include 'modules/member.php';
        break;
    case 'member_group':
        include 'modules/member_group.php';
        break;
    case 'message':
        include 'modules/message.php';
        break;
    case 'guestbook':
        include 'modules/guestbook.php';
        break;
    case 'comment':
        include 'modules/comment.php';
        break;
    case 'vote':
        include 'modules/vote.php';
        break;
    case 'contribute':
        include 'modules/contribute.php';
        break;
    case 'slide':
        include 'modules/slide.php';
        break;
    case 'link':
        include 'modules/link.php';
        break;
    case 'ads':
        include 'modules/ads.php';
        break;
    case 'template':
        include 'modules/template.php';
        break;
    case 'tag_help':
        include 'modules/tag_help.php';
        break;
    case 'version':
        include 'modules/version.php';
        break;
    case 'custom_var':
        include 'modules/custom_var.php';
        break;
    case 'recharge':
        include 'modules/recharge.php';
        break;
    case 'pay_order':
        $moduleLoader->includeModule('pro.pay_order');
        break;
    case 'order':
        include 'modules/order.php';
        break;
    case 'site':
        include 'modules/site.php';
        break;
    case 'payment':
        include 'modules/payment.php';
        break;
    case 'auth':
        include 'modules/auth.php';
        break;
    case 'help_center':
        include 'modules/help_center.php';
        break;
    case 'log':
        include 'modules/log.php';
        break;
    case 'database':
        include 'modules/database.php';
        break;
    case 'profile':
        include 'modules/profile.php';
        break;
    case 'admin_user':
        include 'modules/admin_user.php';
        break;
    default:
        include 'modules/dashboard.php';
        break;
}
ob_end_flush();
if (!isset($license) || !is_object($license)) {
    $license = new \Core\Lib\License();
}
if (is_object($license)) {
    $licStatus = $license->getStatus();
    if (!$licStatus['can_remove_copyright']): ?>
<div style="background:#f8fafc;border-top:1px solid #e2e8f0;padding:12px 20px;text-align:center;font-size:12px;color:#94a3b8;">
    芋头CMS <?php echo htmlspecialchars($licStatus['level_name']); ?> | <a href="http://www.yutoucms.cn/" target="_blank" style="color:#94a3b8;text-decoration:none;">Powered by 芋头CMS</a>
</div>
    <?php endif;
} else {
    echo '<div style="background:#f8fafc;border-top:1px solid #e2e8f0;padding:12px 20px;text-align:center;font-size:12px;color:#94a3b8;">芋头CMS 免费版 | <a href="http://www.yutoucms.cn/" target="_blank" style="color:#94a3b8;text-decoration:none;">Powered by 芋头CMS</a></div>';
}
?>
</div>
</body>
</html>
