<?php

namespace App\Console\Commands;

use App\Models\Betting;
use App\Models\GameId;
use App\Models\GamePoints;
use App\Models\GameSettings;
use App\Models\NextGameId;
use App\Models\PaymentSettings;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class GameFiveMinute extends Command
{
    protected $signature = 'game:five';

    protected $description = 'Cron Job to update GameId';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $payment_settings = PaymentSettings::first();
        $previous_game = GameId::where(['status' => 0, 'type' => 'five_minute'])->with(['betting'])->latest()->first();

        $total_amount = rand(30000, 40000);
        if (isset($previous_game->betting) && count($previous_game->betting) > 0) {
            $all_bettings = $previous_game->betting;
            $five_minute_bets = $all_bettings->where('tab', '=', 'five_minute');
            $five_minute_bet_users = $all_bettings->where('tab', '=', 'five_minute')->groupBy('user_id');
            $five_minute_color_bettings = $all_bettings->where('type', '=', 'join')->where('tab', '=', 'five_minute')->count();
        } else {
            $all_bettings = [];
            $five_minute_bets = [];
            $five_minute_bet_users = [];
            $five_minute_color_bettings = 0;
        }



        if (count($five_minute_bet_users) == 1 || $five_minute_color_bettings == 0) {
            $five_minute_code = $this->calculateWinningCode($five_minute_bets);
        } elseif (count($five_minute_bet_users) == 2 && $five_minute_color_bettings > 0) {
            $five_minute_code = $this->calculateWinningCode($five_minute_bets);
        } elseif (count($five_minute_bet_users) > 2 && $five_minute_color_bettings > 0) {
            $five_minute_code = $this->calculateWinningCode($five_minute_bets);
        }


        $game_settings = GameSettings::first();
        if ($game_settings->five_minute_manual == 1 && $game_settings->five_minute_code !== null) {
            $five_minute_code = $game_settings->five_minute_code;
            // Log::info('CHECKING GAEM XX MANNUAL SET ' . $game_settings->five_minute_code);
        }

        if (env('NEXT_ENABLE') && $game_settings->five_minute_manual != 1) {
            $nextGameResult = NextGameId::where(['game_id' => $previous_game->game_id, 'type' => 'five_minute'])->first();
            if ($nextGameResult) {
                $five_minute_code = $nextGameResult->five_minute_code;
                $nextGameResult->status = 1;
                $nextGameResult->save();
            }
        }


        if (isset($previous_game)) {
            $previous_game->five_minute_code = $five_minute_code;
            $previous_game->Save();
        }

        foreach ($all_bettings as $bet) {
            if ($bet->type == 'individual' && $this->ifWon($bet->tab, $bet->code, $previous_game)) {
                if ($bet->code == 0 || $bet->code == 5) {
                    $winning_amount = $bet->amount * $payment_settings->number_two_color_multiple;
                } else {
                    $winning_amount = $bet->amount * $payment_settings->number_one_color_multiple;
                }

                $bet->update([
                    'result' => 1,
                    'status' => 1,
                    'winning_amount' => $winning_amount,
                    'total_amount' => $total_amount
                ]);

                User::where(['id' => $bet->user_id])->increment('amount', $winning_amount);
            } else {
                $code = explode(',', $bet->code);
                $found = false;
                foreach ($code as $value) {
                    if (!$found && $this->ifWon($bet->tab, $value, $previous_game)) {
                        if ($bet->color == 'big' || $bet->color == "small") {
                            $winning_amount = ($bet->amount * $payment_settings->big_small_multiple);
                        } else if ($value == 5 && $bet->color == 'green') {
                            $winning_amount = ($bet->amount * $payment_settings->red_green_with_0_5_multiple);
                        } else if ($value == 0 && $bet->color == 'red') {
                            $winning_amount = ($bet->amount * $payment_settings->red_green_with_0_5_multiple);
                        } else if (($value == 0 || $value == 5) && ($bet->color == 'violet')) {
                            $winning_amount = ($bet->amount * $payment_settings->violet_with_0_5_multiple);
                        } else {
                            $winning_amount = ($bet->amount * $payment_settings->color_multiple);
                        }
                        // $winning_amount = $bet->amount * $payment_settings->color_multiple;
                        $bet->update([
                            'result' => 1,
                            'status' => 1,
                            'winning_amount' => $winning_amount,
                            'total_amount' => $total_amount
                        ]);
                        User::where(['id' => $bet->user_id])->increment('amount', $winning_amount);
                        $found = true;
                    }
                }
            }
        }

        Betting::where(['status' => 0, 'tab' => 'five_minute'])->update(['status' => 1, 'total_amount' => $total_amount]);
        GameId::where(['status' => 0, 'type' => 'five_minute'])->update(['status' => 1]);



        $pid_now = generateGameId(5, $previous_game);

        $gameId = new GameId();
        $gameId->game_id = $pid_now;
        $gameId->type = "five_minute";
        $gameId->open_price = rand(30000, 40000);
        $gameId->save();

        GameSettings::first()->update([
            'five_minute_manual' => 0,
            'five_minute_code' => null,
        ]);
    }

    public function ifWon($bet_tab, $bet_code, $game_codes)
    {
        if ($bet_tab == 'five_minute' && $bet_code == $game_codes->five_minute_code) {
            return true;
        } else {
            return false;
        }
    }

    public function calculateWinningCode($five_minute_bets)
    {
        // $gameIdLastToday = GameId::orderBy('id', 'desc')
        //     ->where('type', 'five_minute')
        //     ->first();

        // if (substr($gameIdLastToday->game_id, -3) === '000') {
        //     $latestGame  = GameId::whereDate('created_at', Carbon::yesterday())
        //         ->orderBy('id', 'desc')
        //         ->where('type', 'five_minute')
        //         ->first();
        //     $five_minute_code = $latestGame->five_minute_code;
        //     return $five_minute_code;
        // }


        $payment_settings = PaymentSettings::first();
        $value_against_point = [];
        $game_points = GamePoints::all();

        foreach ($game_points as $point) {
            $total_amount = 0;
            if (count($five_minute_bets) > 0) {
                foreach ($five_minute_bets as $betting) {
                    if ($betting->type == "individual" && $betting->code == $point->game_code) {
                        if ($betting->code == 0 || $betting->code == 5) {
                            $total_amount += ($betting->amount * $payment_settings->number_two_color_multiple);
                        } else {
                            $total_amount += ($betting->amount * $payment_settings->number_one_color_multiple);
                        }
                    } elseif ($betting->type == "join") {
                        $betting_codes = explode(',', $betting->code);
                        if (in_array($point->game_code, $betting_codes)) {
                            if ($point->game_code == 5 && $betting->color == 'green') {
                                $total_amount += ($betting->amount * $payment_settings->red_green_with_0_5_multiple);
                            } elseif ($point->game_code == 0 && $betting->color == 'red') {
                                $total_amount += ($betting->amount * $payment_settings->red_green_with_0_5_multiple);
                            } elseif (($point->game_code == 0 || $point->game_code == 5) && ($betting->color == 'violet')) {
                                $total_amount += ($betting->amount * $payment_settings->violet_with_0_5_multiple);
                            } else {
                                $total_amount += ($betting->amount * $payment_settings->color_multiple);
                            }
                        }
                    }
                }
            }
            array_push($value_against_point, $total_amount);
        }
        $indexes = array_keys($value_against_point, min($value_against_point));
        $random_keys = array_rand($indexes);
        return $indexes[$random_keys];
    }

    public function calculateLowestWinningCode($parity_bets)
    {
        $payment_settings = PaymentSettings::first();

        $value_against_point = [];
        $game_points = GamePoints::all();

        foreach ($game_points as $point) {
            $total_amount = 0;
            if (count($parity_bets) > 0) {
                foreach ($parity_bets as $betting) {
                    if ($betting->type == "individual" && $betting->code == $point->game_code) {
                        if ($betting->code == 0 || $betting->code == 5) {
                            $total_amount += ($betting->amount * $payment_settings->number_two_color_multiple);
                        } else {
                            $total_amount += ($betting->amount * $payment_settings->number_one_color_multiple);
                        }
                    } elseif ($betting->type == "join") {
                        $betting_codes = explode(',', $betting->code);
                        if (in_array($point->game_code, $betting_codes)) {
                            if ($point->game_code == 5 && $betting->color == 'green') {
                                $total_amount += ($betting->amount * $payment_settings->red_green_with_0_5_multiple);
                            } elseif ($point->game_code == 0 && $betting->color == 'red') {
                                $total_amount += ($betting->amount * $payment_settings->red_green_with_0_5_multiple);
                            } elseif (($point->game_code == 0 || $point->game_code == 5) && ($betting->color == 'violet')) {
                                $total_amount += ($betting->amount * $payment_settings->violet_with_0_5_multiple);
                            } else {
                                $total_amount += ($betting->amount * $payment_settings->color_multiple);
                            }
                        }
                    }
                }
            }
            array_push($value_against_point, $total_amount);
        }

        // prx($value_against_point);

        $new_array = array_filter($value_against_point, function ($value) {
            if ($value != 0) {
                return true;
            } else {
                return false;
            }
        });

        $indexes = array_keys($new_array, min($new_array));
        $random_keys = array_rand($indexes);
        return $indexes[$random_keys];
    }

    public function calculateSecondLowestWinningCode($parity_bets)
    {
        $payment_settings = PaymentSettings::first();

        $value_against_point = [];
        $game_points = GamePoints::all();

        foreach ($game_points as $point) {
            $total_amount = 0;
            if (count($parity_bets) > 0) {
                foreach ($parity_bets as $betting) {
                    if ($betting->type == "individual" && $betting->code == $point->game_code) {
                        if ($betting->code == 0 || $betting->code == 5) {
                            $total_amount += ($betting->amount * $payment_settings->number_two_color_multiple);
                        } else {
                            $total_amount += ($betting->amount * $payment_settings->number_one_color_multiple);
                        }
                    } elseif ($betting->type == "join") {
                        $betting_codes = explode(',', $betting->code);
                        if (in_array($point->game_code, $betting_codes)) {
                            if ($point->game_code == 5 && $betting->color == 'green') {
                                $total_amount += ($betting->amount * $payment_settings->red_green_with_0_5_multiple);
                            } elseif ($point->game_code == 0 && $betting->color == 'red') {
                                $total_amount += ($betting->amount * $payment_settings->red_green_with_0_5_multiple);
                            } elseif (($point->game_code == 0 || $point->game_code == 5) && ($betting->color == 'violet')) {
                                $total_amount += ($betting->amount * $payment_settings->violet_with_0_5_multiple);
                            } else {
                                $total_amount += ($betting->amount * $payment_settings->color_multiple);
                            }
                        }
                    }
                }
            }
            array_push($value_against_point, $total_amount);
        }

        $new_array = array_filter($value_against_point, function ($value) {
            if ($value != 0) {
                return true;
            } else {
                return false;
            }
        });

        asort($new_array);
        $indexes = array_keys($new_array);
        if (count($indexes) > 1) {
            return $indexes[1];
        } else {
            return $indexes[0];
        }
    }
}
