<?php

namespace App\Http\Controllers\API;

use App\Models\User;
use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class BettingController extends Controller
{
    public function history()
    {
        /** @var User $user */
        $user = auth()->user();
        $gameHistory = $user->bettings()->with(['details'])->latest('id')->get();
        //change 'details' to 'bettings'

        // Manipulate the data to change the key name from 'details' to 'bettings'
        $gameHistory->transform(function ($item) {
            $item->setAttribute('bettings', $item->getAttribute('details'));
            $item->unsetRelation('details');
            return $item;
        });

        return response()->success(
            'Successfully get game history.',
            compact('gameHistory')
        );
    }

    public function submit(Request $request)
    {

        // Log::info('Submit Game Request: ' . json_encode($request->all()));

        /** @var User $user */
        $user = auth()->user();
        if (!$user->isAgent()) {
            return response()->failed(
                'User is not agent.',
                'You are unauthorized to submit game.'
            );
        }

        $request->validate([
            'name' => 'required|string',
            'bettings' => 'required|array',
            'bettings.*.amount' => 'required|numeric',
            'bettings.*.number' => 'required|numeric|min:0|max:9'
        ]);

        $totalBettingAmount = collect($request->bettings)->sum('amount');

        if ($totalBettingAmount > $user->balance) {
            return response()->failed('Agent balance is insufficient for the total bettings.');
        }

        $currentRunningGame = Game::currentRunning()->first();

        if (blank($currentRunningGame)) {
            return response()->failed('No Game is currently running.');
        }

        $commissionSetting = Setting::where('key', 'commission')->first();
        if ($commissionSetting) {
            $commissionPercentage = $commissionSetting->value;
            $commissionAmount = ($totalBettingAmount / 100) * $commissionPercentage;
            $user->balance = $user->balance + $commissionAmount;
            $user->transactions()->create([
                'type' => 'deposit',
                'amount' => $commissionAmount,
                'purpose' => 'commission',
            ]);
        }

        $totalBettingAmount = array_sum(array_column($request->bettings, 'amount'));
        Log::info('Total Betting Amount: ' . $totalBettingAmount);
        $user->balance = $user->balance - $totalBettingAmount;
        $user->save();

        $betting = $user->bettings()->create([
            'name' => $request->name,
            'game_id' => $currentRunningGame->id,
        ]);

        foreach ($request->bettings as $bet) {
            $betting->details()->create([
                'amount' => $bet['amount'],
                'bet_number' => $bet['number'],
            ]);
        }

        $user->transactions()->create([
            'type' => 'withdraw',
            'amount' => $totalBettingAmount,
            'purpose' => 'game_betting',
        ]);
        $balance_left = $user->balance;
        // Log::info('Balance Left: ' . $balance_left);
        return response()->success('Successfully bet on game.', compact('balance_left'));
    }
}
