<?php
/**
 * One-off migration runner for XXXV Konferencja registration form fields.
 *
 * Usage:
 * - Browser: /_rejestracja/sql/apply-2026-04-24-registration-form-update.php?run=20260424
 * - CLI:     php apply-2026-04-24-registration-form-update.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'] === '20260424');

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

if (!$approved) {
    echo "DRY RUN ONLY\n";
    echo "To apply migration, run with ?run=20260424 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');

$table = 'mf_participant';
$columns = array(
    'participation_option' => array('definition' => "VARCHAR(50) NULL", 'after' => 'conference_fee'),
    'participation_days' => array('definition' => "VARCHAR(255) NULL", 'after' => 'participation_option'),
    'one_day_lodging' => array('definition' => "TINYINT(1) NULL DEFAULT 0", 'after' => 'participation_days'),
    'diet_special' => array('definition' => "VARCHAR(255) NULL", 'after' => 'diet'),
    'fee_room1' => array('definition' => "TINYINT(1) NULL DEFAULT 0", 'after' => 'fee_full'),
    'fee_room_add_person' => array('definition' => "TINYINT(1) NULL DEFAULT 0", 'after' => 'fee_room1'),
);

echo "Applying migration for table `" . $table . "`...\n";

foreach ($columns as $column => $meta) {
    if (column_exists($mysqli, $dbConfig['prodDb'], $table, $column)) {
        echo "SKIP: `" . $column . "` already exists.\n";
        continue;
    }

    $afterSql = '';
    if (!empty($meta['after']) && column_exists($mysqli, $dbConfig['prodDb'], $table, $meta['after'])) {
        $afterSql = " AFTER `" . $mysqli->real_escape_string($meta['after']) . "`";
    }

    $sql = "ALTER TABLE `" . $table . "` ADD COLUMN `" . $column . "` " . $meta['definition'] . $afterSql;
    if (!$mysqli->query($sql)) {
        fail("FAILED adding `" . $column . "`: " . $mysqli->error . "\nSQL: " . $sql);
    }

    echo "OK: added `" . $column . "`.\n";
}

echo "Migration complete.\n";
$mysqli->close();

function column_exists(mysqli $mysqli, $dbName, $table, $column) {
    $sql = "SELECT COUNT(*) AS cnt
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = ?
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?";

    $stmt = $mysqli->prepare($sql);
    if (!$stmt) {
        fail("Prepare failed: " . $mysqli->error);
    }

    $stmt->bind_param('sss', $dbName, $table, $column);
    if (!$stmt->execute()) {
        fail("Column check failed: " . $stmt->error);
    }

    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();

    return isset($row['cnt']) && (int)$row['cnt'] > 0;
}

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

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

