-- ===========================================
-- 班级操行分管理系统 - v1.5 → v1.6 升级脚本
-- 字符集: utf8mb4
--
-- 变更内容:
--   1. subjects 表添加 subject_code 列（科目代码）
--   2. subjects 表添加 sort_order 列（排序序号）
--   3. 更新已有科目的 subject_code
--
-- 兼容性: 使用存储过程实现幂等，phpMyAdmin 可直接执行
-- ===========================================

-- 升级步骤 1: subjects 添加 subject_code 列
DROP PROCEDURE IF EXISTS `upgrade_step`;
DELIMITER $$
CREATE PROCEDURE `upgrade_step`()
BEGIN
    IF NOT EXISTS (
        SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'subjects' 
          AND COLUMN_NAME = 'subject_code'
    ) THEN
        ALTER TABLE `subjects` 
        ADD COLUMN `subject_code` VARCHAR(20) DEFAULT NULL COMMENT '科目代码' 
        AFTER `subject_name`;
    END IF;
END$$
DELIMITER ;

CALL `upgrade_step`();
DROP PROCEDURE IF EXISTS `upgrade_step`;

-- 升级步骤 2: subjects 添加 sort_order 列
DROP PROCEDURE IF EXISTS `upgrade_step`;
DELIMITER $$
CREATE PROCEDURE `upgrade_step`()
BEGIN
    IF NOT EXISTS (
        SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
          AND TABLE_NAME = 'subjects' 
          AND COLUMN_NAME = 'sort_order'
    ) THEN
        ALTER TABLE `subjects` 
        ADD COLUMN `sort_order` INT DEFAULT 0 COMMENT '排序序号' 
        AFTER `is_active`;
    END IF;
END$$
DELIMITER ;

CALL `upgrade_step`();
DROP PROCEDURE IF EXISTS `upgrade_step`;

-- 升级步骤 3: 更新已有科目的 subject_code
UPDATE `subjects` SET `subject_code` = 'CHI' WHERE `subject_name` = '语文' AND (`subject_code` IS NULL OR `subject_code` = '');
UPDATE `subjects` SET `subject_code` = 'MATH' WHERE `subject_name` = '数学' AND (`subject_code` IS NULL OR `subject_code` = '');
UPDATE `subjects` SET `subject_code` = 'ENG' WHERE `subject_name` = '英语' AND (`subject_code` IS NULL OR `subject_code` = '');

-- 升级步骤 4: 设置默认排序
UPDATE `subjects` SET `sort_order` = 1 WHERE `subject_name` = '语文' AND `sort_order` = 0;
UPDATE `subjects` SET `sort_order` = 2 WHERE `subject_name` = '数学' AND `sort_order` = 0;
UPDATE `subjects` SET `sort_order` = 3 WHERE `subject_name` = '英语' AND `sort_order` = 0;
