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

try {
    // Add slug to factions table
    $cols = $db->query("DESCRIBE factions")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('slug', $cols)) {
        // Add slug after name
        $db->exec("ALTER TABLE factions ADD COLUMN slug VARCHAR(100) NULL AFTER name");
        echo "Column 'slug' added to 'factions' table.\n";
        
        // Populate existing slugs with slugified names
        $factions = $db->query("SELECT id, name FROM factions")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($factions as $f) {
            $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $f['name'])));
            $stmt = $db->prepare("UPDATE factions SET slug = ? WHERE id = ?");
            $stmt->execute([$slug, $f['id']]);
        }
        echo "Existing slugs populated.\n";
    } else {
        echo "Column 'slug' already exists in 'factions' table.\n";
    }

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

