<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Services\MinecraftService;
use App\ServerSettings;
use Auth;

class ServerConsoleController extends AdminController
{
    
    public function index()
    {
        return view('manage.admin.serverconsole', [
            'settings' => $this->getSettings(),
        ]);
    }


    public function store(Request $request)
    {
        $request->validate([
            'command' => 'required|string'
        ]);

    
        $username = Auth::user()->username ?? Auth::user()->name;
        $commandRaw = str_replace('%player', $username, $request->command);

      
        $commands = array_filter(array_map('trim', explode(';', $commandRaw)));

      
        $server = ServerSettings::whereNotNull('websender_port')->first();

        if (!$server) {
            return back()->with('command_error', 'No WebSender server configured.');
        }

        try {
            $mc = new MinecraftService($server->server_id);

            $output = "";

            foreach ($commands as $cmd) {
                $mc->run($cmd);
                $output .= "✔ Executed: {$cmd}\n";
            }

            return back()->with('command_result', $output);

        } catch (\Exception $e) {
            return back()->with('command_error', $e->getMessage());
        }
    }
}
