<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\User;

class AviatorController extends Controller
{

    public function fetchUsersBalance(Request $request)
    {
        $secretTokenFromAgent = $request->header('secretTokenFromAgent');

        // Check if the secret token matches the one in the .env file
        if ($secretTokenFromAgent !== env('AVIATOR_SECRET_TOKEN_FROM_AGENT')) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 200);
        }

        // Retrieve the playerBalances array from the request
        $userList = $request->input('userList', []);

        $response = [];

        foreach ($userList as $userId) {
            $user = User::where('id', $userId)
                ->first();

            if ($user) {
                $response[] = [
                    'userId' => $userId,
                    'balance' => $user->amount,
                ];
            } else {
                // Return balance as 0 if the user does not exist
                $response[] = [
                    'userId' => $userId,
                    'balance' => 0,
                ];
            }
        }

        return response()->json(['success' => true, 'balances' => $response]);
    }



    public function updateGamePlay(Request $request)
    {
        Log::info('Aviator updateGamePlay');
        Log::info($request->all());
        $secretTokenFromAgent = $request->header('secretTokenFromAgent');

        // Check if the secret token matches the one in the .env file
        if ($secretTokenFromAgent !== env('AVIATOR_SECRET_TOKEN_FROM_AGENT')) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 200);
        }

        // Retrieve the results array from the request
        $playList = $request->input('playList', []);
        $updatedUsers = []; // Initialize array to store updated users

        foreach ($playList as $play) {
            $user = User::where('id', $play['userId'])
                ->first();

            if ($user) {
                $existingUserKey = array_search($play['userId'], array_column($updatedUsers, 'userId'));

                if ($existingUserKey !== false) {
                    if ($play['gameStatus'] === 'win') {
                        $updatedUsers[$existingUserKey]['updatedBalance'] += $play['winAmount'];
                        $user->amount += $play['winAmount'];
                    } elseif ($play['gameStatus'] === 'pending') {
                        $updatedUsers[$existingUserKey]['updatedBalance'] -= $play['playAmount'];
                        $user->amount -= $play['playAmount'];
                    }
                } else {
                    if ($play['gameStatus'] === 'win') {
                        $user->amount += $play['winAmount'];
                    } elseif ($play['gameStatus'] === 'pending') {
                        $user->amount -= $play['playAmount'];
                    }
                    // Add the updated user data to the response array
                    $updatedUsers[] = [
                        'userId' => $play['userId'],
                        'updatedBalance' => $user->amount
                    ];
                }

                $user->save();
                $user->refresh();
            }
        }


        return response()->json(['success' => true, 'message' => 'Balances updated successfully', 'updatedUsers' => $updatedUsers]);
    }


    public function getGameToken()
    {
        try {
            Log::info('Aviator getGameToken');
            $user = Auth::user();
            $payLoad = [
                'userId' => $user->id,
                'userName' => $user->name ?? 'User',
                'userEmail' => $user->mobile . "@gmail.com",
                'gameType' => 'aviator',
            ];
            $response = Http::withHeaders([
                'secretTokenFromAdmin' => env('AVIATOR_SECRET_TOKEN_FROM_ADMIN'),
                //accept application/json
                'Accept' => 'application/json',
            ])->post(env('AVIATOR_BACKEND_URL') . '/api/user/generateToken', $payLoad);

            Log::info('Aviator getGameToken request', ['request' => $payLoad]);

            if ($response->successful()) {
                // Ensure response is decoded as an associative array
                $response_Json = json_decode($response->body(), true);

                Log::info('Aviator getGameToken response', ['response' => $response_Json]);

                // Check if 'response' key exists and access the 'status'
                if ($response_Json['status']) {
                    $aviatorGameToken = $response_Json['token'];
                    $gameUrl = env('AVIATOR_FRONTEND_URL') . '&token=' . $aviatorGameToken . "&user=" . $user->id;

                    $user->aviator_game_url = $gameUrl;
                    $user->save();

                    Log::info($gameUrl);
                    return response()->json(['success' => true, 'gameUrl' => $gameUrl]);
                } else {
                    Log::info('status 2');
                    $message = $response_Json['message'] ?? 'Error generating token.';
                    return response()->json(['success' => false, 'message' => $message], 200);
                }
            } else {
                Log::info('status 3');
                return response()->json(['success' => false, 'message' => 'Request failed'], 200);
            }
        } catch (\Exception $e) {
            Log::error('Error calling API');
            Log::error($e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 200);
        }
    }
}
