<?php
require_once __DIR__ . '/config.php';
$db = db();

try {
    // 1. Create settlement_sizes table
    $db->exec("CREATE TABLE IF NOT EXISTS settlement_sizes (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        slug VARCHAR(50) NOT NULL,
        description TEXT
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // 2. Insert default sizes if empty
    $count = $db->query("SELECT COUNT(*) FROM settlement_sizes")->fetchColumn();
    if ($count == 0) {
        $db->exec("INSERT INTO settlement_sizes (name, slug, description) VALUES 
            ('Minuscule', 'minuscule', 'Très petit établissement.'),
            ('Petit', 'petit', 'Établissement mineur.'),
            ('Moyen', 'moyen', 'Établissement standard.'),
            ('Grand', 'grand', 'Métropole importante.'),
            ('Gigantesque', 'gigantesque', 'Centre urbain colossal.')");
    }

    // 3. Ensure settlement_types has better data (just types)
    // We'll keep existing but maybe add more
    $count = $db->query("SELECT COUNT(*) FROM settlement_types")->fetchColumn();
    if ($count <= 5) { // If it only has the old mixed ones
        $db->exec("INSERT INTO settlement_types (name, slug, description) VALUES 
            ('Base Militaire', 'base_militaire', 'Installation de défense.'),
            ('Station de Recherche', 'station_recherche', 'Laboratoire scientifique.')");
    }

    // 4. Update cities table
    // First, add new columns
    $db->exec("ALTER TABLE cities ADD COLUMN settlement_type_id INT NULL AFTER planet_id;");
    $db->exec("ALTER TABLE cities ADD COLUMN settlement_size_id INT NULL AFTER settlement_type_id;");

    // Try to migrate old data if any
    // Map old enum strings to IDs (rough estimation)
    $db->exec("UPDATE cities SET settlement_type_id = 1 WHERE type = 'avant-poste'");
    $db->exec("UPDATE cities SET settlement_type_id = 2 WHERE type != 'avant-poste'");
    $db->exec("UPDATE cities SET settlement_size_id = 2 WHERE type = 'petite'");
    $db->exec("UPDATE cities SET settlement_size_id = 3 WHERE type = 'moyenne'");
    $db->exec("UPDATE cities SET settlement_size_id = 4 WHERE type = 'grande'");
    $db->exec("UPDATE cities SET settlement_size_id = 5 WHERE type = 'mégacité'");

    // Drop old type column
    $db->exec("ALTER TABLE cities DROP COLUMN type;");

    echo "Migration successful!\n";
} catch (Exception $e) {
    echo "Error during migration: " . $e->getMessage() . "\n";
}

