<?php
/**
 * 程序分类迁移脚本 - 基于市面 PHP 网站分类重新规划
 * 
 * 访问: /admin/migrate_categories.php
 * 需管理员登录，支持预览模式(?preview=1)和实际执行
 */
require_once __DIR__ . '/../MPHX/common.php';

header('Content-Type: text/html; charset=UTF-8');

if (!is_admin_login()) {
    echo '<p style="color:red;">请先登录后台</p>';
    exit;
}

$preview = isset($_GET['preview']) ? true : false;
$execute = isset($_GET['execute']) && $_GET['execute'] === '1';

// 基于市面 PHP 网站分类的规划（参考：织梦、帝国、Discuz、ECShop、易支付、微擎等主流分类）
$new_categories = array(
    array('name' => 'CMS系统', 'icon' => 'fa fa-cubes', 'desc' => '内容管理系统：织梦、帝国、PHPCMS、迅睿等', 'sort' => 1),
    array('name' => '博客系统', 'icon' => 'fa fa-rss', 'desc' => '博客程序：WordPress、Typecho、Z-Blog、Emlog', 'sort' => 2),
    array('name' => '电商系统', 'icon' => 'fa fa-shopping-cart', 'desc' => '电子商务：ECShop、ShopEx、ShopXO、WooCommerce', 'sort' => 3),
    array('name' => '论坛系统', 'icon' => 'fa fa-comments', 'desc' => '论坛社区：Discuz、phpBB、HYBBS', 'sort' => 4),
    array('name' => '企业官网', 'icon' => 'fa fa-building', 'desc' => '企业建站：米拓、DM建站、展示型网站', 'sort' => 5),
    array('name' => '支付系统', 'icon' => 'fa fa-credit-card', 'desc' => '支付收款：易支付、码支付、虎皮椒', 'sort' => 6),
    array('name' => '授权/代理', 'icon' => 'fa fa-key', 'desc' => '授权发卡：授权系统、卡密系统、代理系统', 'sort' => 7),
    array('name' => '微信/小程序', 'icon' => 'fa fa-weixin', 'desc' => '微信生态：微擎、壹佰云、小程序', 'sort' => 8),
    array('name' => '在线教育', 'icon' => 'fa fa-graduation-cap', 'desc' => '网校系统：MeEdu、云课网校', 'sort' => 9),
    array('name' => '问答/社交', 'icon' => 'fa fa-question-circle', 'desc' => '问答社区：Tipask、Whatsns', 'sort' => 10),
    array('name' => '其他', 'icon' => 'fa fa-folder', 'desc' => '其他类型程序', 'sort' => 99),
);

// 程序类型迁移映射（旧 type -> 新 type）
$type_migration = array(
    'other' => '其他',
    '支付' => '支付系统',
    '易支付' => '支付系统',
    '支付系统' => '支付系统',
    '授权' => '授权/代理',
    '代理' => '授权/代理',
    '发卡' => '授权/代理',
);

// 程序名称关键词 -> 新分类（用于将"其他"下的程序智能迁移）
$name_keyword_migration = array(
    '支付' => '支付系统',
    '易支付' => '支付系统',
    '码支付' => '支付系统',
    '虎皮椒' => '支付系统',
    '授权' => '授权/代理',
    '鼠大侠' => '授权/代理',
    '卡密' => '授权/代理',
    '发卡' => '授权/代理',
    '代理' => '授权/代理',
);

echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>分类迁移</title>";
echo "<link rel='stylesheet' href='/static/css/bootstrap.min.css'></head><body class='p-4'>";
echo "<div class='container'><h2>程序分类迁移 - 基于市面 PHP 网站分类</h2>";
echo "<p class='text-muted'>参考主流建站系统分类：织梦、帝国、Discuz、ECShop、易支付、微擎等</p><hr>";

// 获取当前分类
$current_cats = array();
$res = $DB->query("SELECT * FROM `program_categories` ORDER BY `sort_order` ASC, `id` ASC");
while ($row = $DB->fetch($res)) {
    $current_cats[] = $row;
}

// 获取表结构
$columns = array();
$col_res = $DB->query("SHOW COLUMNS FROM `program_categories`");
while ($col = $DB->fetch($col_res)) {
    $columns[] = $col['Field'];
}
$has_description = in_array('description', $columns);
$has_status = in_array('status', $columns);

if ($preview) {
    echo "<div class='alert alert-info'><strong>预览模式</strong> - 仅显示将要执行的操作，不修改数据</div>";
    echo "<h4>新分类规划（共 " . count($new_categories) . " 项）</h4>";
    echo "<table class='table table-bordered'><thead><tr><th>排序</th><th>分类名称</th><th>图标</th><th>描述</th></tr></thead><tbody>";
    foreach ($new_categories as $c) {
        echo "<tr><td>{$c['sort']}</td><td>{$c['name']}</td><td><i class='{$c['icon']}'></i> {$c['icon']}</td><td>{$c['desc']}</td></tr>";
    }
    echo "</tbody></table>";
    
    // 统计当前程序分布
    echo "<h4>当前程序类型分布</h4>";
    $type_res = $DB->query("SELECT `type`, COUNT(*) as cnt FROM `bs` GROUP BY `type`");
    echo "<table class='table table-sm'><thead><tr><th>类型</th><th>程序数</th><th>迁移后</th></tr></thead><tbody>";
    while ($row = $DB->fetch($type_res)) {
        $new_type = isset($type_migration[$row['type']]) ? $type_migration[$row['type']] : $row['type'];
        $migrate_note = ($new_type != $row['type']) ? '<span class="text-warning">将迁移</span>' : '-';
        echo "<tr><td>{$row['type']}</td><td>{$row['cnt']}</td><td>{$new_type} {$migrate_note}</td></tr>";
    }
    echo "</tbody></table>";
    
    // 智能迁移预览（"其他"下将按名称迁移的程序）
    $other_esc = $DB->escape('其他');
    $other_progs = $DB->get_all("SELECT id, name FROM `bs` WHERE `type`='{$other_esc}' OR `type`='other'");
    if (!empty($other_progs)) {
        echo "<h4>「其他」分类下的智能迁移预览</h4>";
        echo "<table class='table table-sm'><thead><tr><th>程序名称</th><th>迁移到</th></tr></thead><tbody>";
        foreach ($other_progs as $p) {
            $target = '其他（保持）';
            foreach ($name_keyword_migration as $keyword => $new_type) {
                if (mb_strpos($p['name'], $keyword) !== false) {
                    $target = $new_type;
                    break;
                }
            }
            echo "<tr><td>" . htmlspecialchars($p['name']) . "</td><td>{$target}</td></tr>";
        }
        echo "</tbody></table>";
    }
    
    echo "<p><a href='migrate_categories.php?execute=1' class='btn btn-primary' onclick=\"return confirm('确定执行迁移？将清空并重建分类表。')\">执行迁移</a> ";
    echo "<a href='category.php' class='btn btn-secondary'>返回分类管理</a></p>";
    echo "</div></body></html>";
    exit;
}

if ($execute) {
    echo "<div class='alert alert-warning'>正在执行迁移...</div>";
    
    // 1. 迁移程序的 type 字段（按类型映射）
    foreach ($type_migration as $old_type => $new_type) {
        if ($old_type !== $new_type) {
            $old_esc = $DB->escape($old_type);
            $new_esc = $DB->escape($new_type);
            $DB->query("UPDATE `bs` SET `type`='{$new_esc}' WHERE `type`='{$old_esc}'");
            $affected = $DB->affected();
            if ($affected > 0) {
                echo "<p>已迁移 {$affected} 个程序：{$old_type} → {$new_type}</p>";
            }
        }
    }
    
    // 2. 智能迁移：将"其他"分类下名称含关键词的程序迁移到对应分类
    $other_esc = $DB->escape('其他');
    $progs = $DB->get_all("SELECT id, name, type FROM `bs` WHERE `type`='{$other_esc}'");
    foreach ($progs as $p) {
        $name = $p['name'];
        foreach ($name_keyword_migration as $keyword => $new_type) {
            if (mb_strpos($name, $keyword) !== false) {
                $new_esc = $DB->escape($new_type);
                $DB->query("UPDATE `bs` SET `type`='{$new_esc}' WHERE `id`=" . intval($p['id']));
                echo "<p>智能迁移：{$name} → {$new_type}</p>";
                break;
            }
        }
    }
    
    // 3. 清空并重建分类表
    $DB->query("TRUNCATE TABLE `program_categories`");
    
    // 4. 插入新分类
    foreach ($new_categories as $c) {
        $name = $DB->escape($c['name']);
        $icon = $DB->escape($c['icon']);
        $desc = $DB->escape($c['desc']);
        $sort = intval($c['sort']);
        
        $sql = "INSERT INTO `program_categories` (`name`, `icon`, `sort_order`) VALUES ('{$name}', '{$icon}', {$sort})";
        if ($has_description) {
            $sql = "INSERT INTO `program_categories` (`name`, `icon`, `description`, `sort_order`) VALUES ('{$name}', '{$icon}', '{$desc}', {$sort})";
        }
        $DB->query($sql);
    }
    
    echo "<div class='alert alert-success'><strong>迁移完成！</strong> 已更新 " . count($new_categories) . " 个分类</div>";
    echo "<p><a href='category.php' class='btn btn-primary'>查看分类管理</a> <a href='list.php?gn=cx' class='btn btn-secondary'>程序列表</a></p>";
    logjl(is_admin_login(), '程序分类', '执行分类迁移，共 ' . count($new_categories) . ' 个分类', true);
} else {
    echo "<div class='alert alert-info'>";
    echo "<h5>新分类规划说明</h5>";
    echo "<ul>";
    echo "<li><strong>CMS系统</strong> - 织梦、帝国、PHPCMS、迅睿CMS</li>";
    echo "<li><strong>博客系统</strong> - WordPress、Typecho、Z-Blog、Emlog</li>";
    echo "<li><strong>电商系统</strong> - ECShop、ShopEx、ShopXO、WooCommerce</li>";
    echo "<li><strong>论坛系统</strong> - Discuz、phpBB、HYBBS</li>";
    echo "<li><strong>企业官网</strong> - 米拓、DM建站、企业展示站</li>";
    echo "<li><strong>支付系统</strong> - 易支付、码支付、虎皮椒（新增）</li>";
    echo "<li><strong>授权/代理</strong> - 授权系统、卡密、发卡、代理系统（新增）</li>";
    echo "<li><strong>微信/小程序</strong> - 微擎、壹佰云（新增）</li>";
    echo "<li><strong>在线教育</strong> - MeEdu、云课网校（新增）</li>";
    echo "<li><strong>问答/社交</strong> - Tipask、Whatsns（新增）</li>";
    echo "<li><strong>其他</strong> - 兜底分类</li>";
    echo "</ul></div>";
    echo "<p><a href='migrate_categories.php?preview=1' class='btn btn-info'>预览迁移</a> ";
    echo "<a href='category.php' class='btn btn-secondary'>分类管理</a></p>";
}

echo "</div></body></html>";
