<?php
/**
 * Web Interface for API Module Database Migrations
 * Access this file through your browser to run migrations
 */

// Define necessary constants
define('BASEPATH', true);
define('APPPATH', '../application/');
define('ENVIRONMENT', 'production');

require_once '../../index.php';

$CI =& get_instance();

// Check if user is admin
if (!is_admin()) {
    die('<div style="color: red; font-family: Arial, sans-serif; padding: 20px;">
        <h2>Access Denied</h2>
        <p>You must be logged in as an administrator to access this page.</p>
        <a href="../admin">Go to Admin Panel</a>
    </div>');
}

// Check if API module is active
if (!$CI->app_modules->is_active('api')) {
    die('<div style="color: red; font-family: Arial, sans-serif; padding: 20px;">
        <h2>API Module Not Active</h2>
        <p>The API module must be activated before running migrations.</p>
        <p>Go to <strong>Setup → Modules</strong> and activate the API module.</p>
        <a href="../admin/modules">Go to Modules</a>
    </div>');
}

$message = '';
$action = isset($_POST['action']) ? $_POST['action'] : '';
$target_version = isset($_POST['target_version']) ? (int)$_POST['target_version'] : null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        require_once 'migration_runner.php';

        $runner = new APIMigrationRunner();

        switch ($action) {
            case 'upgrade':
                $success = $runner->run($target_version, false);
                $message = $success ?
                    '<div style="color: green;">✅ All migrations completed successfully!</div>' :
                    '<div style="color: red;">❌ Some migrations failed. Check the output above.</div>';
                break;

            case 'rollback':
                $success = $runner->run($target_version, true);
                $message = $success ?
                    '<div style="color: green;">✅ Rollback completed successfully!</div>' :
                    '<div style="color: red;">❌ Rollback failed. Check the output above.</div>';
                break;

            case 'check_status':
                // Just show current status
                break;
        }
    } catch (Exception $e) {
        $message = '<div style="color: red;">❌ Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// Get current status
$current_version = 0;
$migration_table = db_prefix() . 'migrations';

if ($CI->db->table_exists('migrations')) {
    $result = $CI->db->select('version')->from('migrations')->where('module', 'api')->get();
    if ($result->num_rows() > 0) {
        $current_version = $result->row()->version;
    }
}

// Get available migrations
$migrations = [];
$files = glob('migrations/*_version_*.php');
foreach ($files as $file) {
    if (preg_match('/(\d+)_version_(\d+)\.php$/', basename($file), $matches)) {
        $version = (int) $matches[1];
        $migrations[$version] = 'Version_' . $matches[1];
    }
}
ksort($migrations);

$pending_migrations = array_filter($migrations, function($version) use ($current_version) {
    return $version > $current_version;
}, ARRAY_FILTER_USE_KEY);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API Module Database Migrations</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2c3e50;
            border-bottom: 3px solid #3498db;
            padding-bottom: 10px;
        }
        .status {
            background: #ecf0f1;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .migration-list {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin: 15px 0;
        }
        .migration-item {
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        .migration-item:last-child {
            border-bottom: none;
        }
        .pending { color: #e74c3c; font-weight: bold; }
        .completed { color: #27ae60; }
        .form-group {
            margin: 15px 0;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        select, input[type="number"] {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        .btn {
            background: #3498db;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover { background: #2980b9; }
        .btn-danger { background: #e74c3c; }
        .btn-danger:hover { background: #c0392b; }
        .btn-success { background: #27ae60; }
        .btn-success:hover { background: #229954; }
        .message {
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
        }
        .output {
            background: #2c3e50;
            color: #ecf0f1;
            padding: 20px;
            border-radius: 5px;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            margin: 20px 0;
            max-height: 400px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 API Module Database Migrations</h1>

        <?php if ($message): ?>
            <div class="message"><?php echo $message; ?></div>
        <?php endif; ?>

        <div class="status">
            <h3>📊 Current Status</h3>
            <p><strong>Current Migration Version:</strong> <?php echo $current_version; ?></p>
            <p><strong>API Module Status:</strong> ✅ Active</p>
            <p><strong>Database Connection:</strong> ✅ Connected</p>
            <p><strong>Pending Migrations:</strong> <?php echo count($pending_migrations); ?></p>
        </div>

        <div class="migration-list">
            <h3>📋 Available Migrations</h3>
            <?php if (empty($migrations)): ?>
                <p>No migrations found.</p>
            <?php else: ?>
                <?php foreach ($migrations as $version => $name): ?>
                    <div class="migration-item <?php echo ($version <= $current_version) ? 'completed' : 'pending'; ?>">
                        Version <?php echo $version; ?>: <?php echo $name; ?>
                        <?php if ($version <= $current_version): ?>
                            <span style="float: right;">✅ Applied</span>
                        <?php else: ?>
                            <span style="float: right;">⏳ Pending</span>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <h3>🔧 Migration Actions</h3>

        <form method="post">
            <div class="form-group">
                <label for="target_version">Target Version (optional):</label>
                <input type="number" id="target_version" name="target_version"
                       placeholder="Leave empty for latest/all"
                       min="0" value="<?php echo $target_version ?? ''; ?>">
                <small>Specify a version number to migrate to that specific version</small>
            </div>

            <button type="submit" name="action" value="upgrade" class="btn btn-success">
                ⬆️ Run Upgrade
            </button>

            <button type="submit" name="action" value="rollback" class="btn btn-danger">
                ⬇️ Run Rollback
            </button>

            <button type="submit" name="action" value="check_status" class="btn">
                🔄 Refresh Status
            </button>
        </form>

        <?php if (isset($runner)): ?>
            <h3>📄 Migration Output</h3>
            <div class="output">
                <?php
                // Capture and display the runner output
                ob_start();
                $runner->run($target_version, ($action === 'rollback'));
                $output = ob_get_clean();
                echo htmlspecialchars($output);
                ?>
            </div>
        <?php endif; ?>

        <h3>📖 Instructions</h3>
        <ul>
            <li><strong>Upgrade:</strong> Runs all pending migrations to bring the database up to date</li>
            <li><strong>Rollback:</strong> Reverts migrations to a previous version (use with caution!)</li>
            <li><strong>Target Version:</strong> Specify a version number to migrate to that specific point</li>
            <li><strong>Backup First:</strong> Always backup your database before running migrations</li>
        </ul>

        <p><a href="../admin/modules">← Back to Modules</a></p>
    </div>
</body>
</html>