<?php
/**
 * One-off migration: adds additional_info column to mf_participant.
 *
 * Usage:
 * - Browser: /_rejestracja/sql/apply-2026-04-27-additional-info-field.php?run=20260427
 * - CLI:     php apply-2026-04-27-additional-info-field.php --run
 *
 * Remove this file from the server after a successful production run.
 */

ini_set('display_errors', 1);
error_reporting(E_ALL);

$isCli = PHP_SAPI === 'cli';
$approved = $isCli
    ? in_array('--run', $argv, true)
    : (isset($_GET['run']) && $_GET['run'] === '20260427');

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

if (!$approved) {
    echo "DRY RUN ONLY\n";
    echo "To apply migration, run with ?run=20260427 in browser or --run in CLI.\n";
    echo "No database changes were made.\n";
    exit;
}

$configPath = __DIR__ . '/../core/config/Strona/db.config.ini';
if (!is_file($configPath)) {
    fail("Config file not found: " . $configPath);
}

$config = parse_ini_file($configPath, true);
if (!isset($config['db'])) {
    fail("Missing [db] section in config.");
}

$dbConfig = $config['db'];
foreach (array('prodHost', 'prodUser', 'prodPass', 'prodDb') as $key) {
    if (!array_key_exists($key, $dbConfig)) {
        fail("Missing db config key: " . $key);
    }
}

$mysqli = new mysqli(
    $dbConfig['prodHost'],
    $dbConfig['prodUser'],
    $dbConfig['prodPass'],
    $dbConfig['prodDb']
);

if ($mysqli->connect_errno) {
    fail("MySQL connection failed: " . $mysqli->connect_error);
}

$mysqli->set_charset('utf8');

echo "Checking mf_participant.additional_info column...\n";

$result = $mysqli->query(
    "SELECT COUNT(*) AS cnt
     FROM INFORMATION_SCHEMA.COLUMNS
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME   = 'mf_participant'
       AND COLUMN_NAME  = 'additional_info'"
);

if (!$result) {
    fail("INFORMATION_SCHEMA query failed: " . $mysqli->error);
}

$row = $result->fetch_assoc();

if ((int)$row['cnt'] > 0) {
    echo "Column additional_info already exists. Nothing to do.\n";
    $mysqli->close();
    exit;
}

if (!$mysqli->query("ALTER TABLE `mf_participant` ADD COLUMN `additional_info` TEXT NULL DEFAULT NULL AFTER `nip`")) {
    fail("ALTER TABLE failed: " . $mysqli->error);
}

echo "Column additional_info added successfully.\n";
$mysqli->close();

function fail($message) {
    echo "ERROR: " . $message . "\n";
    exit(1);
}

function header_safe($header) {
    if (!headers_sent() && PHP_SAPI !== 'cli') {
        header($header);
    }
}

?>
