<?php

namespace App\Http\Controllers\Admin;

# Models
use App\User;
use App\Models\Day;
use App\Models\Bit;
use App\Models\Game;
use App\Models\Store;
use App\Models\JodiBit;
use App\Models\GameRate;
use App\Models\GameGroup;
use App\Models\StoreGame;
use App\Models\GameWinner;
use App\Models\SingleDigitBit;
use App\Models\ChoicePannaBit;
use App\Models\SinglePattiBit;
use App\Models\SinglePattiPannaBit;
use App\Models\DoublePattiBit;
use App\Models\DoublePattiPannaBit;
use App\Models\BeadOnMotor;
use App\Exports\gameWinnerExport;
use App\Models\UserWinnersAmount;

# Other Classes
use DB;
use Excel;
use Auth;
use Validator;
use App\Traits\FirebaseTraits;
use App\Traits\WinnerTrait;
use App\Traits\ShowWinnerTrait;
use App\Traits\GameTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\NotificationService;

class GameWinnerController extends Controller
{
        use FirebaseTraits;
    use WinnerTrait;
    use GameTrait;
    use ShowWinnerTrait;
    
    
    
      # Define Base view
    protected $view = 'admin.game-winner.';

    
    protected $notificationService;
    #Bind GameGroup model
    protected $gameGroup;
     
     #Bind StoreGame model
    protected $storeGame;

     #Bind Game model
    protected $game;

     #Bind Store model
    protected $store;

    #Bind Day model
    protected $day;

    #Bind GameRate model
    protected $gameRate;

    #Bind GameWinner model
    protected $gameWinner;

    #Bind Bit model
    protected $bit;

       #Bind SingleDigitBit model
    protected $singleDigitBit;

    #Bind ChoicePannaBit model
    protected $choicePannaBit;

    #Bind JodiBit model
    protected $jodiBit;

     #Bind SinglePattiBit model
    protected $singlePattiBit;

         #Bind SinglePattiPannaBit model
    protected $singlePattiPannaBit;

    #Bind DoublePattiBit model
    protected $doublePattiBit;

         #Bind DoublePattiPannaBit model
    protected $doublePattiPannaBit;

    #Bind BeadOnMotor model
    protected $beadOnMotor;

      /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                Day $day,
                                 User $user,
                                Bit $bit,
                                Game $game,
                                Store $store,
                                GameGroup $gameGroup,
                                StoreGame $storeGame,
                                GameRate $gameRate,
                                GameWinner $gameWinner,
                                SingleDigitBit $singleDigitBit,
                                ChoicePannaBit $choicePannaBit,
                                JodiBit $jodiBit,
                                SinglePattiBit $singlePattiBit,
                                SinglePattiPannaBit $singlePattiPannaBit,
                                DoublePattiBit $doublePattiBit,
                                DoublePattiPannaBit $doublePattiPannaBit,
                                BeadOnMotor $beadOnMotor,
                                NotificationService $notificationService
                            )
    {
        $this->bit                 = $bit;
        $this->gameGroup           = $gameGroup;
        $this->game                = $game;
        $this->store               = $store;
        $this->day                 = $day;
        $this->storeGame           = $storeGame;
        $this->gameRate            = $gameRate;
        $this->gameWinner          = $gameWinner;
        $this->singleDigitBit      = $singleDigitBit;
        $this->choicePannaBit      = $choicePannaBit;
        $this->jodiBit             = $jodiBit;
        $this->singlePattiBit      = $singlePattiBit;
        $this->singlePattiPannaBit = $singlePattiPannaBit;
        $this->doublePattiBit      = $doublePattiBit;
        $this->doublePattiPannaBit = $doublePattiPannaBit;
        $this->beadOnMotor         = $beadOnMotor;
        $this->notificationService    = $notificationService;
             $this->user                 = $user;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //  try{
            
           $input = $request->all();
           
           
           $date = isset($request->date) ? dateYYYYMMDD($request->date) : currentDate();
           
        
            #get all paymentUser resources
    
            $details['lists'] = $this->store
                ->with([
                    'storesDay',
                    'winnerbydate' => function ($q) use ($date) {
                        $q->where('created_at', 'like', $date . '%');
                    },
                ])
                ->select('*')
                ->selectRaw('
                    (SELECT opent_time 
                     FROM stores_game 
                     WHERE stores_game.stores_id = stores.id 
                     ORDER BY opent_time ASC 
                     LIMIT 1) as open_time_sort
                ')
                ->orderBy('open_time_sort', 'ASC') 
                ->paginate(150);

          
          
        //   return $details;
       
            #render view
            return view($this->view.'index',$details);
        // }catch(\Exception $ex)
        // {
        //     return back()->with('error', $ex->getMessage());
        // }
    }
     public function downloadExcel(Request $request)
    {

         try
        {
            
           $input = $request->all();
             $search_date = '';
            if(isset($input['search_date'])){
                $search_date = $input['search_date'];
                
            }else{
                $search_date = currentDate();
            }
           return Excel::download(new gameWinnerExport($search_date), 'game_winner.xlsx');
        }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        try{
              $relation =['storesDay'];
            $details['store'] = $this->store->with( $relation)->get();
            #render view
            return view($this->view.'create',$details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    
      public function gameWinner(Request $request,$id)
    {
        
         try
        {
          
            $input = $request->all();
            $realtion = ['gameRate'];
            $gamess = $this->game->with($realtion)->orderBy('id', 'asc')->get();
            $data = array();
  
            $i=0;
            $totalamount =0;
            foreach($gamess as $key){
                $result = '';
                 $data[$i]['name'] = $key->name;
                 $data[$i]['rate'] = $key->gameRate->rate;
                 $data[$i]['id'] = $key->id;
                  $data[$i]['amount'] = $key->id == 10 || $key->id == 2 ? 0 : $this->bit->where('created_at','like',currentDate().'%')->where('stores_id',$id)->where('game_id',$key->id)->where('type','=','open')->sum('amount');
                 $data[$i]['winneramount'] =  UserWinnersAmount::where('created_at','like',currentDate().'%')->where('stores_id',$id)->where('game_id',$key->id)->where('type','=','open')->sum('amount');
                 $totalamount = $totalamount+$data[$i]['winneramount'];
                 $i++;
                
            }
       
            $details['game'] = $data;
            $details['storesid'] =$id;
             $details['storess'] = $this->store->whereId($id)->first();
             $details['result'] =$this->gameWinner->where('stores_id',$id)->orderBy('created_at', 'DESC')->first();
             
             $details['totalamount'] =  $totalamount ;
             
            
            #render view
            return view($this->view.'gamewinner',$details);
        }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
        
        
    }
    
         public function gameWinnerClose(Request $request,$id)
    {
        
         try
        {
            
            
           
            $input = $request->all();
            $realtion = ['gameRate'];
            $gamess = $this->game->with($realtion)->orderBy('id', 'asc')->get();
            $data = array();
            $i=0;
            foreach($gamess as $key){
                $result = '';
                 $data[$i]['name'] = $key->name;
                 $data[$i]['rate'] = $key->gameRate->rate;
                 $data[$i]['id'] = $key->id;
                  $data[$i]['amount'] = $key->id == 10 || $key->id == 2 ? $this->bit->where('created_at','like',currentDate().'%')->where('stores_id',$id)->where('game_id',$key->id)->where('type','=','open')->sum('amount') : $this->bit->where('created_at','like',currentDate().'%')->where('stores_id',$id)->where('game_id',$key->id)->where('type','=','close')->sum('amount');
                 $data[$i]['winneramount'] =  UserWinnersAmount::where('created_at','like',currentDate().'%')->where('stores_id',$id)->where('game_id',$key->id)->where('type','=','close')->sum('amount');
                 $i++;
                
            }
       
            $details['game'] = $data;
             
             $details['storess'] = $this->store->whereId($id)->first();
             
             $details['result'] =$this->gameWinner->where('stores_id',$id)->orderBy('created_at', 'DESC')->first();
            
             $details['totalamount'] =  $this->bit->where('created_at','like',currentDate().'%')->where('type','=','close')->where('stores_id',$id)->sum('amount');
             $details['storessnew'] = $this->store->whereId($id)->first();
            $details['storesid'] =$id;
          
            #render view
            return view($this->view.'gamewinnerclose',$details);
        }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
        
        
    }
    
      public function addOpenResult(Request $request,$id)
    {
        try{
              $relation =['storesDay'];
            $details['store'] = $this->store->with($relation)->whereId($id)->first();
           
           $details['date'] = $request->date ?? currentDate();
           
            #render view
            return view($this->view.'create',$details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    
      public function addOpenReverseResult(Request $request,$id)
    {
        try{
              $relation =['storesDay'];
            $details['store'] = $this->store->with( $relation)->whereId($id)->first();
            #render view
           $details['date'] = $request->date ?? currentDate();
            return view($this->view.'reverse',$details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    
      public function postOpenResult(Request $request,$id)
    {
        
         $date = $request->date ?? currentDate();
            $user_id = Auth::user()->id;
          DB::beginTransaction();
         
        //   try{
              
               $bit_open = $request->result;   // Example: "127"

                // Patti (first 3 digits)
                $patti = substr($bit_open, 0, 3);
                
                // Remove anything that is not a digit
                $onlyDigits = preg_replace('/\D/', '', $bit_open);
                
                // Sum of digits
                $sum = array_sum(str_split($onlyDigits));
                
                // Last digit of sum
                $digit = $sum % 10;
                
                // update the result as 127-0
                $request->merge([
                    'result' => $bit_open . '-' . $digit
                ]);
              
            $data = [
                    'stores_id'        => $id,
                    'game_id'          => 1,
                    'game_group_id'    => 1,
                    'day_id'           => 2,
                    'bit_place'        => 00000,
                    'open_time'        => $request->result,
                    'user_id'          => Auth::user()->id,
                    'date'          => $date,
              'created_at'  => $date,
                    ];
            #store the newly creted resoures
            
            
            $check =  $this->gameWinner->where('stores_id',$id)->where('created_at', 'like', $date.'%')->first();
         
            if($check){
                
                if(isset($check->open_time)){
                    DB::commit();
                  toastr()->success('Winner Create Sucess fully ...');
                return redirect('/admin/game-winner');
                }
                
                 $this->gameWinner->whereId($check->id)->update($data);
                $winer= $check;
            }else{
                $winer= $this->gameWinner->create($data);
            }
            
            
            $bit_open = (str_replace('-','',$request->result));
          
            $patti = $bit_open[0].$bit_open[1].$bit_open[2];
            $digit = $bit_open[3];
          
            $this->SingleDigitOpen($id,$digit,$winer->id,$date);
            $this->SinglePannaOpen($id,$patti,$winer->id,$date);
            $this->DoublePannaOpen($id,$patti,$winer->id,$date);
            $this->TripplePannaOpen($id,$patti,$winer->id,$date);
            $this->PannaSpOpen($id,$patti,$winer->id,$date);
            $this->PannaDpOpen($id,$patti,$winer->id,$date);
            $this->PannaFamilyOpen($id,$patti,$winer->id,$date);
            $this->CyclePattiOpen($id,$patti,$winer->id,$date);
            $this->SPMotorOpen($id,$patti,$winer->id,$date);
            $this->DPMotorOpen($id,$patti,$winer->id,$date);
            
             $postcust = $this->user->whereId($user_id)->first();
             $relation =['storesDay'];
             $stt = $this->store->with($relation)->whereId($id)->first();
                    $user_id = $user_id;
                    $name = $postcust->name.''.isset( $stt->storesDay) ? timeShow( $stt->storesDay->opent_time) : '';
                    $body = $request->result.'-x-xxx';
                    $title = $stt->name." Open";
                    // $this->notification($title,$body,$user_id);
                    
                    $noti = app(NotificationService::class)->sendPushNotification(
                            $stt->name, // title/message
                            $body, // title/message
                                [                                 // additional data (make sure it's a one-dimensional array)
                                    'type' => 'commentReplied',
                                ]
                            );
         
              DB::commit();
              toastr()->success('Winner Create Sucess fully ...');
            return redirect('/admin/game-winner');
        //  }catch(\Exception $ex)
        // {
        //      DB::rollback();
        //     return back()->with('error', $ex->getMessage());
        // }
    }
    
        
      public function postOpenReverseResult(Request $request,$id)
    {
        
       
          DB::beginTransaction();
         $date = $request->date ?? currentDate();
        // try{
            $data = [
                    'stores_id'        => $id,
                    'game_id'          => 1,
                    'game_group_id'    => 1,
                    'day_id'           => 2,
                    'bit_place'        => 00000,
                    'open_time'        => null,
                    'user_id'          => Auth::user()->id,
                    'date'          => $date,
              'created_at'  => $date,
                    ];
            #store the newly creted resoures
            
            $check =  $this->gameWinner->where('stores_id',$id)->where('created_at', 'like', $date.'%')->first();
         
            if($check){
                 $winer= $this->gameWinner->whereId($check->id)->update($data);
                
                //   $winer= $this->gameWinner->whereId($check->id)->first();
            }
            
                 $userwinnercheck = UserWinnersAmount::where('game_winners_id',$check->id)->where('type','=','open')->get();
                 if(count( $userwinnercheck)>0){
                      foreach($userwinnercheck as $vv){
                         
                      debitReverseAmount($vv->user_id,$vv->amount);
                      $remark = " Result Reverse  By Admin ".$vv->amount;
                       PaymentRemarkReverse($vv->user_id, $remark,$vv->amount);
                        UserWinnersAmount::whereId($vv->id)->delete();
                      }
                 }
           
          
              DB::commit();
              toastr()->success('Winner Create Sucess fully ...');
            return redirect('/admin/game-winner');
        //  }catch(\Exception $ex)
        // {
        //      DB::rollback();
        //     return back()->with('error', $ex->getMessage());
        // }
    }
    
      public function addCloseResult(Request $request,$id)
    {
        try{
              $relation =['storesDay'];
            $details['store'] = $this->store->with( $relation)->whereId($id)->first();
            #render view
           $details['date'] = $request->date ?? currentDate();
            return view($this->view.'create_close',$details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    
      public function postCloseResult(Request $request,$id)
    {
        
 
      $date = $request->date ?? currentDate();
          DB::beginTransaction();
         
        //   try{
        
        $bit_open = $request->result;   // Example: "127"

                // Patti (first 3 digits)
                $patti = substr($bit_open, 0, 3);
                
                // Remove anything that is not a digit
                $onlyDigits = preg_replace('/\D/', '', $bit_open);
                
                // Sum of digits
                $sum = array_sum(str_split($onlyDigits));
                
                // Last digit of sum
                $digit = $sum % 10;
                
                // update the result as 127-0
                $request->merge([
                    'result' => $digit . '-' . $bit_open,
                ]);
        
              $check = $this->gameWinner->where('stores_id',$id)->where('created_at','like',$date.'%')->first();
              
            $data = [
                    'stores_id'        => $id,
                    'game_id'          => 1,
                    'game_group_id'    => 1,
                    'day_id'           => 2,
                    'bit_place'        => 00000,
                    'close_time'        => $request->result,
                    'user_id'          => Auth::user()->id ,
                    'date'          => $date,
              'created_at'  => $date,
                    ];
            #store the newly creted resoures
            if($check){
                
                if(isset($check->close_time)){
                    DB::commit();
                  toastr()->success('Winner Create Sucess fully ...');
                return redirect('/admin/game-winner');
                }
                 $this->gameWinner->whereId($check->id)->update($data);
                 $winer= $check;
            }else{
                 $winer= $this->gameWinner->create($data);
            }
           
           
        
                
            $bit_open = (str_replace('-','',$request->result));
            $bit_open_open = (str_replace('-','',$winer->open_time));
          
            $patti = $bit_open[1].$bit_open[2].$bit_open[3];
            $patti_open = $bit_open_open[0].$bit_open_open[1].$bit_open_open[2];
            $single_open = $bit_open_open[3];
            $digit = $bit_open[0];
          
            $this->SingleDigitClose($id,$digit,$winer->id,$date);
            $this->SinglePannaClose($id,$patti,$winer->id,$date);
            $this->DoublePannaClose($id,$patti,$winer->id,$date);
            $this->TripplePannaClose($id,$patti,$winer->id,$date);
            $this->PannaSpClose($id,$patti,$winer->id,$date);
            $this->PannaDpClose($id,$patti,$winer->id,$date);
            $this->PannaFamilyClose($id,$patti,$winer->id,$date);
             $this->CyclePattiClose($id,$patti,$winer->id,$date);
            $this->FullSangamClose($id,$patti,$patti_open,$winer->id,$date);
            $this->SPMotorClose($id,$patti,$winer->id,$date);
            $this->DPMotorClose($id,$patti,$winer->id,$date);
            
            
            
            $this->HalfSangamOpen($id,$patti_open,$digit,$winer->id,$date);
            $this->HalfSangamClose($id,$patti,$single_open,$winer->id,$date);
            
             if($check){
                  $bitopenss = $check->open_time;
                  $digit1 = $bitopenss[4];
                  $jodibb = $digit1.''.$digit;
                 
                  $this->JodiClose($id,$jodibb,$winer->id,$date);
                  $this->RedJodiClose($id,$jodibb,$winer->id,$date);
                  $this->RedJodiFamilyClose($id,$jodibb,$winer->id,$date);
                  $this->JodiFamilyClose($id,$jodibb,$winer->id,$date);
            }
              $postcust = $this->user->whereId(1)->first();
             $relation =['storesDay'];
             $stt = $this->store->with($relation)->whereId($id)->first();
                    $user_id = 3;
                    $name = $postcust->name.''.isset( $stt->storesDay) ? timeShow( $stt->storesDay->close_time) : '';
                    $body = $winer->open_time.''.$request->result;
                    $title = $stt->name." Close";
                    // $this->notification($title,$body,$user_id);
                    
                     $noti = app(NotificationService::class)->sendPushNotification(
                            $stt->name, // title/message
                            $body, // title/message
                                [                                 // additional data (make sure it's a one-dimensional array)
                                    'type' => 'commentReplied',
                                ]
                            );
                    
            //   dd($digit);
              DB::commit();
              toastr()->success('Winner Create Sucess fully ...');
            return redirect('/admin/game-winner');
        //  }catch(\Exception $ex)
        // {
        //      DB::rollback();
        //     return back()->with('error', $ex->getMessage());
        // }
    }
    
      public function addCloseReverseResult(Request $request,$id)
    {
        try{
              $relation =['storesDay'];
            $details['store'] = $this->store->with( $relation)->whereId($id)->first();
            #render view
           $details['date'] = $request->date ?? currentDate();
            return view($this->view.'reverse_close',$details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    public function postCloseReverseResult(Request $request,$id)
    {
        
 
      $date = $request->date ?? currentDate();
          DB::beginTransaction();
         
        //   try{
              $check = $this->gameWinner->where('stores_id',$id)->where('created_at','like',$date.'%')->first();
              
            $data = [
                    'stores_id'        => $id,
                    'game_id'          => 1,
                    'game_group_id'    => 1,
                    'day_id'           => 2,
                    'bit_place'        => 00000,
                    'close_time'        => null,
                    'user_id'          => Auth::user()->id ,
                    'date'          => $date,
              'created_at'  => $date,
                    ];
            #store the newly creted resoures
            if($check){
                 $this->gameWinner->whereId($check->id)->update($data);
                 $winer= $check;
            }else{
                 $winer= $this->gameWinner->create($data);
            }
            
               $userwinnercheck = UserWinnersAmount::where('game_winners_id',$check->id)->where('type','=','open')->where('game_id',2)->get();
               
             
        
                 if(count( $userwinnercheck)>0){
                      foreach($userwinnercheck as $vv){
                         
                      debitReverseAmount($vv->user_id,$vv->amount);
                      
                     $remark = " Result Reverse  By Admin ".$vv->amount;
                       PaymentRemarkReverse($vv->user_id, $remark,$vv->amount);
                       
                       UserWinnersAmount::whereId($vv->id)->delete();
                      }
                 }
                 
             $userwinnercheck = UserWinnersAmount::where('game_winners_id',$check->id)->where('type','=','close')->get();
                 if(count( $userwinnercheck)>0){
                      foreach($userwinnercheck as $vv){
                         
                      debitReverseAmount($vv->user_id,$vv->amount);
                      $remark = " Result Reverse  By Admin ".$vv->amount;
                       PaymentRemarkReverse($vv->user_id, $remark,$vv->amount);
                       UserWinnersAmount::whereId($vv->id)->delete();
                      }
                 }
           
            
              DB::commit();
              toastr()->success('Winner Create Sucess fully ...');
            return redirect('/admin/game-winner');
        //  }catch(\Exception $ex)
        // {
        //      DB::rollback();
        //     return back()->with('error', $ex->getMessage());
        // }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
       {
         
         DB::beginTransaction();
          try{
             #validate the request
            
            $validate = Validator::make($request->all(),[
                                                         'stores_id'         => 'required'
                                                        ]);
            if($validate->fails()){

                return redirect()->back()->withErrors($validate);
            }

            #update data
                
           
                 #get the requested data in Data variable
                
            $data = [
                    'stores_id'        => $request->stores_id,
                    'game_id'          => 1,
                    'game_group_id'    => 1,
                    'day_id'           => 2,
                    'bit_place'        => 00000,
                    'open_time'        => $request->bit_open,
                    'close_time'       => isset($request->bit_close) ? $request->bit_close : 'xxx-x',
                    'user_id'          => Auth::user()->id ,
                    ];
            #store the newly creted resoures
            $winer= $this->gameWinner->create($data);
            $request['game_winners_id'] = $winer->id;
            $bit_open = (str_replace('-','',$request->bit_open));
            $patti = $bit_open[0].$bit_open[1].$bit_open[2];
            $digit = $bit_open[3];
            $singlepatti = $this->SingleDigitOpen($request,$digit);
            
             $sp = $this->checkSp();
             $dp = $this->checkDp();
             $spdp = '';
            //  $bidonmotorcombination = bidOnMotorCombination($bit_open);
             // $jodiamount = $this->jodiCompare($request,$digit);
             if(!in_array($patti,$this->checkTripple())){

                if(in_array($patti,$sp)){
                 
                          $spdpamount = $this->singlePattiOpen($request,$patti);
                          $bidonamount = $this->SpbedOnMotorOpen($request,$bidonmotorcombination);
                             

                 }
                 if(in_array($patti,$dp)){

                    $spdpamount = $this->doublePattiOpen($request,$patti);
                    $bidonamount = $this->DpbedOnMotorOpen($request,$bidonmotorcombination);
                 }
             }else{
                $spdpamount = $this->triplePattiOpen($request,$patti);
                $bidonamount = 0;
             }
             
             
             
             if($request->bit_close){
                $bit_close = (str_replace('-','',$request->bit_close));
                $patti_close = $bit_close[0].$bit_close[1].$bit_close[2];
                $digit_close = $bit_close[3];
                $jodi_digit = $digit.$digit_close;
                $singlepatti_close = $this->SingleDigitClose($request,$digit_close);
                    $jodiamount = $this->jodiBitwinner($request,$jodi_digit);
                 if(!in_array($patti_close,$this->checkTripple())){

                    if(in_array($patti_close,$sp)){
                     
                              $Closespdpamount = $this->singlePattiClose($request,$patti_close);
                              $Closebidonamount = $this->SpbedOnMotorClose($request,$bidonmotorcombination);
                                 

                     }
                     if(in_array($patti_close,$dp)){

                         $Closespdpamount = $this->doublePattiClose($request,$patti_close);
                          $Closebidonamount = $this->DpbedOnMotorClose($request,$bidonmotorcombination);
                     }
                 }else{
                    $Closespdpamount = $this->triplePattiClose($request,$patti_close);
                    $Closebidonamount = 0;
                 }
            }   
            
             DB::commit();
            // #return redirect back to view
             toastr()->success('Winner Create Sucess fully ...');
            return redirect('/admin/game-winner');
         }catch(\Exception $ex)
         {
            DB::rollback();
             toastr()->success($ex->getMessage());
            return back()->with('error', $ex->getMessage());
         }
    }

    /**
     * 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)
    {
        
        try{
            # Fetch records
             $details['store'] = $this->store->get();
            $details['gameGroup'] = $this->gameGroup->get();
            $details['game']      = $this->game->get();
            $details['day'] = $this->day->get();
            $details['detail'] = $this->gameWinner->where('id', $id)->first();
            
            #return to view
            return view($this->view.'edit', $details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
         DB::beginTransaction();
          try{
             #validate the request
            
            $validate = Validator::make($request->all(),[
                                                         'stores_id'         => 'required'
                                                        ]);
            if($validate->fails()){

                return redirect()->back()->withErrors($validate);
            }

            #update data
                
           
                 #get the requested data in Data variable
                
            $data = [
                    'stores_id'        => $request->stores_id,
                    'game_id'          => 1,
                    'game_group_id'    => 1,
                    'day_id'           => 2,
                    'bit_place'        => 00000,
                    'open_time'        => $request->bit_open,
                    'close_time'       => isset($request->bit_close) ? $request->bit_close : 'xxx-x',
                    'user_id'          => Auth::user()->id ,
                    ];
            #store the newly creted resoures
            $winer= $this->gameWinner->whereId($id)->update($data);
            $request['game_winners_id'] = $id;
            $bit_open = (str_replace('-','',$request->bit_open));
            $patti = $bit_open[0].$bit_open[1].$bit_open[2];
            $digit = $bit_open[3];
            $singlepatti = $this->SingleDigitOpen($request,$digit);

             $sp = $this->checkSp();
             $dp = $this->checkDp();
             $spdp = '';
             $bidonmotorcombination = bidOnMotorCombination($bit_open);
             // $jodiamount = $this->jodiCompare($request,$digit);
             if(!in_array($patti,$this->checkTripple())){

                if(in_array($patti,$sp)){
                 
                          $spdpamount = $this->singlePattiOpen($request,$patti);
                          $bidonamount = $this->SpbedOnMotorOpen($request,$bidonmotorcombination);
                             

                 }
                 if(in_array($patti,$dp)){

                    $spdpamount = $this->doublePattiOpen($request,$patti);
                    $bidonamount = $this->DpbedOnMotorOpen($request,$bidonmotorcombination);
                 }
             }else{
                $spdpamount = $this->triplePattiOpen($request,$patti);
                $bidonamount = 0;
             }
             if($request->bit_close){
                $bit_close = (str_replace('-','',$request->bit_close));
                $patti_close = $bit_close[0].$bit_close[1].$bit_close[2];
                $digit_close = $bit_close[3];
                $jodi_digit = $digit.$digit_close;
                $singlepatti_close = $this->SingleDigitClose($request,$digit_close);
                    $jodiamount = $this->jodiBitwinner($request,$jodi_digit);
                 if(!in_array($patti_close,$this->checkTripple())){

                    if(in_array($patti_close,$sp)){
                     
                              $Closespdpamount = $this->singlePattiClose($request,$patti_close);
                              $Closebidonamount = $this->SpbedOnMotorClose($request,$bidonmotorcombination);
                                 

                     }
                     if(in_array($patti_close,$dp)){

                         $Closespdpamount = $this->doublePattiClose($request,$patti_close);
                          $Closebidonamount = $this->DpbedOnMotorClose($request,$bidonmotorcombination);
                     }
                 }else{
                    $Closespdpamount = $this->triplePattiClose($request,$patti_close);
                    $Closebidonamount = 0;
                 }
            }   
            
             DB::commit();
            // #return redirect back to view
             toastr()->success('Winner Updated Sucess fully ...');
            return redirect('/admin/game-winner');
         }catch(\Exception $ex)
         {
            DB::rollback();
             toastr()->success($ex->getMessage());
            return back()->with('error', $ex->getMessage());
         }
    }

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

        $details['bitamount'] = $this->bit->where('stores_id',$request->stores_id)->where('type',$request->open)->sum('amount');
        $details['p_r_amount'] =0;
        $details['winnamount'] = 0;
        #start open 
        $bit_open = (str_replace('-','',$request->bit_open));
       
        $patti = $bit_open[0].$bit_open[1].$bit_open[2];
        $digit = $bit_open[3];
        $singlepatti = $this->SingleDigitCompare($request,$digit);

         $sp = $this->checkSp();
         $dp = $this->checkDp();
         $spdp = '';
         $bidonmotorcombination = bidOnMotorCombination($bit_open);
         // $jodiamount = $this->jodiCompare($request,$digit);
         if(!in_array($patti,$this->checkTripple())){

            if(in_array($patti,$sp)){
             
                      $spdpamount = $this->sPDpCompare($request,$patti);
                      $bidonamount = $this->bidOnSpCompare($request,$bidonmotorcombination);
                         

             }
             if(in_array($patti,$dp)){

                 $spdpamount = $this->dPspCompare($request,$patti);
                  $bidonamount = $this->bidOnDpCompare($request,$bidonmotorcombination);
             }
         }else{
            $spdpamount = $this->tripleCompare($request,$patti);
            $bidonamount = 0;
         }
        $details['winnamount'] = $singlepatti+$spdpamount+$bidonamount;
        $details['p_r_amount'] =$details['bitamount']-$details['winnamount'];
         #endopen

         #start close 
        if($request->bit_close){
            $bit_close = (str_replace('-','',$request->bit_close));
            $patti_close = $bit_close[0].$bit_close[1].$bit_close[2];
            $digit_close = $bit_close[3];
            $jodi_digit = $digit.$digit_close;
            $singlepatti_close = $this->SingleDigitCloseCompare($request,$digit_close);
            $jodiamount = $this->jodiCompare($request,$jodi_digit);
             if(!in_array($patti_close,$this->checkTripple())){

                if(in_array($patti_close,$sp)){
                 
                          $Closespdpamount = $this->sPDpCloseCompare($request,$patti_close);
                          $Closebidonamount = $this->bidOnSpCloseCompare($request,$bidonmotorcombination);
                             

                 }
                 if(in_array($patti_close,$dp)){

                     $Closespdpamount = $this->dPspCloseCompare($request,$patti_close);
                      $Closebidonamount = $this->bidOnDpCloseCompare($request,$bidonmotorcombination);
                 }
             }else{
                $Closespdpamount = $this->tripleClosedCompare($request,$patti_close);
                $Closebidonamount = 0;
             }
             $details['bitamountclose'] =$this->bit->where('stores_id',$request->stores_id)->where('type','=','close')->sum('amount');
              $details['winnamountclose'] = $singlepatti_close+$jodiamount+$Closespdpamount+$Closebidonamount;
              $details['p_r_amountclose'] =$details['bitamountclose']-$details['winnamountclose'];
             #end close
              
        } 
            
        
         
             
       
       
         

        #render view
        return view($this->view.'compare',$details);
    }
    
    public function showWinner($stores_id,$type,$open_panna,$close_panna,$date){
        
        $opendigit = '';
        $closedigit = '';
        $jodi   = '';
        if($open_panna){
                // Patti (first 3 digits)
                $patti = substr($open_panna, 0, 3);
                
                // Remove anything that is not a digit
                $onlyDigits = preg_replace('/\D/', '', $open_panna);
                
                // Sum of digits
                $sum = array_sum(str_split($onlyDigits));
                
                // Last digit of sum
                $opendigit = $sum % 10;
        }
        if($close_panna){
                // Patti (first 3 digits)
                $patti = substr($close_panna, 0, 3);
                
                // Remove anything that is not a digit
                $onlyDigits = preg_replace('/\D/', '', $close_panna);
                
                // Sum of digits
                $sum = array_sum(str_split($onlyDigits));
                
                // Last digit of sum
                $closedigit = $sum % 10;
        }
        
        if($opendigit && $closedigit){
            $jodi = $opendigit.$closedigit;
        }
        $list = [];
        if($type == 'open'){
            $list = array_merge(
                $list,
                 $this->WinSingleDigitOpen($stores_id,$opendigit,$date),
                $this->WinSinglePannaOpen($stores_id,$open_panna,$date),
                $this->WinDoublePannaOpen($stores_id,$open_panna,$date),
                $this->WinTripplePannaOpen($stores_id,$open_panna,$date),
                $this->WinPannaSpOpen($stores_id,$open_panna,$date),
                $this->WinPannaDpOpen($stores_id,$open_panna,$date),
                $this->WinPannaFamilyOpen($stores_id,$open_panna,$date),
                $this->WinCyclePattiOpen($stores_id,$open_panna,$date),
                $this->WinSPMotorOpen($stores_id,$open_panna,$date),
                $this->WinDPMotorOpen($stores_id,$open_panna,$date)
            );
        }
        
        if ($type == 'close') {

            $list = array_merge(
                $this->WinSingleDigitClose($stores_id, $closedigit, $date),
                $this->WinSinglePannaClose($stores_id, $close_panna, $date),
                $this->WinDoublePannaClose($stores_id, $close_panna, $date),
                $this->WinTripplePannaClose($stores_id, $close_panna, $date),
                $this->WinPannaSpClose($stores_id, $close_panna, $date),
                $this->WinPannaDpClose($stores_id, $close_panna, $date),
                $this->WinPannaFamilyClose($stores_id, $close_panna, $date),
                $this->WinCyclePattiClose($stores_id, $close_panna, $date),
                $this->WinFullSangamClose($stores_id, $patti, $open_panna, $date),
                $this->WinSPMotorClose($stores_id, $close_panna, $date),
                $this->WinDPMotorClose($stores_id, $close_panna, $date)
            );
        
            if ($jodi) {
        
                $list = array_merge(
                    $list,
                    $this->WinJodiClose($stores_id, $jodi, $date),
                    $this->WinRedJodiClose($stores_id, $jodi, $date),
                    $this->WinRedJodiFamilyClose($stores_id, $jodi, $date),
                    $this->WinJodiFamilyClose($stores_id, $jodi, $date)
                );
            }
        
            $list = array_merge(
                $list,
                $this->WinHalfSangamOpen($stores_id, $open_panna, $closedigit, $date),
                $this->WinHalfSangamClose($stores_id, $close_panna, $opendigit, $date)
            );
        }
        
        
        return $list;
    }
    
    
    public function declareResult(Request $request){
        
         DB::beginTransaction();
        //   try{
             #validate the request
            
            $validate = Validator::make($request->all(),[
                     'stores_id'         => 'required',
                     'type'         => 'required',
                    ]);
            if($validate->fails()){

                return redirect()->back()->withErrors($validate);
            }

            $request->date = isset($request->date) ? $request->date : currentDate();
            
            #update data
            if($request->btn_type == 'declare_result'){
                
                    $validate = Validator::make($request->all(),[
                             'result'         => 'required',
                            ]);
                    if($validate->fails()){
        
                        return redirect()->back()->withErrors($validate);
                    }
                
                if($request->type == 'open'){
                    $this->postOpenResult($request,$request->stores_id);
                }else{
                    $this->postCloseResult($request,$request->stores_id);
                }
                 DB::commit();
                // #return redirect back to view
                 toastr()->success('Winner Create Sucess fully ...');
                return redirect('/admin/game-winner');
            }
            if($request->btn_type == 'show_winner'){
                $list['winlist'] = [];
                if(isset($request->result)){
                    if($request->type == 'open'){
                       $list['winlist'] = $this->showWinner($request->stores_id,$request->type,$request->result,null,$request->date);
                    }else{
                       $list['winlist'] =  $this->showWinner($request->stores_id,$request->type,null,$request->result,$request->date);
                    }
                }
                
                if(isset($request->open_panna) || isset($request->close_panna)){
                    $list['winlist'] =  $this->showWinner($request->stores_id,$request->type,$request->open_panna,$request->close_panna,$request->date);
                }
                
                // return $list;
             DB::commit();
                return view('admin.show-winner.list',$list);
                
            }
            
            
             DB::commit();
            // #return redirect back to view
             toastr()->success('Winner Create Sucess fully ...');
            return redirect('/admin/game-winner');
        //  }catch(\Exception $ex)
        //  {
        //     DB::rollback();
        //      toastr()->success($ex->getMessage());
        //     return back()->with('error', $ex->getMessage());
        //  }
        
        
    }
    
    public function winnerPrediction(Request $request){
        
          try{
              
              
            $list['stores'] = $this->store->where('status',1)->get();
            
                return view('admin.show-winner.index',$list);
                
            
         }catch(\Exception $ex)
         {
             toastr()->success($ex->getMessage());
            return back()->with('error', $ex->getMessage());
         }
        
        
    }
    
}