-- ============================================
-- Migration: 003_admin_account_payment_config
-- Created:   2026-08-27
-- Author:    Claude (v6.2 Phase 5)
-- Purpose:   admin_account 表新增 can_use_payment_config 欄位
--            讓 admin 在使用者權限管理頁可以勾選「付款設定」權限。
--            沒此權限的人(包含所有運營商帳號)即使知道 URL 也進不去
--            EVmcloud/payment_gateway.php。
--            v6.2 設計見 INVENTORY §11.45 (Phase 5 perm 規劃)
--
-- Depends on:  v6.0 月結報表 perm 已存在(可選,本 migration 獨立)
-- Reversible: YES (見下方 DOWN 段)
-- ============================================

-- ---------- UP ----------

-- 先檢查欄位是否已存在(給重跑冪等),MySQL 沒原生 IF NOT EXISTS for ADD COLUMN 用 procedure 包
SET @col_exists = (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'admin_account'
    AND COLUMN_NAME = 'can_use_payment_config'
);

SET @ddl = IF(
  @col_exists = 0,
  'ALTER TABLE `admin_account` ADD COLUMN `can_use_payment_config` INT(11) DEFAULT NULL COMMENT ''可閱覽付款設定'' AFTER `can_use_monthreport`',
  'SELECT ''can_use_payment_config column already exists, skip'' AS status'
);

PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 把現有「總Admin」(user_role_name = '總Admin')預設開啟,
-- 一般 admin 帳號需要手動去權限管理頁勾選(保守,避免大爆權限)
UPDATE `admin_account`
SET `can_use_payment_config` = 1
WHERE `user_role_name` = '總Admin'
  AND (`can_use_payment_config` IS NULL OR `can_use_payment_config` <> 1);

-- ---------- DOWN ----------

-- MySQL 5.7 不支援 DROP COLUMN IF EXISTS,所以先查詢確認存在
SET @col_exists = (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'admin_account'
    AND COLUMN_NAME = 'can_use_payment_config'
);

SET @ddl = IF(
  @col_exists = 1,
  'ALTER TABLE `admin_account` DROP COLUMN `can_use_payment_config`',
  'SELECT ''can_use_payment_config column not found, skip'' AS status'
);

PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
