<?php
@set_time_limit(0);
@ini_set('memory_limit', '512M');
@header('Content-Type: application/json; charset=UTF-8');
include dirname(__DIR__) . '/includes/common.php';

if($islogin != 1) {
    exit(json_encode(['code' => -1, 'msg' => '未登录']));
}

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

// 老数据库连接
function getOldDbConnection($config, $timeout = 600) {
    $dsn = "mysql:host={$config['db_host']};port={$config['db_port']};dbname={$config['db_name']};charset=utf8";
    try {
        $pdo = new PDO($dsn, $config['db_user'], $config['db_pwd'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT => $timeout
        ]);
        return $pdo;
    } catch(PDOException $e) {
        return false;
    }
}

// 快速测试连接（短超时）
function getTestDbConnection($config) {
    $dsn = "mysql:host={$config['db_host']};port={$config['db_port']};dbname={$config['db_name']};charset=utf8";
    try {
        $pdo = new PDO($dsn, $config['db_user'], $config['db_pwd'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_TIMEOUT => 5
        ]);
        return $pdo;
    } catch(PDOException $e) {
        return false;
    }
}

switch($action) {
    case 'test_connection':
        $config = [
            'db_host' => $_POST['db_host'] ?? 'localhost',
            'db_port' => $_POST['db_port'] ?? '3306',
            'db_name' => $_POST['db_name'] ?? '',
            'db_user' => $_POST['db_user'] ?? '',
            'db_pwd' => $_POST['db_pwd'] ?? '',
            'db_prefix' => $_POST['db_prefix'] ?? 'bot_'
        ];

        if(empty($config['db_name']) || empty($config['db_user'])) {
            exit(json_encode(['code' => -1, 'msg' => '请填写完整数据库信息']));
        }

        $pdo = getTestDbConnection($config);
        if($pdo) {
            // 检查表是否存在
            $prefix = $config['db_prefix'];
            $tables = ['user', 'login_class', 'loginconfig', 'qq', 'goods', 'km'];
            $existTables = [];
            foreach($tables as $table) {
                $stmt = $pdo->query("SHOW TABLES LIKE '{$prefix}{$table}'");
                if($stmt->rowCount() > 0) {
                    $existTables[] = $table;
                }
            }
            exit(json_encode(['code' => 1, 'msg' => '找到表: ' . implode(', ', $existTables)]));
        } else {
            exit(json_encode(['code' => -1, 'msg' => '数据库连接失败，请检查配置']));
        }
        break;

    case 'save_config':
        $config = [
            'db_host' => $_POST['db_host'] ?? 'localhost',
            'db_port' => $_POST['db_port'] ?? '3306',
            'db_name' => $_POST['db_name'] ?? '',
            'db_user' => $_POST['db_user'] ?? '',
            'db_pwd' => $_POST['db_pwd'] ?? '',
            'db_prefix' => $_POST['db_prefix'] ?? 'bot_'
        ];

        $configContent = "<?php\nreturn " . var_export($config, true) . ";\n";
        $result = file_put_contents(dirname(__DIR__) . '/old_db_config.php', $configContent);

        if($result) {
            exit(json_encode(['code' => 1, 'msg' => '配置已保存']));
        } else {
            exit(json_encode(['code' => -1, 'msg' => '保存失败，请检查目录权限']));
        }
        break;

    case 'clear_data':
        try {
            // 清空表数据，保留管理员账号
            $DB->exec("DELETE FROM pre_user WHERE zid != 1000 AND zid != 1");
            $DB->exec("DELETE FROM pre_login_class WHERE id != 1000");
            $DB->exec("TRUNCATE TABLE pre_qq");
            $DB->exec("TRUNCATE TABLE pre_loginconfig");
            $DB->exec("TRUNCATE TABLE pre_goods");
            $DB->exec("TRUNCATE TABLE pre_km");
            exit(json_encode(['code' => 1, 'msg' => '数据已清空']));
        } catch(Exception $e) {
            exit(json_encode(['code' => -1, 'msg' => '清空失败: ' . $e->getMessage()]));
        }
        break;

    case 'get_table_count':
        $table = $_POST['table'] ?? '';
        $config = [
            'db_host' => $_POST['db_host'] ?? 'localhost',
            'db_port' => $_POST['db_port'] ?? '3306',
            'db_name' => $_POST['db_name'] ?? '',
            'db_user' => $_POST['db_user'] ?? '',
            'db_pwd' => $_POST['db_pwd'] ?? '',
            'db_prefix' => $_POST['db_prefix'] ?? 'bot_'
        ];

        if(empty($table)) {
            exit(json_encode(['code' => -1, 'msg' => '未指定表']));
        }

        $pdo = getOldDbConnection($config);
        if(!$pdo) {
            exit(json_encode(['code' => -1, 'msg' => '老数据库连接失败']));
        }

        $prefix = $config['db_prefix'];
        $oldTable = $prefix . $table;

        try {
            $count = $pdo->query("SELECT COUNT(*) FROM $oldTable")->fetchColumn();
            exit(json_encode(['code' => 1, 'count' => intval($count)]));
        } catch(Exception $e) {
            exit(json_encode(['code' => -1, 'msg' => '获取数量失败: ' . $e->getMessage()]));
        }
        break;

    case 'import_table':
        $table = $_POST['table'] ?? '';
        $offset = intval($_POST['offset'] ?? 0);
        $limit = intval($_POST['limit'] ?? 2000);
        $config = [
            'db_host' => $_POST['db_host'] ?? 'localhost',
            'db_port' => $_POST['db_port'] ?? '3306',
            'db_name' => $_POST['db_name'] ?? '',
            'db_user' => $_POST['db_user'] ?? '',
            'db_pwd' => $_POST['db_pwd'] ?? '',
            'db_prefix' => $_POST['db_prefix'] ?? 'bot_'
        ];

        if(empty($table)) {
            exit(json_encode(['code' => -1, 'msg' => '未指定导入表']));
        }

        $pdo = getOldDbConnection($config);
        if(!$pdo) {
            exit(json_encode(['code' => -1, 'msg' => '老数据库连接失败']));
        }

        $prefix = $config['db_prefix'];
        $log = [];
        $count = 0;

        try {
            switch($table) {
                case 'user':
                    $result = importUserTable($pdo, $DB, $prefix, $log, $offset, $limit);
                    $count = $result;
                    break;
                case 'login_class':
                    $result = importLoginClassTable($pdo, $DB, $prefix, $log, $offset, $limit);
                    $count = $result;
                    break;
                case 'qq':
                    $result = importQqTable($pdo, $DB, $prefix, $log, $offset, $limit);
                    $count = $result;
                    break;
                case 'km':
                    $result = importKmTable($pdo, $DB, $prefix, $log, $offset, $limit);
                    $count = $result;
                    break;
                case 'loginconfig':
                    $result = importLoginconfigTable($pdo, $DB, $prefix, $log, $offset, $limit);
                    $count = $result;
                    break;
                case 'goods':
                    $result = importGoodsTable($pdo, $DB, $prefix, $log, $offset, $limit);
                    $count = $result;
                    break;
                default:
                    exit(json_encode(['code' => -1, 'msg' => '未知表名']));
            }
            exit(json_encode(['code' => 1, 'count' => $count, 'log' => $log, 'offset' => $offset + $count]));
        } catch(Exception $e) {
            exit(json_encode(['code' => -1, 'msg' => $e->getMessage()]));
        }
        break;

    default:
        exit(json_encode(['code' => -1, 'msg' => '未知操作']));
}

// 导入用户表
function importUserTable($pdo, $DB, $prefix, &$log, $offset = 0, $limit = 2000) {
    $oldTable = $prefix . 'user';

    $stmt = $pdo->query("SHOW TABLES LIKE '$oldTable'");
    if($stmt->rowCount() == 0) {
        throw new Exception("老用户表不存在: $oldTable");
    }

    $stmt = $pdo->prepare("SELECT * FROM $oldTable ORDER BY zid ASC LIMIT $offset, $limit");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $count = 0;
    $insertData = [];

    foreach($rows as $row) {

        $insertData[] = [
            $row['zid'],
            $row['upzid'] ?? 0,
            $row['upzid_all'] ?? '',
            $row['type'] ?? 0,
            $row['domain'] ?? '',
            $row['domain2'] ?? '',
            $row['user'] ?? '',
            $row['pwd'] ?? '',
            $row['phone'] ?? '',
            $row['openid_qq'] ?? '',
            $row['openid_wx'] ?? '',
            $row['openid_alipay'] ?? '',
            $row['rmb'] ?? 0,
            $row['rmb_tc'] ?? 0,
            $row['vip'] ?? 1,
            $row['qq'] ?? '',
            $row['kf_wx'] ?? '',
            $row['sitename'] ?? '',
            $row['title'] ?? '',
            $row['keywords'] ?? '',
            $row['description'] ?? '',
            $row['gonggao'] ?? '',
            $row['alert_gonggao'] ?? '',
            $row['status'] ?? 0,
            $row['pay_type'] ?? 0,
            $row['pay_name'] ?? '',
            $row['pay_account'] ?? '',
            $row['pay_img'] ?? '',
            $row['msgread'] ?? '',
            $row['template'] ?? '',
            $row['addtime'] ?? '',
            $row['endtime'] ?? '',
            $row['ip'] ?? '',
            $row['wechat_appuid'] ?? '',
            $row['email'] ?? '',
            $row['notice_type'] ?? 0,
            $row['reason'] ?? '',
            $row['ban_day'] ?? 0,
            $row['uptime'] ?? 0
        ];
        $count++;
    }

    if(!empty($insertData)) {
        // 使用 REPLACE INTO 批量插入，存在则替换
        $sql = "REPLACE INTO pre_user (zid,upzid,upzid_all,type,domain,domain2,user,pwd,phone,openid_qq,openid_wx,openid_alipay,rmb,rmb_tc,vip,qq,kf_wx,sitename,title,keywords,description,gonggao,alert_gonggao,status,pay_type,pay_name,pay_account,pay_img,msgread,template,addtime,endtime,ip,wechat_appuid,email,notice_type,reason,ban_day,uptime) VALUES ";

        $placeholders = [];
        $params = [];
        foreach($insertData as $data) {
            $placeholders[] = '(' . implode(',', array_fill(0, count($data), '?')) . ')';
            $params = array_merge($params, $data);
        }

        $sql .= implode(',', $placeholders);
        $DB->exec($sql, $params);
    }

    $log[] = "导入用户 $count 个";

    return $count;
}

// 导入登录接口配置表（老表 bot_loginconfig → 新表 pre_loginconfig），按当前库 pre_loginconfig 实际存在的列写入，兼容旧表结构无 proxy_url/api_error_check 等
function importLoginconfigTable($pdo, $DB, $prefix, &$log, $offset = 0, $limit = 2000) {
    $oldTable = $prefix . 'loginconfig';

    $stmt = $pdo->query("SHOW TABLES LIKE '$oldTable'");
    if ($stmt->rowCount() == 0) {
        throw new Exception("老登录接口配置表不存在: $oldTable");
    }

    // 获取新系统 pre_loginconfig 表实际存在的列（兼容旧安装无 proxy_url 等列）
    $targetCols = $DB->getAll("SHOW COLUMNS FROM pre_loginconfig");
    $colNames = [];
    foreach ($targetCols as $c) {
        $colNames[] = $c['Field'];
    }

    // 老表字段 → 默认值（仅用于目标表有而老表无的列，如 api_error_check）
    $fieldMap = [
        'id' => null,
        'cid' => null,
        'cids' => null,
        'sort' => null,
        'url' => null,
        'port' => null,
        'type' => null,
        'msg' => null,
        'msg_type' => null,
        'citybz' => null,
        'status' => null,
        'status_api' => null,
        'online_census' => null,
        'max' => null,
        'show_online_census' => null,
        'exclusive' => null,
        'apipwd' => null,
        'notify_time' => null,
        'notify_count' => null,
        'protocol' => null,
        'uptime' => null,
        'hktype' => null,
        'api_error_check' => 1,
    ];

    $stmt = $pdo->prepare("SELECT * FROM $oldTable ORDER BY id ASC LIMIT $offset, $limit");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $count = 0;
    $insertData = [];

    foreach ($rows as $row) {
        $line = [];
        foreach ($colNames as $col) {
            if (array_key_exists($col, $row)) {
                $line[$col] = $row[$col];
            } else {
                $line[$col] = isset($fieldMap[$col]) ? $fieldMap[$col] : null;
            }
        }
        $insertData[] = $line;
        $count++;
    }

    if (empty($insertData)) {
        $log[] = "导入登录接口 0 条";
        return $count;
    }

    $cols = $colNames;
    $colsStr = implode(',', $cols);
    $batchSize = 10;
    $inserted = 0;
    for ($i = 0; $i < count($insertData); $i += $batchSize) {
        $batch = array_slice($insertData, $i, $batchSize);
        $placeholders = [];
        $params = [];
        foreach ($batch as $data) {
            $placeholders[] = '(' . implode(',', array_fill(0, count($data), '?')) . ')';
            $params = array_merge($params, array_values($data));
        }
        $sql = "REPLACE INTO pre_loginconfig ($colsStr) VALUES " . implode(',', $placeholders);
        $ret = $DB->exec($sql, $params);
        if ($ret === false) {
            $err = method_exists($DB, 'error') ? $DB->error() : '未知错误';
            throw new Exception('登录接口写入失败: ' . $err);
        }
        $inserted += count($batch);
    }

    $log[] = "导入登录接口 $inserted 条";
    return $count;
}

// 导入商品表（老表 bot_goods → 新表 pre_goods，按新系统字段映射，老表 priceid 不导入，新表 is_fixed_price/fixed_prices 默认为 0/NULL）
function importGoodsTable($pdo, $DB, $prefix, &$log, $offset = 0, $limit = 2000) {
    $oldTable = $prefix . 'goods';

    $stmt = $pdo->query("SHOW TABLES LIKE '$oldTable'");
    if ($stmt->rowCount() == 0) {
        throw new Exception("老商品表不存在: $oldTable");
    }

    $stmt = $pdo->prepare("SELECT * FROM $oldTable ORDER BY id ASC LIMIT $offset, $limit");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $count = 0;
    $insertData = [];

    foreach ($rows as $row) {
        $insertData[] = [
            $row['id'] ?? 0,
            $row['sort'] ?? 10,
            $row['name'] ?? '',
            $row['type'] ?? 0,
            $row['num'] ?? 1,
            $row['time_type'] ?? 0,
            $row['price'] ?? '0.00',
            $row['status'] ?? 1,
            $row['desc'] ?? null,
            0,   // is_fixed_price 新系统字段，默认 0
            null // fixed_prices 新系统字段，默认 NULL
        ];
        $count++;
    }

    if (!empty($insertData)) {
        $sql = "REPLACE INTO pre_goods (id,sort,name,type,num,time_type,price,status,`desc`,is_fixed_price,fixed_prices) VALUES ";
        $placeholders = [];
        $params = [];
        foreach ($insertData as $data) {
            $placeholders[] = '(' . implode(',', array_fill(0, count($data), '?')) . ')';
            $params = array_merge($params, $data);
        }
        $sql .= implode(',', $placeholders);
        $DB->exec($sql, $params);
    }

    $log[] = "导入商品 $count 条";
    return $count;
}

// 导入登录分类表
function importLoginClassTable($pdo, $DB, $prefix, &$log, $offset = 0, $limit = 2000) {
    $oldTable = $prefix . 'login_class';

    $stmt = $pdo->query("SHOW TABLES LIKE '$oldTable'");
    if($stmt->rowCount() == 0) {
        throw new Exception("老登录分类表不存在: $oldTable");
    }

    $stmt = $pdo->prepare("SELECT * FROM $oldTable ORDER BY id ASC LIMIT $offset, $limit");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $count = 0;
    $skipCount = 0;
    $insertData = [];

    foreach($rows as $row) {
        if($row['id'] == 1000) {
            $skipCount++;
            continue;
        }

        $insertData[] = [
            $row['id'],
            $row['sort'] ?? 50,
            $row['name'] ?? '',
            $row['cid'] ?? 0,
            $row['active'] ?? 0,
            $row['free'] ?? 0
        ];
        $count++;
    }

    if(!empty($insertData)) {
        $sql = "REPLACE INTO pre_login_class (id,sort,name,cid,active,free) VALUES ";
        $placeholders = [];
        $params = [];
        foreach($insertData as $data) {
            $placeholders[] = '(' . implode(',', array_fill(0, count($data), '?')) . ')';
            $params = array_merge($params, $data);
        }
        $sql .= implode(',', $placeholders);
        $DB->exec($sql, $params);
    }

    if($offset == 0) {
        $log[] = "跳过默认分类 $skipCount 个";
    }
    $log[] = "导入分类 $count 个";

    return $count;
}

// 导入QQ账号表
function importQqTable($pdo, $DB, $prefix, &$log, $offset = 0, $limit = 2000) {
    $oldTable = $prefix . 'qq';

    $stmt = $pdo->query("SHOW TABLES LIKE '$oldTable'");
    if($stmt->rowCount() == 0) {
        throw new Exception("老QQ账号表不存在: $oldTable");
    }

    $stmt = $pdo->prepare("SELECT * FROM $oldTable ORDER BY id ASC LIMIT $offset, $limit");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $count = 0;
    $insertData = [];

    foreach($rows as $row) {
        $insertData[] = [
            $row['zid'] ?? 0,
            $row['qq'] ?? '',
            $row['pwd'] ?? '',
            $row['cityid'] ?? 0,
            $row['online'] ?? 0,
            $row['dropline'] ?? 0,
            $row['phoneBrand'] ?? '',
            $row['phoneType'] ?? '',
            $row['protocol'] ?? '',
            $row['skeyzt'] ?? 0,
            $row['skey'] ?? '',
            $row['pskey'] ?? '',
            $row['superkey'] ?? '',
            $row['qq_name'] ?? '',
            0, // login_zt 导入默认为离线
            $row['login_rank'] ?? '',
            $row['login_cuont'] ?? 0,
            $row['login_msg'] ?? '',
            $row['cookie'] ?? '',
            $row['cookie_time'] ?? 0,
            $row['msg'] ?? '',
            $row['uptime'] ?? '',
            $row['addtime'] ?? '',
            $row['endtime'] ?? '',
            $row['endtime_arr'] ?? '',
            $row['end_notify'] ?? '',
            $row['dropline_time'] ?? 0,
            $row['out_notify'] ?? ''
        ];
        $count++;
    }

    if(!empty($insertData)) {
        $sql = "REPLACE INTO pre_qq (zid,qq,pwd,cityid,online,dropline,phoneBrand,phoneType,protocol,skeyzt,skey,pskey,superkey,qq_name,login_zt,login_rank,login_cuont,login_msg,cookie,cookie_time,msg,uptime,addtime,endtime,endtime_arr,end_notify,dropline_time,out_notify) VALUES ";

        $placeholders = [];
        $params = [];
        foreach($insertData as $data) {
            $placeholders[] = '(' . implode(',', array_fill(0, count($data), '?')) . ')';
            $params = array_merge($params, $data);
        }

        $sql .= implode(',', $placeholders);
        $DB->exec($sql, $params);
    }

    $log[] = "导入QQ $count 个";

    return $count;
}

// 导入卡密表
function importKmTable($pdo, $DB, $prefix, &$log, $offset = 0, $limit = 2000) {
    $oldTable = $prefix . 'km';

    $stmt = $pdo->query("SHOW TABLES LIKE '$oldTable'");
    if($stmt->rowCount() == 0) {
        throw new Exception("老卡密表不存在: $oldTable");
    }

    $stmt = $pdo->prepare("SELECT * FROM $oldTable ORDER BY id ASC LIMIT $offset, $limit");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $count = 0;
    $insertData = [];

    foreach($rows as $row) {
        $insertData[] = [
            $row['zid'] ?? 0,
            $row['name'] ?? '',
            $row['km'] ?? '',
            $row['shopid'] ?? '',
            $row['rmb'] ?? 0,
            0, // tc_rmb
            $row['isuse'] ?? 0,
            $row['qq'] ?? '',
            $row['usetime'] ?? '',
            $row['addtime'] ?? '',
            $row['time'] ?? 0,
            $row['time_num'] ?? 0
        ];
        $count++;
    }

    if(!empty($insertData)) {
        // 卡密表使用 INSERT IGNORE，已存在则跳过
        $sql = "INSERT IGNORE INTO pre_km (zid,name,km,shopid,rmb,tc_rmb,isuse,qq,usetime,addtime,time,time_num) VALUES ";

        $placeholders = [];
        $params = [];
        foreach($insertData as $data) {
            $placeholders[] = '(' . implode(',', array_fill(0, count($data), '?')) . ')';
            $params = array_merge($params, $data);
        }

        $sql .= implode(',', $placeholders);
        $DB->exec($sql, $params);
    }

    $log[] = "导入卡密 $count 个";

    return $count;
}
