<?php
include_once('./_common.php');

if ($is_guest) {
    alert('판매자센터만 이용가능합니다.', APMS_PARTNER_URL . '/login.php');
}
if ($is_admin !== 'super') {
    alert('최고관리자만 실행할 수 있습니다.', APMS_PARTNER_URL);
}

@set_time_limit(0);

$table = $g5['apms_vpn_server'];
$column = 'vs_vpn_types';

$dry_run = isset($_GET['dry_run']) ? (int)$_GET['dry_run'] : 1;
$apply = isset($_GET['apply']) ? (int)$_GET['apply'] : 0;
if ($apply === 1) {
    $dry_run = 0;
}

header('Content-Type: text/plain; charset=utf-8');

echo "=== Add {$column} column to {$table} ===\n";
echo "time    : " . G5_TIME_YMDHIS . "\n";
echo "dry_run : {$dry_run}\n";
echo "apply   : {$apply}\n";

$col_row = sql_fetch("show columns from {$table} like '{$column}'", false);
$already_exists = is_array($col_row) && count($col_row) > 0;
echo "exists  : " . ($already_exists ? 'yes' : 'no') . "\n";

if ($already_exists) {
    echo "\n이미 컬럼이 존재합니다. 변경 사항이 없습니다.\n";
    exit;
}

$alter_sql = "ALTER TABLE `{$table}` ADD `{$column}` varchar(255) NOT NULL DEFAULT '' COMMENT '감지된 활성 VPN 프로토콜(콤마구분, 예: IKEv2,L2TP/IPsec)' AFTER `vs_metrics_json`;";

echo "\n--- SQL to run ---\n{$alter_sql}\n";

if ($dry_run === 1 || $apply !== 1) {
    echo "\n[DRY-RUN] 컬럼이 추가되지 않았습니다.\n";
    echo "\n실행 가이드:\n";
    echo "1) 우선 dry-run 확인 (기본): ?dry_run=1\n";
    echo "2) 실제 적용: ?apply=1\n";
    exit;
}

sql_query($alter_sql);

$col_row_after = sql_fetch("show columns from {$table} like '{$column}'", false);
$ok = is_array($col_row_after) && count($col_row_after) > 0;

echo "\nresult: " . ($ok ? 'OK - column added' : 'FAILED') . "\n";
