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

try {
    // Create factions table
    $db->exec("CREATE TABLE IF NOT EXISTS factions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        image_url VARCHAR(255) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    echo "Table 'factions' created or already exists.\n";

    // Add faction_id to planets table
    $cols = $db->query("DESCRIBE planets")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('faction_id', $cols)) {
        $db->exec("ALTER TABLE planets ADD COLUMN faction_id INT DEFAULT NULL AFTER status");
        echo "Column 'faction_id' added to 'planets' table.\n";
    } else {
        echo "Column 'faction_id' already exists in 'planets' table.\n";
    }

    // Check if 'Aucune' faction exists
    $stmt = $db->prepare("SELECT COUNT(*) FROM factions WHERE name = 'Aucune'");
    $stmt->execute();
    if ($stmt->fetchColumn() == 0) {
        $db->exec("INSERT INTO factions (name) VALUES ('Aucune')");
        echo "Default faction 'Aucune' created.\n";
    }

} catch (PDOException $e) {
    die("Migration failed: " . $e->getMessage());
}

