<?php

namespace App\Http\Controllers\Admin\Settings;

use Illuminate\Http\Request;
use Inertia\Inertia;

class GameVersionSettingsController extends BaseSettingsController
{
    public function index()
    {
        return Inertia::render('admin/settings/game-version/index', [
            'gameVersion' => $this->getGameVersion(),
        ]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'game_version' => 'required|string|in:07,63,69,70,80,85,88,101,145,156,172',
        ]);

        $apiPath = app_path('Services/API.php');
        if (file_exists($apiPath)) {
            $content = file_get_contents($apiPath);
            $content = preg_replace(
                "/'game_version'\s*=>\s*'[^']*'/",
                "'game_version' => '".$request->game_version."'",
                $content
            );
            file_put_contents($apiPath, $content);
        }

        return back()->with('success', 'Game version updated successfully.');
    }

    private function getGameVersion(): string
    {
        $apiPath = app_path('Services/API.php');
        if (file_exists($apiPath)) {
            $content = file_get_contents($apiPath);
            if (preg_match("/'game_version'\s*=>\s*'([^']*)'/", $content, $matches)) {
                return $matches[1];
            }
        }

        return '156';
    }
}
