<?php
require_once __DIR__.'/lomba/db.php';

function addColumnIfNotExists($mysqli, $table, $column, $definition) {
    $check = $mysqli->query("SHOW COLUMNS FROM $table LIKE '$column'");
    if ($check->num_rows == 0) {
        if ($mysqli->query("ALTER TABLE $table ADD COLUMN $column $definition")) {
            echo "Added column $column to $table.\n";
            return true;
        } else {
            echo "Error adding column $column: " . $mysqli->error . "\n";
            return false;
        }
    } else {
        echo "Column $column already exists in $table.\n";
        return false;
    }
}

// Add username (initially without UNIQUE to allow filling data)
if (addColumnIfNotExists($mysqli, 'users', 'username', 'VARCHAR(50)')) {
    // Fill existing users with default username
    $mysqli->query("UPDATE users SET username = CONCAT('user', id) WHERE username IS NULL OR username = ''");
    echo "Filled default usernames.\n";
    
    // Add UNIQUE constraint
    if ($mysqli->query("ALTER TABLE users ADD UNIQUE (username)")) {
        echo "Added UNIQUE constraint to username.\n";
    } else {
        echo "Error adding UNIQUE constraint: " . $mysqli->error . "\n";
    }
}

// Add other columns
addColumnIfNotExists($mysqli, 'users', 'birthday', 'DATE');
addColumnIfNotExists($mysqli, 'users', 'gender', "ENUM('L', 'P')");
addColumnIfNotExists($mysqli, 'users', 'social_networks', 'TEXT');

echo "Schema update completed.\n";
?>
