<?php
/**
 * Migration Runner - Add Paystack columns to database
 * Access this file in your browser: http://localhost/TellerPro/run_paystack_migration.php
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';

header('Content-Type: text/html; charset=utf-8');

echo '<!DOCTYPE html>
<html>
<head>
    <title>Paystack Migration</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; max-width: 800px; margin: 0 auto; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        pre { background: #f5f5f5; padding: 10px; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>Paystack Integration Migration</h1>';

try {
    echo '<p class="info">Starting migration...</p>';

    // Add Paystack columns to subscriptions table one by one
    $columns = [
        'payment_method' => "ENUM('manual','paystack','stripe') DEFAULT 'manual'",
        'paystack_reference' => 'VARCHAR(100) NULL',
        'paystack_subscription_code' => 'VARCHAR(100) NULL',
        'paystack_customer_code' => 'VARCHAR(100) NULL'
    ];

    foreach ($columns as $column => $definition) {
        try {
            // Check if column exists
            $check = db()->query("SHOW COLUMNS FROM subscriptions LIKE '$column'");
            if ($check->rowCount() == 0) {
                $sql = "ALTER TABLE subscriptions ADD COLUMN $column $definition";
                db()->exec($sql);
                echo '<p class="success">✓ Added ' . $column . ' column to subscriptions table</p>';
            } else {
                echo '<p class="info">⊘ ' . $column . ' column already exists in subscriptions table</p>';
            }
        } catch (Exception $e) {
            echo '<p class="error">✗ Failed to add ' . $column . ': ' . htmlspecialchars($e->getMessage()) . '</p>';
        }
    }

    // Add Paystack plan code column to plans table
    try {
        $check = db()->query("SHOW COLUMNS FROM plans LIKE 'paystack_plan_code'");
        if ($check->rowCount() == 0) {
            $sql = "ALTER TABLE plans ADD COLUMN paystack_plan_code VARCHAR(100) NULL AFTER features";
            db()->exec($sql);
            echo '<p class="success">✓ Added paystack_plan_code column to plans table</p>';
        } else {
            echo '<p class="info">⊘ paystack_plan_code column already exists in plans table</p>';
        }
    } catch (Exception $e) {
        echo '<p class="error">✗ Failed to add paystack_plan_code: ' . htmlspecialchars($e->getMessage()) . '</p>';
    }

    echo '<h2 class="success">Migration completed successfully!</h2>';
    echo '<p><a href="index.php">Return to application</a></p>';

} catch (Exception $e) {
    echo '<h2 class="error">Migration failed</h2>';
    echo '<pre class="error">' . htmlspecialchars($e->getMessage()) . '</pre>';
    echo '<p>Please check your database configuration and try again.</p>';
}

echo '</body>
</html>';
