<?php
// apply_account_flags.php: Apply only the account restriction columns migration
// Safe to run multiple times; will skip if columns exist

define('TONSUI_LOADED', true);
require_once __DIR__ . '/../db.php';

function columnExists(PDO $pdo, $table, $column) {
    $stmt = $pdo->prepare("SHOW COLUMNS FROM `$table` LIKE ?");
    $stmt->execute([$column]);
    return $stmt->rowCount() > 0;
}

try {
    $added = [];

    if (!columnExists($pdo, 'users', 'account_suspended')) {
        $pdo->exec("ALTER TABLE `users` ADD COLUMN `account_suspended` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'If 1, user account access restricted'");
        $added[] = 'account_suspended';
    }

    if (!columnExists($pdo, 'users', 'transfers_suspended')) {
        $pdo->exec("ALTER TABLE `users` ADD COLUMN `transfers_suspended` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'If 1, outgoing transfers/withdrawals blocked'");
        $added[] = 'transfers_suspended';
    }

    if (!columnExists($pdo, 'users', 'account_dormant')) {
        $pdo->exec("ALTER TABLE `users` ADD COLUMN `account_dormant` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'If 1, dormant; implies transfers suspended and show alerts'");
        $added[] = 'account_dormant';
    }

    header('Content-Type: text/plain');
    if (empty($added)) {
        echo "No changes. Columns already exist.\n";
    } else {
        echo "Added columns: " . implode(', ', $added) . "\n";
    }
} catch (Exception $e) {
    header('Content-Type: text/plain', true, 500);
    echo "Error applying account flags: " . $e->getMessage() . "\n";
    exit(1);
}
