<?php
namespace Peak;

use PDO;

class Migration {
    public static function run(): void {
        try {
            $pdo = new PDO("mysql:host=" . Config::$DB_HOST . ";charset=utf8mb4", Config::$DB_USER, Config::$DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `" . Config::$DB_NAME . "` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `" . Config::$DB_NAME . "`");
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            Database::ensureTables($pdo);
            echo "  ✓ All tables created\n";
            echo "\n✓ Migration completed!\n";
        } catch (\PDOException $e) {
            echo "Migration failed: " . $e->getMessage() . "\n";
            exit(1);
        }
    }

    public static function seed(): void {
        try {
            $pdo = new PDO("mysql:host=" . Config::$DB_HOST . ";dbname=" . Config::$DB_NAME . ";charset=utf8mb4", Config::$DB_USER, Config::$DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            Database::ensureSeedData($pdo);
            echo "  ✓ Default settings and admin user seeded\n";
            echo "\n✓ Seed completed!\n";
        } catch (\PDOException $e) {
            echo "Seed failed: " . $e->getMessage() . "\n";
            exit(1);
        }
    }

    public static function renderUI(): void {
        header('Content-Type: text/html; charset=utf-8');
        echo '<!DOCTYPE html><html><head><title>Peak Platform — Migration</title><style>body{font-family:monospace;background:#0F1115;color:#E5E7EB;padding:40px;max-width:600px;margin:0 auto;}h1{font-weight:300;font-size:24px;}pre{background:#1A1D24;padding:16px;border-radius:8px;color:#22C55E;}.btn{display:inline-block;padding:12px 24px;border-radius:100px;background:linear-gradient(135deg,#B0B8C4,#9CA3AF);color:#0F1115;text-decoration:none;font-size:12px;font-weight:600;margin:8px 4px;}</style></head><body>';
        echo '<h1>Peak Platform — Setup</h1>';
        if (isset($_GET['run'])) {
            echo '<pre>';
            if ($_GET['run'] === 'migrate') { self::run(); echo "\n"; self::seed(); }
            elseif ($_GET['run'] === 'seed') { self::seed(); }
            else { echo "Unknown command.\n"; }
            echo '</pre>';
            echo '<p><a href="?" class="btn">← Back</a></p>';
        } else {
            echo '<p>Choose an action:</p>';
            echo '<p><a href="?run=migrate" class="btn">Run Migration + Seed</a></p>';
            echo '<p><a href="?run=seed" class="btn">Run Seed Only</a></p>';
        }
        echo '</body></html>';
        exit;
    }
}
