<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class MigrationController extends Controller
{
    /**
     * Show the premium installer UI.
     */
    public function index(Request $request)
    {
        return view('installer');
    }

    /**
     * Execute a specific installation/maintenance step via AJAX.
     */
    public function executeStep(Request $request)
    {

        $step = $request->input('step');
        $output = '';

        try {
            switch ($step) {
                case 'migrate':
                    Artisan::call('migrate --force');
                    $output = Artisan::output();
                    break;
                case 'seed':
                    Artisan::call('db:seed --force');
                    $output = Artisan::output();
                    break;
                case 'link':
                    Artisan::call('storage:link');
                    $output = Artisan::output();
                    break;
                case 'clear':
                    Artisan::call('config:clear');
                    $output .= Artisan::output()."\n";
                    Artisan::call('route:clear');
                    $output .= Artisan::output()."\n";
                    Artisan::call('view:clear');
                    $output .= Artisan::output()."\n";
                    Artisan::call('cache:clear');
                    $output .= Artisan::output();
                    break;
                default:
                    return response()->json(['status' => 'error', 'message' => 'Invalid step'], 400);
            }

            return response()->json([
                'status' => 'success',
                'output' => $output ?: 'Success (No output)',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
                'output' => $e->getMessage(),
            ], 500);
        }
    }
}
