<?php
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit('Access denied.');
}

require_once __DIR__ . '/app/bootstrap.php';
use App\Core\Database;

try {
    echo "=== Migrating Billing Tables ===\n";

    // 1. Alter company_subscriptions to support new fields and ENUM
    Database::execute("
        ALTER TABLE company_subscriptions
        MODIFY COLUMN status ENUM('active', 'trialing', 'canceled', 'expired', 'past_due', 'pending_approval') DEFAULT 'active';
    ");
    echo "✅ Updated 'status' ENUM in company_subscriptions.\n";

    // Add payment_method if it doesn't exist
    try {
        Database::execute("ALTER TABLE company_subscriptions ADD COLUMN payment_method VARCHAR(50) NULL COMMENT 'paymob, cliq, binance' AFTER payment_gateway");
        echo "✅ Added 'payment_method' column.\n";
    } catch (\Exception $e) {
        echo "ℹ️ Column 'payment_method' may already exist. Skipping.\n";
    }

    // Add receipt_reference if it doesn't exist
    try {
        Database::execute("ALTER TABLE company_subscriptions ADD COLUMN receipt_reference VARCHAR(255) NULL COMMENT 'External transaction ID or receipt URL' AFTER payment_method");
        echo "✅ Added 'receipt_reference' column.\n";
    } catch (\Exception $e) {
        echo "ℹ️ Column 'receipt_reference' may already exist. Skipping.\n";
    }

    echo "=== Migration Completed Successfully! ===\n";
} catch (\Exception $e) {
    echo "❌ Migration Failed: " . $e->getMessage() . "\n";
}
