<?php
require 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();

try {
    $pdo = new PDO(
        "mysql:host=" . $_ENV['DB_HOST'] . ";dbname=" . $_ENV['DB_NAME'],
        $_ENV['DB_USER'],
        $_ENV['DB_PASS']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo "=== Running Database Migrations: Super Admin Features ===\n";

    // 1. Add max_agents to subscription_plans if not exists
    $result = $pdo->query("SHOW COLUMNS FROM `subscription_plans` LIKE 'max_agents'");
    if ($result->rowCount() === 0) {
        $pdo->exec("ALTER TABLE `subscription_plans` ADD COLUMN `max_agents` INT DEFAULT 1 AFTER `max_sessions`");
        echo "✅ Added 'max_agents' column to 'subscription_plans' table.\n";
    } else {
        echo "ℹ️ Column 'max_agents' already exists in 'subscription_plans' table. Skipping.\n";
    }

    // 2. Update default plans limits (Starter: 1, Growth: 3, Pro: 10)
    $pdo->exec("UPDATE `subscription_plans` SET `max_agents` = 1 WHERE `id` = 1");
    $pdo->exec("UPDATE `subscription_plans` SET `max_agents` = 3 WHERE `id` = 2");
    $pdo->exec("UPDATE `subscription_plans` SET `max_agents` = 10 WHERE `id` = 3");
    
    echo "✅ Updated default subscription plans limits.\n";
    
    echo "Migration completed successfully!\n";
} catch (PDOException $e) {
    echo "❌ Database error: " . $e->getMessage() . "\n";
}
