<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use App\Models\Api;

class GameApiController extends Controller
{
    /**
     * Ambil data agent dari database
     */
    private function getAgent()
    {
        $api = Api::where('nx_status', 1)->first(); 
        // ⬆️ ganti nx_ → ng_ / sg_ / wsg_ sesuai provider

        if (!$api) {
            abort(500, 'API game belum dikonfigurasi');
        }

        return [
            'agentcode' => $api->nx_agent_code,
            'signature' => $api->nx_token,
            'baseapi'   => rtrim($api->nx_endpoint, '/')
        ];
    }

    /**
     * Launch Game
     */
    public function subGameLaunch(Request $request)
    {
        $request->validate([
            'gameid' => 'required|string'
        ]);

        $user = Auth::user();

        if (empty($user->extplayer)) {
            return response()->json([
                'status' => false,
                'message' => 'User belum memiliki extplayer'
            ], 400);
        }

        $agent = $this->getAgent();

        $endpoint = $agent['baseapi'] . '?' . http_build_query([
            'cmd'        => 'launch',
            'agent_code' => $agent['agentcode'],
            'username'   => $user->extplayer,
            'gameid'     => $request->gameid,
            'signature'  => $agent['signature'],
        ]);

        $response = Http::timeout(15)->get($endpoint);

        if (!$response->ok()) {
            return response()->json([
                'status' => false,
                'message' => 'Gagal launch game'
            ], 500);
        }

        return $response->json();
    }
}
