<?php

namespace App\Http\Controllers\API\Roullete;

use App\Models\Rate;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Period;
use App\Models\Game;
use App\Models\CustomResult;
use App\Models\NumberResult;
use App\Models\WalletHistory;
use App\Models\ColourMatakaBetting;
use App\Models\ColourMatakaResult;
use App\Models\ColourMatakaWinner;
use App\Models\NumberBetting;
use App\Models\ResultCondition;
use App\Models\AdminPercentage;

#Other Class
use OTP;
use Mail;
use Session;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Traits\MasterTraits;
use App\Traits\FirebaseTraits;
use App\Traits\ChakriTrait;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\AppDetail;
use App\Models\RouletteBettingOptions;
use App\Models\RouletteBettings;
use App\Models\JackpotBetting;
use App\Models\JackpotResult;
use App\Models\RouletteSetUp;
use App\Models\RoulleteGame;
use App\Models\RoulletResult;
use App\Models\RoulletResultCondition;
use App\Models\Users;
use Illuminate\Support\Facades\DB;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ResultController extends BaseController
{
    use FirebaseTraits;

    use MasterTraits;

    use ChakriTrait;

    #Bind Wallet model
    protected $wallet;

    #Bind Period model
    protected $period;

    #Bind RoulleteGame model
    protected $games;

    #Bind Rate model
    protected $rate;

    #Bind CustomResult model
    protected $customResult;

    #Bind NumberResult model
    protected $numberResult;

    #Bind NumberBetting model
    protected $numberBetting;

    #Bind ResultCondition model
    protected $resultCondition;

    #Bind RouletteBettings model
    protected $rouletteBettings;

    #Bind RoulletResult model
    protected $roulletResult;

    #Bind RoulletResultCondition model
    protected $roulletResultCondition;

    #Bind RouletteSetUp model
    protected $rouletteSetUp;

    #Bind JackpotBetting model
    protected $jackpotBetting;

    #Bind ColourMatakaBetting model
    protected $colourMatakaBetting;

    #Bind ColourMatakaResult model
    protected $colourMatakaResult;

    #Bind ColourMatakaWinner model
    protected $colourMatakaWinner;

    #Bind JackpotResult model
    protected $jackpotResult;

    #Bind RoulletBettingoptions model
    protected $roulletBettingoptions;

    #Bind AppDetails model
    protected $appDetails;

    public function __construct(
        Rate                                  $rate,
        RoulleteGame                          $games,
        Period                                $period,
        NumberResult                          $numberResult,
        NumberBetting                         $numberBetting,
        CustomResult                          $customResult,
        ResultCondition                       $resultCondition,
        RouletteBettings                      $rouletteBettings,
        RoulletResult                         $roulletResult,
        RoulletResultCondition                $roulletResultCondition,
        RouletteSetUp                         $rouletteSetUp,
        JackpotBetting                        $jackpotBetting,
        JackpotResult                         $jackpotResult,
        ColourMatakaBetting                   $colourMatakaBetting,
        ColourMatakaResult                    $colourMatakaResult,
        ColourMatakaWinner                    $colourMatakaWinner,
        RouletteBettingOptions                $roulletBettingoptions,
        AppDetail                             $appDetails
    ) {
        $this->rate                           = $rate;
        $this->games                          = $games;
        $this->period                         = $period;
        $this->customResult                   = $customResult;
        $this->numberResult                   = $numberResult;
        $this->numberBetting                  = $numberBetting;
        $this->resultCondition                = $resultCondition;
        $this->rouletteBettings               = $rouletteBettings;
        $this->roulletResult                  = $roulletResult;
        $this->roulletResultCondition         = $roulletResultCondition;
        $this->rouletteSetUp                  = $rouletteSetUp;
        $this->jackpotBetting                 = $jackpotBetting;
        $this->jackpotResult                  = $jackpotResult;
        $this->colourMatakaBetting            = $colourMatakaBetting;
        $this->colourMatakaResult             = $colourMatakaResult;
        $this->colourMatakaWinner             = $colourMatakaWinner;
        $this->roulletBettingoptions          = $roulletBettingoptions;
        $this->appDetails                     = $appDetails;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
     
     
     public function roulletRates(){
        $rates = $this->rouletteSetUp->first();

        $success = [];
        
        $success['rates'] = [
            [
                'name' => 'Single Rate',
                'amount' => 10,
                'rate' => 10 * $rates->single_rate,
            ],
            [
                'name' => 'Even/Odd Rate',
                'amount' => 10,
                'rate' => 10 * $rates->even_odd_rate,
            ],
            [
                'name' => 'Color Rate',
                'amount' => 10,
                'rate' => 10 * $rates->color_rate,
            ],
            [
                'name' => 'Big Small Rate',
                'amount' => 10,
                'rate' => 10 * $rates->big_small_rate,
            ],
        ];

             
             return $this->sendResponse($success, 'Rate Fetch successfully.');
         
     }
     
       public function predictionRates(){
        $rates = $this->rate->get();

        $success = [];
        $number = false;
       foreach($rates as $key => $value){
           if($value->type == 'number' && $number == false){
               $success['rates'][] = [
                'name' => 'Digit',
                'amount' => 10,
                'rate' => 10 * $value->rate,
                ];
                $number = true;
           }
           
           if($value->type != 'number'){
               $success['rates'][] = [
                'name' => $value->betting_options,
                'amount' => 10,
                'rate' => 10 * $value->rate,
                ];
           }
           
       }
             
             return $this->sendResponse($success, 'Rate Fetch successfully.');
         
     }
     
    public function index(Request $request)
    {
        // try {
        DB::beginTransaction();
        $validator = Validator::make($request->all(), [
            'game_id'                   => 'required',
            'play_time_id'              => 'required',
        ]);

        if ($validator->fails()) {
            return $this->sendError('Validation Error.', $validator->messages());
        }

        $periods = $this->period->where('game_id', $request->game_id)->where('play_time_id', $request->play_time_id)->latest()->first();
        $checknumberResult = $this->numberResult->where('period_id', $periods->id)->first();
        $success['new_period'] = $this->periodcreate($request->game_id, $request->play_time_id);
        $success['old_period'] = $periods;
        if (isset($periods) && !isset($checknumberResult)) {
            $numberBettings = $this->numberBetting->with('rates')->where('period_id', $periods->id)->get();
            $conditions = $this->resultCondition->get();
            $checkcustomResult = $this->customResult->where('game_id', 1)->where('play_time_id', $request->play_time_id)->where('period', $periods->period)->first();
            if (!$checkcustomResult) {
                if (count($numberBettings) > 0) {
                    $totalBettingAmount = $numberBettings->sum('amount');
                    $adminPercentage = $this->appDetails->first();
                    $percentageCal = round($totalBettingAmount * ($adminPercentage->admin_Roullete_percent / 100));
                    $adminAmount = $percentageCal;
                    $distribute_amount_in_user = $totalBettingAmount - $percentageCal;
                    $tolerance = 0.10; // Define the tolerance range (adjust as needed)
                    $combinationAmountArray = [];
                    foreach ($conditions as $key => $value) {
                        // Separate colors
                        $separatedValues = explode(',', $value->color);
                        $color1 = $separatedValues[0] ?? null;
                        $color2 = $separatedValues[1] ?? null;

                        // Query for numberBettings and join with rates
                        $check = $this->numberBetting
                            ->where('period_id', $periods->id)
                            ->where(function ($query) use ($value, $color1, $color2) {
                                $query->where('number', $value->number)
                                    ->orWhere('color', $color1)
                                    ->orWhere('color', $color2)
                                    ->orWhere('size', $value->size);
                            })
                            ->join('rates', 'number_bettings.betting_option_id', '=', 'rates.id')
                            ->select('number_bettings.*', 'rates.rate', DB::raw('number_bettings.amount * rates.rate as total_amount'))
                            ->get();
                        // Calculate the sum of the total_amount for this combination
                        $combinationAmount = $check->sum('total_amount');
                        $combinationAmountArray[$value->id] = $combinationAmount;
                    }

                    // Find the nearest value to distribute_amount_in_user in combinationAmountArray
                    $nearestAmount = null;
                    $nearestCombination = null;
                    $smallestDifference = PHP_INT_MAX; // Initialize with a very large number

                    foreach ($combinationAmountArray as $key => $amount) {
                        $difference = abs($distribute_amount_in_user - $amount); // Calculate the absolute difference

                        if ($difference < $smallestDifference) {
                            $smallestDifference = $difference;
                            $nearestAmount = $amount; // Set the nearest amount
                            $nearestCombination = $key; // Set the nearest amount
                        }
                    }
                    $adminAmount = $totalBettingAmount - $nearestAmount;
                    $checkAdmin = Users::where('type', 'admin')->first();
                    // $comment = 'Admin Percentage Form Color Prediction Game And Amount Is' . $adminAmount;
                    // $check = $this->walletss(
                    //     $checkAdmin->id,            // User ID
                    //     $adminAmount,               // Amount
                    //     'Deposit',                  // Transaction Type
                    //     'Game',                     // Payment Method
                    //     null,                       // Transaction Number
                    //     'Complete',                 // Status
                    //     'Deposit',                  // Description or another identifier
                    //     null,                       // Channel ID
                    //     null,
                    //     $comment
                    // );
                } else {
                    $getconditions = $conditions->random();
                    $nearestCombination = $getconditions->id;
                }
            } else {
                $nearestCombination = $checkcustomResult->color_result_condition_id;
            }
            $resultCombination = $this->resultCondition->whereId($nearestCombination)->first();
            $separatedValue = explode(',', $resultCombination->color);
            $colorOne = $separatedValue[0] ?? null;
            $colorTwo = $separatedValue[1] ?? null;
            $numberResultData = [
                'period_id' => $periods->id,
                'number'    => $resultCombination->number,
                'size'      => $resultCombination->size,
                'color'     => isset($colorTwo) ? $colorOne . ',' . $colorTwo : $colorOne,
            ];
            $result = $this->numberResult->create($numberResultData);

            $success['result'] = $result;
            // $this->resultcreate($numberResultData, $request->game_id,$request->play_time_id);
            
            
            
            foreach ($numberBettings as $key => $value) {
                
                
                $winAmount = $value->balance * $value->rates->rate;
                $lossAmount = $value->balance;
                if ($value->color == $colorOne || $value->color == $colorTwo || $value->number == $resultCombination->number || $value->size == $resultCombination->size) {
                    $comment = 'Win Color Prediction Game And Amount Is' . $winAmount;
                    
                     $this->Payment($value->user_id,$winAmount);
                    
                    $remark =  'Win Color Prediction Game And Amount Is' . $winAmount;
                    PaymentRemark($value->user_id, $remark, $winAmount);
                    
                    $value->profit = $winAmount;
                    $value->balance = 0;
                    $value->result = 'win';
                    $value->save();
                } else {
                    $comment = "";
                    
                    $value->loss = $lossAmount;
                    $value->balance = 0;
                    $value->result = 'loss';
                    $value->save();
                }
            }
            $success['user_result'] = $this->numberBetting->where('user_id', Auth::id())->where('period_id', $periods->id)->get();
            DB::commit();
            return $this->sendResponse($success, 'Result Fetch successfully.');
        } else {
            return $this->sendError('Validation Error.', 'Period Not Found Or This Period Result is already decleared');
        }
        DB::commit();
        return $this->sendResponse($success, 'Result Fetch successfully.');
        // } catch (\Exception $ex) {
        DB::rollback();
        //     return $this->sendError('Validation Error.', $ex->getMessage());
        // }
    }

    public function  resultHistory(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'game_id'                   => 'required',
                'play_time_id'              => $request->game_id == 1 ? 'required' : 'nullable',
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->messages());
            }

            if ($request->game_id == 1) {
                # code...
                $periodId = $this->period->where('play_time_id', $request->play_time_id)->pluck('id')->toArray();
                $success = $this->numberResult->with('period')->whereIn('period_id', $periodId)->orderBy('id', 'DESC')->paginate(50);
            } elseif ($request->game_id == 3) {
                $periodId = $this->period->where('game_id', $request->game_id)->pluck('id')->toArray();
                $relation = ['period'];
                $query = $this->jackpotResult
                    ->with($relation)
                    ->whereIn('period_id', $periodId);
                if ($request->has('date')) {
                    $date = $request->date;
                    $query->whereDate('created_at', $date);
                }
                $success = $query->orderBy('id', 'DESC')->paginate(10);
            } else {
                $periodId = $this->period->where('game_id', $request->game_id)->pluck('id')->toArray();
                $relation = ['period.roulletBetting.user'];
                $query = $this->roulletResult->with($relation)->whereIn('period_id', $periodId);
                if ($request->has('date')) {

                    $date = $request->date;
                    $query->whereDate('created_at', $date);
                }
                $success = $query->orderBy('id', 'DESC')->paginate(10);
            }

            return $this->sendResponse($success, 'Bet Result History Successfully.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }

    public function  myresultHistory(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'game_id'                   => 'required',
                'play_time_id'              => $request->game_id == 1 ? 'required' : 'nullable',

            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->messages());
            }

            if ($request->game_id == 1) {
                $periodId = $this->period->where('play_time_id', $request->play_time_id)->pluck('id')->toArray();
                $relation = ['period.numberResult'];
                $success = $this->numberBetting->with($relation)->whereIn('period_id', $periodId)->where('user_id', Auth::id())->orderBy('id', 'DESC')->paginate(50);
            } elseif ($request->game_id == 3) {
                $periodId = $this->period->where('game_id', $request->game_id)->pluck('id')->toArray();
                $relation = ['period.jackPotResult'];

                $query = $this->jackpotBetting
                    ->with($relation)
                    ->whereIn('period_id', $periodId)
                    ->where('user_id', Auth::id());

                if ($request->has('date')) {
                    $date = $request->date;
                    $query->whereDate('created_at', $date);
                }

                $success = $query->orderBy('id', 'DESC')->paginate(10);

                // attach winnumber to each betting row
                foreach ($success as $bet) {
                    $resultNumber = optional($bet->period->jackPotResult)->number;
                    $betNumber    = $bet->number;
                    $bet->winnumber = null;

                    if ($resultNumber && $betNumber) {
                        $resultDigits = str_split((string) $resultNumber);
                        $betDigits    = str_split((string) $betNumber);

                        $mask = array_fill(0, count($resultDigits), '*'); // start with *****

                        for ($i = count($resultDigits) - 1; $i >= 0; $i--) {
                            if ($resultDigits[$i] == $betDigits[$i]) {
                                $mask[$i] = $resultDigits[$i]; // replace * with digit
                            } else {
                                break; // stop at first mismatch
                            }
                        }

                        $bet->winnumber = implode('', $mask);
                    }
                }
            } elseif ($request->game_id == 4) {
                $periodId = $this->period
                    ->where('game_id', $request->game_id)
                    ->pluck('id')
                    ->toArray();

                $query = $this->colourMatakaBetting
                    ->with([
                        'period.colorMatkaResult.winner' => function ($query) {
                            $query->where('user_id', Auth::id());
                        }
                    ])
                    ->whereIn('period_id', $periodId)
                    ->where('user_id', Auth::id());

                if ($request->has('date')) {
                    $date = $request->date;
                    $query->whereDate('created_at', $date);
                }

                $success = $query->orderBy('id', 'DESC')->paginate(10);
            } else {
                $periodId = $this->period->where('game_id', $request->game_id)->pluck('id')->toArray();
                $relation = ['period.roulletResult','roulette_betting_option'];
                $query = $this->rouletteBettings->with($relation)->whereIn('period_id', $periodId)->where('user_id', Auth::id());
                if ($request->has('date')) {

                    $date = $request->date;
                    $query->whereDate('created_at', $date);
                }
                $success = $query->orderBy('id', 'DESC')->paginate(10);
            }

            return $this->sendResponse($success, 'Bet Result History Successfully.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }

    public function gteResult(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'period_id'                   => 'required',
                'game_id'                   => 'required',
                // 'play_time_id'              => $request->game_id == 1 ? 'required' : 'nullable',
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->messages());
            }

            $periodId = $this->period->where('id', $request->period_id)->first();

            if ($request->game_id == 1) {
                # code...
                $success['result'] = $this->numberResult->with('period')->where('period_id', $request->period_id)->first();
                $results = $this->numberBetting
                    ->where('user_id', Auth::id())
                    ->where('period_id', $request->period_id)
                    ->get();
                
                if ($results->contains('result', 'win')) {
                    // If any win exists, assign only wins
                    $success['user_result'] = $results->where('result', 'win')->values();
                } else {
                    // Otherwise assign all (all losses)
                    $success['user_result'] = $results;
                }

            } elseif ($request->game_id == 3) {
                $success['result'] = $this->jackpotResult
                    ->with('period')
                    ->where('period_id', $request->period_id)
                    ->first();

                $success['user_result'] = $this->jackpotBetting
                    ->where('user_id', Auth::id())
                    ->where('period_id', $request->period_id)
                    ->get();

                if ($success['result']) {
                    $resultNumber = str_split((string) $success['result']->number);
                    foreach ($success['user_result'] as $bet) {
                        $betDigits = str_split((string) $bet->number);

                        $matched = '';
                        // compare from rightmost (index 4 to 0 for 5 digits)
                        for ($i = count($resultNumber) - 1; $i >= 0; $i--) {
                            if ($resultNumber[$i] == $betDigits[$i]) {
                                // prepend digit since we are going right → left
                                $matched = $resultNumber[$i] . $matched;
                            } else {
                                break; // stop at first mismatch
                            }
                        }

                        // attach winnumber to each bet
                        $bet->winnumber = $matched ?: null;
                    }
                }
            } else {
                $success['result'] = $this->roulletResult->with('period')->where('period_id', $request->period_id)->first();
                $success['user_result'] = $this->rouletteBettings->where('user_id', Auth::id())->where('period_id', $request->period_id)->get();

                $win = 0;
                $loss = 0;

                foreach ($success['user_result'] as $bet) {
                    if ($bet->result  == 'win') {
                        $win += $bet->profit;
                    } else {
                        $loss += $bet->loss;
                    }
                }
                $success['win_amount'] = $win;
                $success['loss_amount'] = $loss;
            }
            return $this->sendResponse($success, 'Bet Placed successfully.');
        } catch (\Exception $ex) {
            return $this->sendError('Validation Error.', $ex->getMessage());
        }
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function RoulletResult(Request $request)
    {
        // try {
        DB::beginTransaction();

        $periods = $this->period->where('game_id', 2)->latest()->first();
        $success['old_period'] = $periods;

        $checknumberResult = $this->roulletResult->where('period_id', $periods->id)->first();

        if (isset($periods) && !isset($checknumberResult)) {
            $numberBettings = $this->rouletteBettings->with('roulette_betting_option', 'roulette_types')->where('period_id', $periods->id)->get();
            $conditions = $this->roulletResultCondition->get();
            $checkcustomResult = $this->customResult->where('game_id', 2)->where('play_time_id', $request->play_time_id)->where('period', $periods->period)->first();
            if (!$checkcustomResult) {
                if (count($numberBettings) > 0) {
                    $totalBettingAmount = $numberBettings->sum('amount');
                    $adminPercentage = $this->appDetails->first();
                    $percentageCal = round($totalBettingAmount * ($adminPercentage->admin_Roullete_percent / 100));
                    $adminAmount = $percentageCal;
                    $distribute_amount_in_user = $totalBettingAmount - $percentageCal;
                    $Bettingoptions = $this->roulletBettingoptions->all();
                    $rates = $this->rouletteSetUp->first();
                    $BettingoptionsAmountArray = [];
                    foreach ($Bettingoptions as $key => $value) {
                        $check = $this->rouletteBettings
                            ->where(
                                'period_id',
                                $periods->id
                            )->where(
                                'betting_option_id',
                                $value->id
                            )->get();

                        switch ($value->id) {
                            case $value->id > 1 && $value->id <= 13:
                                # code...
                                $combinationAmount = $check->sum('amount');
                                // $BettingoptionsAmountArray[$value->id] = $combinationAmount;
                                $total = $combinationAmount * $rates->single_rate;
                                $BettingoptionsAmountArray[$value->betting_options] = $total;
                                break;
                            case $value->id == 14 || $value->id == 15:
                                # code...
                                $combinationAmount = $check->sum('amount');
                                // $BettingoptionsAmountArray[$value->id] = $combinationAmount;
                                $total = $combinationAmount * $rates->even_odd_rate;
                                $BettingoptionsAmountArray[$value->betting_options] = $total;
                                break;
                            case $value->id == 16 || $value->id == 17:
                                # code...
                                $combinationAmount = $check->sum('amount');
                                // $BettingoptionsAmountArray[$value->id] = $combinationAmount;
                                $total = $combinationAmount * $rates->big_small_rate;
                                $BettingoptionsAmountArray[$value->betting_options] = $total;
                                break;
                            case $value->id == 18 || $value->id == 19:
                                # code...
                                $combinationAmount = $check->sum('amount');
                                // $BettingoptionsAmountArray[$value->id] = $combinationAmount;
                                $total = $combinationAmount * $rates->color_rate;
                                $BettingoptionsAmountArray[$value->betting_options] = $total;
                                break;
                            default:
                                # code...
                                break;
                        }
                    }

                    $combinationAmountArray = [];
                    foreach ($conditions as $key => $value) {
                        if ($value->id == 1) {
                            $combinationAmountArray[$value->id] = $BettingoptionsAmountArray[$value->number];
                        } else {
                            $combinationAmountArray[$value->id] = $BettingoptionsAmountArray[$value->number]
                                + $BettingoptionsAmountArray[$value->color]
                                + $BettingoptionsAmountArray[$value->even_odd]
                                + $BettingoptionsAmountArray[$value->small_big];
                        }
                    }


                    // Step 1: Sort in descending order
                    arsort($combinationAmountArray);
                    // Step 2: Convert associative array to indexed array to shuffle
                    $keys = array_keys($combinationAmountArray);
                    shuffle($keys);

                    // Step 3: Rebuild the shuffled array
                    $shuffledArray = [];
                    foreach ($keys as $key) {
                        $shuffledArray[$key] = $combinationAmountArray[$key];
                    }

                    $nearestValue = null;
                    $nearestKey = null;
                    $minDifference = PHP_INT_MAX;
                    // return $BettingoptionsAmountArray;
                    // return $shuffledArray;

                    foreach ($shuffledArray as $key => $value) {
                        $difference = abs($distribute_amount_in_user - $value);
                        if ($difference <= $minDifference) {
                            $minDifference = $difference;
                            $nearestValue = $value;
                            $nearestKey = $key;
                        }
                    }


                    // arsort($combinationAmountArray);
                    // $nearestValue = null;
                    // $nearestKey = null;
                    // $minDifference = PHP_INT_MAX;

                    // // return $combinationAmountArray;

                    // foreach ($combinationAmountArray as $key => $value) {
                    //     $difference = abs($distribute_amount_in_user - $value);
                    //     if ($difference <= $minDifference) {
                    //         $minDifference = $difference;
                    //         $nearestValue = $value;
                    //         $nearestKey = $key;
                    //     }
                    // }


                    // $nearestValue = null;
                    // $nearestKey = null;
                    // $minDifference = PHP_INT_MAX;

                    // $resultArray = [];
                    // foreach ($combinationAmountArray as $key => $value) {
                    //     $difference = abs($distribute_amount_in_user - $value);
                    //     if ($difference < $minDifference) {
                    //         $minDifference = $difference;
                    //         $resultArray[$key] = [
                    //             'nearestValue' => $value,
                    //             'nearestKey' => $key
                    //         ];
                    //     }
                    // }

                    // // Select a random key from the $resultArray
                    // $randomKey = array_rand(array_keys($resultArray));

                    // // Get the selected value and its key
                    // $resultwin = $resultArray[$randomKey];
                    // $nearestValue = $resultwin['nearestValue'];
                    // $nearestKey = $resultwin['nearestKey'];

                    // $adminAmount = $totalBettingAmount - $nearestValue;
                    // $checkAdmin = Users::where('type', 'admin')->first();
                    // $comment = 'Admin Percentage From Roulette  Game And Amount Is' . $adminAmount;
                    // $check = $this->walletss(
                    //     $checkAdmin->id,
                    //     $adminAmount,
                    //     'Deposit',
                    //     'Game',
                    //     null,
                    //     'Complete',
                    //     'Deposit',
                    //     null,
                    //     null,
                    //     $comment
                    // );
                } else {
                    $getconditions = $conditions->random();
                    $nearestKey = $getconditions->id;
                }
            } else {
                $nearestKey = $checkcustomResult->roulettte_result_condition_id;
            }

            $resultCombination = $this->roulletResultCondition->whereId($nearestKey)->first();
            // Prepare data for result creation
            $numberResultData = [
                'period_id'    => $periods->id,
                'number'       => $resultCombination->number,
                'color'        => $resultCombination->color,
                'even_odd'     => $resultCombination->even_odd,
                'small_big'    => $resultCombination->small_big,
                'row'          => $resultCombination->row,
                'combination'  => $resultCombination->combination,
            ];

            // Create the result in the database
            $result = $this->roulletResult->create($numberResultData);
            $success['result'] = $result;
            // $this->resultcreate($numberResultData, 2,0);
            // Initialize the variables for betting options
            $num_result_id = null;
            $color_result_id = null;
            $even_odd_result_id = null;
            $small_big_result_id = null;
            $row_result_id = null;
            $combination_result_id = null;

            // Query the betting options
            if ($resultCombination->id === 1) {
                // Only retrieve the number for resultCombination with id === 1
                $num_result_id = $this->roulletBettingoptions->where('betting_options', $resultCombination->number)->first();
            } else {
                // Retrieve all necessary betting options for other cases
                $num_result_id = $this->roulletBettingoptions->where('betting_options', $resultCombination->number)->first();
                $color_result_id = $this->roulletBettingoptions->where('betting_options', $resultCombination->color)->first();
                $even_odd_result_id = $this->roulletBettingoptions->where('betting_options', $resultCombination->even_odd)->first();
                $small_big_result_id = $this->roulletBettingoptions->where('betting_options', $resultCombination->small_big)->first();
                $row_result_id = $this->roulletBettingoptions->where('betting_options', $resultCombination->row)->first();
                $combination_result_id = $this->roulletBettingoptions->where('betting_options', $resultCombination->combination)->first();
            }

            // return $combination_result_id;
            foreach ($numberBettings as $key => $value) {
                $winAmount = 0;
                $lossAmount = 0;
                switch ($value->betting_option_id) {
                    case $value->betting_option_id > 1 && $value->betting_option_id <= 13:
                        # code...
                        $winAmount = $value->balance * $rates->single_rate;
                        $lossAmount = $value->balance;
                        break;
                    case $value->betting_option_id == 14 || $value->betting_option_id == 15:
                        # code...
                        $winAmount = $value->balance * $rates->even_odd_rate;
                        $lossAmount = $value->balance;
                        break;
                    case $value->betting_option_id == 16 || $value->betting_option_id == 17:
                        # code...                 
                        $winAmount = $value->balance * $rates->big_small_rate;
                        $lossAmount = $value->balance;
                        break;
                    case $value->betting_option_id == 18 || $value->betting_option_id == 19:
                        # code...
                        $winAmount = $value->balance * $rates->color_rate;
                        $lossAmount = $value->balance;
                        break;
                    default:
                        # code...
                        break;
                }
                if ($resultCombination->id === 1) {
                    if (
                        in_array($value->betting_option_id, [
                            $num_result_id->id,
                        ])
                    ) {
                        // If it is a winning option, assign winning details
                        $comment = 'Win Roulette Game And Amount Is ' . $winAmount;

                        $check = $this->walletss(
                            2,
                            $value->user_id,
                            $value->id,
                            $winAmount,
                            'Profit',
                            $comment
                        );
                        
                        $this->Payment($value->user_id,$winAmount);

                        // Update the game result and wallet for a win
                        // $value->profit = $winAmount;
                        // $value->balance = 0;
                        // $value->result = 'win';
                        // $value->save();
                    } else {
                        // If not a winning option, assign losing details
                        $comment = 'Loss Roulette Game And Amount Is ' . $lossAmount;

                        $check = $this->walletss(
                            2,
                            $value->user_id,
                            $value->id,
                            $lossAmount,
                            'Loss',
                            $comment
                        );

                        // Update the game result and wallet for a loss
                        // $value->loss = $lossAmount;
                        // $value->balance = 0;
                        // $value->result = 'loss';
                        // $value->save();
                    }
                } else {
                    if (
                        in_array($value->betting_option_id, [
                            $num_result_id->id,
                            $color_result_id->id,
                            $even_odd_result_id->id,
                            $small_big_result_id->id
                        ])
                    ) {
                        // If it is a winning option, assign winning details
                        $comment = 'Win Roulette Game And Amount Is ' . $winAmount;

                        $check = $this->walletss(
                            2,
                            $value->user_id,
                            $value->id,
                            $winAmount,
                            'Profit',
                            $comment
                        );


                        $this->Payment($value->user_id,$winAmount);
                        // Update the game result and wallet for a win
                        // $value->profit = $winAmount;
                        // $value->balance = 0;
                        // $value->result = 'win';
                        // $value->save();
                    } else {
                        // If not a winning option, assign losing details
                        $comment = 'Loss Roulette Game And Amount Is ' . $winAmount;

                        $check = $this->walletss(
                            2,
                            $value->user_id,
                            $value->id,
                            $lossAmount,
                            'Loss',
                            $comment
                        );

                        // Update the game result and wallet for a loss
                        // $value->loss = $lossAmount;
                        // $value->balance = 0;
                        // $value->result = 'loss';
                        // $value->save();
                    }
                }
            }

            $success['user_result'] = $this->rouletteBettings->where('user_id', Auth::id())->where('period_id', $periods->id)->get();
            $success['new_period'] =  $this->periodcreate($request->game_id, $request->play_time_id);

            DB::commit();
            return $this->sendResponse($success, 'Result Fetch successfully.');
        }
        $success['result'] = [];
        $success['user_result'] = [];
        $this->periodcreate($request->game_id, $request->play_time_id);
        DB::commit();
        return $this->sendResponse($success, 'Result Fetch successfully.');
        // } catch (\Exception $ex) {
        DB::rollback();
        //     return $this->sendError('Validation Error.', $ex->getMessage());
        // }
    }
}
