<?php

namespace App\Http\Controllers\AdminAPI\GameManagement;

# Models
use App\Models\Day;
use App\Models\RateType;
use App\Models\Game;
use App\Models\Store;
use App\Models\GameRate;
use App\Models\GameGroup;
use App\Models\StoreGame;

# Other Classes
use DB;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use Auth;

class GameRateController extends BaseController
{
     # Define Base view
    protected $view = 'admin.game-rate.';

    #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 RateType model
    protected $rateType;

      /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                GameGroup $gameGroup,
                                Game $game,
                                RateType $rateType,
                                Day $day,
                                Store $store,
                                StoreGame $storeGame,
                                GameRate $gameRate
                            )
    {
        $this->gameGroup  = $gameGroup;
        $this->rateType  = $rateType;
        $this->game       = $game;
        $this->store      = $store;
        $this->day        = $day;
        $this->storeGame  = $storeGame;
        $this->gameRate   = $gameRate;
    }
   /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
         try
        {
         

           $relation = ['Stores','GameGroupName','GameName','Day'];
       
            #get all paymentUser resources

            $details['lists'] = $this->gameRate->with($relation)->where('created_at','!=',null)->paginate(10);
             
            #render view
            return $this->sendResponse($details, 'Result Get successfully.');
        }catch(\Exception $ex)
        {
          return $this->sendError($ex, 'Error');
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
         try{
            
            $realtion = ['gameRate'];
            $details['game']      = $this->game->with($realtion)->whereIn('id',[1,2,5,6,7,9,10,12])->where('status',1)->get();
                  
            #render view
            return $this->sendResponse($details, 'Result Get successfully.');
         }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }

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

                return $this->sendError($validate->messages(), 'Please Fill Mandatory field');
            }

                $rates = json_decode($request->rate, true);
                $game_ids = json_decode($request->game_id, true);
                
                $games = $this->game->where('status',1)->get();
                
            #update data
       
            foreach ($games as $key) {

                $rate = $rates[$key->id] ?? 0;
            
                $check = $this->gameRate
                    ->where('game_id', $key->id)
                    ->first();
            
                $data = [
                    'game_id'   => $key->id,
                    'rate'      => $rate * 10,
                    'user_id'   => Auth::id(),
                ];
            
                if ($check) {
                    $check->update($data);
                } else {
                    $this->gameRate->create($data);
                }
            }
                 #get the requested data in Data variable
              
           
               
               
            
           
            // #return redirect back to view
             toastr()->success('Rate Create Sucess fully ...');
             return $this->sendResponse(true, 'Result Get successfully.');
        //  }catch(\Exception $ex)
        // {
        //      toastr()->success($ex->getMessage());
        //     return $this->sendError($ex, 'Error');
        // }
    }

    /**
     * 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->where('status',1)->get();
            $details['day'] = $this->day->get();
            $details['detail'] = $this->gameRate->where('id', $id)->first();
            
            #return to view
            return $this->sendResponse($details, 'Result Get successfully.');
         }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }

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

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

            #update data
       
           
                 #get the requested data in Data variable
                $check =  $this->gameRate->where('game_id',$request->game_id)->first();
            $data = [
                    'game_id'          => $request->game_id,
                    'rate'             => $request->rate,
                    'user_id'          => Auth::user()->id ,
                    ];
            #store the newly creted resoures
            if($check){
                 $this->gameRate->whereId($check->id)->update($data);
            }else{
                 $this->gameRate->create($data);
            }
           
               
               
            
           
            // #return redirect back to view
             toastr()->success('Rate Update Sucess fully ...');
             return $this->sendResponse(true, 'Result Get successfully.');
         }catch(\Exception $ex)
        {
             toastr()->success($ex->getMessage());
            return $this->sendError($ex, 'Error');
        }
    }

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