<?php
include("../includes/common.php");
$islogin=1;
if($islogin==1){}else exit('{"code":-1,"msg":"未登录"}');

// 开启错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 设置响应头
header('Content-Type: application/json; charset=UTF-8');

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

if($act=='checkAuth'){
    $domain = $_POST['domain'] ?? null;
    $auth_key = $_POST['auth_key'] ?? null;
    
    $url = 'https://auth.7t.ink/verify.php';
    $post = [
        'domain' => $domain,
        'auth_key' => $auth_key
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    header('Content-Type: application/json');
    if($response === false) {
        exit(json_encode([
            'code' => 500,
            'message' => '请求授权接口失败',
            'data' => null
        ]));
    }
    
    echo $response;
}

elseif($act=='checkUpdate'){
    $version = $_GET['version'] ?? '0.0.0';
    
    $url = 'https://auth.7t.ink/verify.php?check_update=1&version='.urlencode($version);
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    header('Content-Type: application/json');
    if($response === false) {
        exit(json_encode([
            'status' => 'error',
            'message' => '请求更新接口失败'
        ]));
    }
    
    echo $response;
}

elseif($act=='startUpdate'){
    $version = $_POST['version'] ?? '';
    $download_url = $_POST['download_url'] ?? '';
    $file_name = $_POST['file_name'] ?? '';
    $admin_dir = $_POST['admin_dir'] ?? 'admin';
    
    if(empty($version) || empty($download_url) || empty($file_name)) {
        exit(json_encode(['code'=>-1, 'msg'=>'参数不完整']));
    }
    
    // 检查目录名称合法性
    if(!preg_match('/^[a-zA-Z0-9_-]+$/', $admin_dir)) {
        exit(json_encode(['code'=>-1, 'msg'=>'目录名称只能包含字母、数字、下划线和横杠']));
    }
    
    // 创建临时目录
    $temp_dir = ROOT.'temp';
    if(!is_dir($temp_dir)) mkdir($temp_dir);
    
    // 保存更新信息到session
    $_SESSION['update_info'] = [
        'version' => $version,
        'download_url' => $download_url,
        'file_name' => $file_name,
        'admin_dir' => $admin_dir,
        'temp_dir' => $temp_dir,
        'status' => '准备下载',
        'percent' => 0,
        'step' => 'download',
        'success' => false,
        'finished' => false,
        'error' => null
    ];
    
    exit(json_encode(['code'=>0]));
}

elseif($act=='getUpdateProgress'){
    if(!isset($_SESSION['update_info'])) {
        exit(json_encode(['code'=>-1, 'msg'=>'没有更新进程']));
    }
    
    $info = &$_SESSION['update_info'];
    
    // 如果上一次检查时已完成，直接返回结果
    if($info['finished']) {
        $result = [
            'code' => 0,
            'status' => $info['status'],
            'percent' => $info['percent'],
            'finished' => true,
            'success' => $info['success']
        ];
        if($info['error']) $result['msg'] = $info['error'];
        unset($_SESSION['update_info']);
        exit(json_encode($result));
    }
    
    // 根据当前步骤执行相应操作
    try {
        if($info['step'] == 'download') {
            // 下载文件
            $file_path = $info['temp_dir'].'/'.$info['file_name'];
            $fp = fopen($file_path, 'w');
            
            $ch = curl_init($info['download_url']);
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_NOPROGRESS, false);
            curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($resource, $download_size, $downloaded) use (&$info) {
                if($download_size > 0) {
                    $info['percent'] = round($downloaded / $download_size * 40); // 下载占进度的40%
                }
            });
            
            $success = curl_exec($ch);
            curl_close($ch);
            fclose($fp);
            
            if(!$success) throw new Exception('下载更新包失败');
            
            $info['status'] = '正在解压更新包...';
            $info['step'] = 'extract';
            $info['percent'] = 40;
        }
        
        if($info['step'] == 'extract') {
            $zip = new ZipArchive;
            $file_path = $info['temp_dir'].'/'.$info['file_name'];
            
            if($zip->open($file_path) !== true) {
                throw new Exception('无法打开更新包');
            }
            
            // 解压到临时目录
            $extract_dir = $info['temp_dir'].'/extract';
            if(!is_dir($extract_dir)) mkdir($extract_dir);
            $zip->extractTo($extract_dir);
            $zip->close();
            
            $info['status'] = '正在更新文件...';
            $info['step'] = 'copy';
            $info['percent'] = 60;
        }
        
        if($info['step'] == 'copy') {
            $extract_dir = $info['temp_dir'].'/extract';
            $admin_src = $extract_dir.'/admin';
            $admin_dst = ROOT.$info['admin_dir'];
            
            // 如果目标目录不存在则创建
            if(!is_dir($admin_dst)) {
                if(!mkdir($admin_dst, 0755, true)) {
                    throw new Exception('创建目标目录失败');
                }
            }
            
            // 复制admin目录内的文件到目标目录
            function copyDir($src, $dst) {
                $dir = opendir($src);
                if(!is_dir($dst)) mkdir($dst);
                while(($file = readdir($dir)) !== false) {
                    if($file != '.' && $file != '..') {
                        $srcFile = $src . '/' . $file;
                        $dstFile = $dst . '/' . $file;
                        if(is_dir($srcFile)) {
                            copyDir($srcFile, $dstFile);
                        } else {
                            copy($srcFile, $dstFile);
                        }
                    }
                }
                closedir($dir);
            }
            
            // 复制admin目录内的文件
            if(is_dir($admin_src)) {
                $dir = opendir($admin_src);
                while(($file = readdir($dir)) !== false) {
                    if($file != '.' && $file != '..') {
                        $srcFile = $admin_src . '/' . $file;
                        $dstFile = $admin_dst . '/' . $file;
                        if(is_dir($srcFile)) {
                            copyDir($srcFile, $dstFile);
                        } else {
                            copy($srcFile, $dstFile);
                        }
                    }
                }
                closedir($dir);
            }
            
            // 复制其他文件（admin目录外的文件）
            $dir = opendir($extract_dir);
            while(($file = readdir($dir)) !== false) {
                if($file != '.' && $file != '..' && $file != 'admin') {
                    $srcFile = $extract_dir . '/' . $file;
                    $dstFile = ROOT . $file;
                    if(is_dir($srcFile)) {
                        copyDir($srcFile, $dstFile);
                    } else {
                        copy($srcFile, $dstFile);
                    }
                }
            }
            closedir($dir);
            
            $info['status'] = '正在清理临时文件...';
            $info['step'] = 'cleanup';
            $info['percent'] = 80;
        }
        
        if($info['step'] == 'cleanup') {
            // 删除临时文件
            function delDir($dir) {
                $dh = opendir($dir);
                while(($file = readdir($dh)) !== false) {
                    if($file != '.' && $file != '..') {
                        $fullpath = $dir . '/' . $file;
                        if(is_dir($fullpath)) {
                            delDir($fullpath);
                        } else {
                            unlink($fullpath);
                        }
                    }
                }
                closedir($dh);
                rmdir($dir);
            }
            
            delDir($info['temp_dir']);
            
            // 更新版本号
            file_put_contents(ROOT.$info['admin_dir'].'/version', $info['version']);
            
            $info['status'] = '更新完成';
            $info['percent'] = 100;
            $info['success'] = true;
            $info['finished'] = true;
        }
        
        exit(json_encode([
            'code' => 0,
            'status' => $info['status'],
            'percent' => $info['percent'],
            'finished' => $info['finished'],
            'success' => $info['success']
        ]));
        
    } catch(Exception $e) {
        $info['status'] = '更新失败';
        $info['error'] = $e->getMessage();
        $info['success'] = false;
        $info['finished'] = true;
        
        exit(json_encode([
            'code' => 0,
            'status' => $info['status'],
            'percent' => $info['percent'],
            'finished' => true,
            'success' => false,
            'msg' => $e->getMessage()
        ]));
    }
}

elseif($act=='debug'){
    $type = $_GET['type'] ?? '';
    $result = [];
    
    if($type == 'auth'){
        $domain = $_SERVER['HTTP_HOST'];
        $url = 'https://auth.7t.ink/verify.php';
        $post = ['domain' => $domain];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $body = substr($response, $headerSize);
        
        $result['request_url'] = $url;
        $result['request_data'] = $post;
        $result['response_header'] = $header;
        $result['response_body'] = $body;
        $result['curl_info'] = curl_getinfo($ch);
        
        curl_close($ch);
    }
    elseif($type == 'update'){
        $current_version = @file_get_contents(ROOT.'admin/version') ?: '1.0.0';
        $url = 'https://auth.7t.ink/verify.php?check_update=1&version='.$current_version;
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $body = substr($response, $headerSize);
        
        $result['request_url'] = $url;
        $result['response_header'] = $header;
        $result['response_body'] = $body;
        $result['curl_info'] = curl_getinfo($ch);
        
        curl_close($ch);
    }
    elseif($type == 'ad'){
        $url = 'https://auth.7t.ink/verify.php?get_ads=1';
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $body = substr($response, $headerSize);
        
        $result['request_url'] = $url;
        $result['response_header'] = $header;
        $result['response_body'] = $body;
        $result['curl_info'] = curl_getinfo($ch);
        
        // 获取最近的点击记录
        $url = 'https://auth.7t.ink/verify.php?get_ads=1&show_clicks=1';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $body = substr($response, $headerSize);
        
        $result['clicks_data'] = $body;
        
        curl_close($ch);
    }
    elseif($type == 'message'){
        // 获取留言列表
        $url = 'https://auth.7t.ink/verify.php?get_messages=1';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $body = substr($response, $headerSize);
        
        $result['request_url'] = $url;
        $result['response_header'] = $header;
        $result['response_body'] = $body;
        $result['curl_info'] = curl_getinfo($ch);
        
        // 获取当前域名
        $result['current_domain'] = $_SERVER['HTTP_HOST'];
        
        // 获取最近提交的留言
        $url = 'https://auth.7t.ink/verify.php?get_messages=1&show_my=1';
        curl_setopt($ch, CURLOPT_URL, $url);
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $body = substr($response, $headerSize);
        
        $result['my_messages'] = $body;
        
        curl_close($ch);
    }
    elseif($type == 'changelog'){
        $current_version = @file_get_contents(ROOT.'admin/version') ?: '1.0.0';
        $url = 'https://auth.7t.ink/verify.php?get_changelog=1&version='.$current_version;
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'ColorfulSystem/1.0');
        curl_setopt($ch, CURLOPT_REFERER, 'https://'.$_SERVER['HTTP_HOST']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $body = substr($response, $headerSize);
        
        $result['request_url'] = $url;
        $result['current_version'] = $current_version;
        $result['response_header'] = $header;
        $result['response_body'] = $body;
        $result['curl_info'] = curl_getinfo($ch);
        
        // 获取最近的更新记录
        $url = 'https://auth.7t.ink/verify.php?get_changelog=1&version=0.0.0';
        curl_setopt($ch, CURLOPT_URL, $url);
        
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $body = substr($response, $headerSize);
        
        $result['all_versions'] = $body;
        
        curl_close($ch);
    }
    
    header('Content-Type: application/json');
    echo json_encode($result);
}

elseif($act=='getAd'){
    $url = 'https://auth.7t.ink/verify.php?get_ads=1'; // 修改为资源获取接口
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    header('Content-Type: application/json');
    if($response === false) {
        exit(json_encode([
            'code' => 500,
            'message' => '请求资源接口失败',
            'data' => null
        ]));
    }
    
    // 解析响应数据
    $data = json_decode($response, true);
    if(!$data) {
        exit(json_encode([
            'code' => 500,
            'message' => '解析资源数据失败',
            'data' => null
        ]));
    }
    
    // 确保返回的数据是数组格式
    if(isset($data['data']) && !is_array($data['data'])) {
        $data['data'] = [$data['data']];
    }
    
    // 如果没有资源数据，返回空数组
    if(!isset($data['data']) || empty($data['data'])) {
        exit(json_encode([
            'code' => 200,
            'message' => '暂无资源数据',
            'data' => []
        ]));
    }
    
    echo json_encode($data);
}

elseif($act=='recordClick'){
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    $url = 'https://auth.7t.ink/verify.php?record_click=1&id='.$id;
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    header('Content-Type: application/json');
    if($response === false) {
        exit(json_encode([
            'code' => 500,
            'message' => '请求失败'
        ]));
    }
    
    echo $response;
}

elseif($act=='getMessages'){
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
    
    $url = 'https://auth.7t.ink/verify.php?get_messages=1&page='.$page.'&limit='.$limit;
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; ColorfulSystem/1.0)');
    curl_setopt($ch, CURLOPT_REFERER, 'https://'.$_SERVER['HTTP_HOST']);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    header('Content-Type: application/json');
    if($response === false || $httpCode !== 200) {
        exit(json_encode([
            'code' => 500,
            'message' => '请求失败: ' . curl_error($ch),
            'data' => null
        ]));
    }
    
    // 解析响应数据
    $data = json_decode($response, true);
    if(!$data) {
        exit(json_encode([
            'code' => 500,
            'message' => '解析数据失败: ' . json_last_error_msg(),
            'data' => null
        ]));
    }
    
    echo $response;
}

elseif($act=='submitMessage'){
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    
    if(empty($content)) {
        exit(json_encode([
            'code' => 400,
            'message' => '留言内容不能为空',
            'data' => null
        ]));
    }
    
    // 获取当前域名
    $domain = $_SERVER['HTTP_HOST'];
    if(empty($domain)) {
        exit(json_encode([
            'code' => 400,
            'message' => '无法获取来源站点信息',
            'data' => null
        ]));
    }
    
    $url = 'https://auth.7t.ink/verify.php';
    $post_data = [
        'submit_message' => 1,
        'content' => $content
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; ColorfulSystem/1.0)');
    curl_setopt($ch, CURLOPT_REFERER, 'https://'.$_SERVER['HTTP_HOST']);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    header('Content-Type: application/json');
    if($response === false || $httpCode !== 200) {
        exit(json_encode([
            'code' => 500,
            'message' => '请求失败: ' . $error,
            'data' => null
        ]));
    }
    
    // 解析响应数据
    $data = json_decode($response, true);
    if(!$data) {
        exit(json_encode([
            'code' => 500,
            'message' => '解析数据失败: ' . json_last_error_msg(),
            'data' => null
        ]));
    }
    
    echo $response;
}

elseif($act=='getChangelog'){
    $version = isset($_GET['version']) ? trim($_GET['version']) : '';
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
    
    if(empty($version)) {
        exit(json_encode([
            'code' => 400,
            'message' => '版本号不能为空',
            'data' => null
        ]));
    }
    
    $url = 'https://auth.7t.ink/verify.php?get_changelog=1&version='.urlencode($version).'&page='.$page.'&limit='.$limit;
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'ColorfulSystem/1.0');
    curl_setopt($ch, CURLOPT_REFERER, 'https://'.$_SERVER['HTTP_HOST']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    header('Content-Type: application/json');
    
    if($response === false) {
        exit(json_encode([
            'code' => 500,
            'message' => '请求更新日志失败: ' . $error,
            'data' => null
        ]));
    }
    
    if($httpCode !== 200) {
        exit(json_encode([
            'code' => $httpCode,
            'message' => '服务器响应异常，状态码：' . $httpCode,
            'data' => null
        ]));
    }
    
    // 解析响应数据
    $data = json_decode($response, true);
    if(!$data) {
        exit(json_encode([
            'code' => 500,
            'message' => '解析更新日志数据失败: ' . json_last_error_msg(),
            'data' => null
        ]));
    }
    
    // 格式化返回数据
    $result = [
        'code' => 200,
        'message' => 'success',
        'data' => [
            'current' => null,
            'history' => []
        ]
    ];
    
    if(isset($data['data']['logs']) && !empty($data['data']['logs'])) {
        // 找到当前版本的更新日志
        foreach($data['data']['logs'] as $log) {
            if($log['version'] === $version) {
                $result['data']['current'] = [
                    'version' => $log['version'],
                    'description' => $log['description'],
                    'release_time' => $log['created_at']
                ];
                break;
            }
        }
        
        // 历史版本记录（只包括当前及更低版本）
        $result['data']['history'] = array_map(function($log) {
            return [
                'version' => $log['version'],
                'description' => $log['description'],
                'release_time' => $log['created_at']
            ];
        }, array_filter($data['data']['logs'], function($log) use ($version) {
            return version_compare($log['version'], $version, '<=');
        }));

        // 按版本号降序排序
        usort($result['data']['history'], function($a, $b) {
            return version_compare($b['version'], $a['version']);
        });

        // 添加分页信息
        if(isset($data['data']['pagination'])) {
            $result['data']['pagination'] = $data['data']['pagination'];
            $result['data']['pagination']['total'] = count($result['data']['history']);
            $result['data']['pagination']['total_pages'] = ceil($result['data']['pagination']['total'] / $limit);
            
            // 分页处理
            $start = ($page - 1) * $limit;
            $result['data']['history'] = array_slice($result['data']['history'], $start, $limit);
        }
    }
    
    echo json_encode($result);
}

elseif($act=='upload_classimg'){
    $cid = intval($_POST['cid']);
    if(!$cid) exit(json_encode(['code'=>-1, 'msg'=>'参数错误']));
    
    if (empty($_FILES['file'])) {
        exit(json_encode(['code'=>-1, 'msg'=>'请选择文件']));
    }
    
    $file = $_FILES['file'];
    if($file['error']>0) {
        exit(json_encode(['code'=>-1, 'msg'=>'文件上传错误']));
    }
    
    $ext = strtolower(substr($file['name'], strrpos($file['name'], '.')+1));
    $allowFiles = array('jpg', 'jpeg', 'png', 'gif');
    if(!in_array($ext, $allowFiles)){
        exit(json_encode(['code'=>-1, 'msg'=>'只支持jpg/jpeg/png/gif格式的图片']));
    }
    
    if($file['size']>2*1024*1024){
        exit(json_encode(['code'=>-1, 'msg'=>'文件大小不能超过2M']));
    }
    
    $imgdir = ROOT.'assets/img/class/';
    if(!is_dir($imgdir)) mkdir($imgdir, 0777, true);
    
    $filename = date("YmdHis").rand(111,999).'.'.$ext;
    $filepath = $imgdir.$filename;
    
    if(move_uploaded_file($file['tmp_name'], $filepath)){
        $url = '../assets/img/class/'.$filename;
        exit(json_encode(['code'=>0, 'msg'=>'上传成功', 'url'=>$url]));
    }else{
        exit(json_encode(['code'=>-1, 'msg'=>'文件保存失败']));
    }
}

elseif($act=='save_classimg'){
    $cid = intval($_POST['cid']);
    $img = trim($_POST['img']);
    if(!$cid) exit(json_encode(['code'=>-1, 'msg'=>'参数错误']));
    if(empty($img)) exit(json_encode(['code'=>-1, 'msg'=>'图片地址不能为空']));
    
    $sql = "UPDATE pre_class SET shopimg=:img WHERE cid=:cid";
    $stmt = $DB->prepare($sql);
    $stmt->execute(['img'=>$img, 'cid'=>$cid]);
    
    if($stmt->rowCount()>0){
        exit(json_encode(['code'=>0, 'msg'=>'保存成功']));
    }else{
        exit(json_encode(['code'=>-1, 'msg'=>'保存失败']));
    }
}

elseif($act=='save_all_classimg'){
    try {
        if(!$DB) {
            throw new Exception('数据库连接失败');
        }
        
        $imgs = isset($_POST['imgs']) ? json_decode($_POST['imgs'], true) : null;
        
        if($imgs === null && json_last_error() !== JSON_ERROR_NONE) {
            exit(json_encode(['code'=>-1, 'msg'=>'JSON解析错误：'.json_last_error_msg()]));
        }
        
        if(!is_array($imgs) || empty($imgs)) {
            exit(json_encode(['code'=>-1, 'msg'=>'参数错误：没有收到有效的图片数据']));
        }
        
        // 检查表是否存在
        $tables = $DB->query("SHOW TABLES LIKE 'pre_class'", false, true);
        if(empty($tables)) {
            throw new Exception('数据表pre_class不存在');
        }
        
        // 检查字段是否存在
        $columns = $DB->query("SHOW COLUMNS FROM pre_class LIKE 'shopimg'", false, true);
        if(empty($columns)) {
            throw new Exception('字段shopimg不存在');
        }
        
        $success = 0;
        $errors = [];
        
        foreach($imgs as $cid=>$img){
            if(empty($img)) continue;
            
            try {
                $sql = "UPDATE pre_class SET shopimg=? WHERE cid=?";
                $result = $DB->query($sql, [$img, intval($cid)]);
                
                if($result !== false) {
                    $success++;
                } else {
                    $errors[] = "分类ID {$cid} 更新失败";
                }
            } catch (Exception $e) {
                $errors[] = "分类ID {$cid} 出错：" . $e->getMessage();
            }
        }
        
        $msg = '成功保存'.$success.'个分类图片';
        if(!empty($errors)) {
            $msg .= '，但有以下错误：' . implode('；', $errors);
        }
        
        exit(json_encode([
            'code' => $success > 0 ? 0 : -1,
            'msg' => $msg,
            'debug' => [
                'success_count' => $success,
                'error_count' => count($errors),
                'errors' => $errors,
                'post_data' => $_POST,
                'decoded_data' => $imgs
            ]
        ]));
        
    } catch (Exception $e) {
        exit(json_encode([
            'code' => -1,
            'msg' => '系统错误：' . $e->getMessage(),
            'debug' => [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'post_data' => $_POST
            ]
        ]));
    }
}
