<?php

namespace App\Http\Controllers\AdminAPI\GameManagement;

# Models
use App\Models\Day;
use App\Models\Game;
use App\Models\NewStore;
use App\Models\Payment;
use App\Models\GameRate;
use App\Models\GameGroup;
use App\Models\NewStoreGame;
use App\Models\NewGameWinner;
use App\Models\PaymentHistory;
use App\Models\NewUserWinnersAmount;
use App\Exports\userWinnerExport;
use App\Models\DebitPayment;

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

class NewUserWinnerController extends BaseController
{
      # Define Base view
    protected $view = 'admin.new-user-winner.';

    #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 UserWinnersAmount model
    protected $userWinnersAmount;


     #Bind Payment model
    protected $payment;
     #Bind PaymentHistory model
    protected $paymentHistory;

     #Bind DebitPayment model
    protected $debitPayment;

      /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                GameGroup $gameGroup,
                                Game $game,
                                Day $day,
                                NewStore $store,
                                NewStoreGame $storeGame,
                                GameRate $gameRate,
                                NewGameWinner $gameWinner,
                                Payment $payment,
                                PaymentHistory $paymentHistory,
                                NewUserWinnersAmount $userWinnersAmount,
                                DebitPayment $debitPayment
                            )
    {
        $this->gameGroup  = $gameGroup;
        $this->game       = $game;
        $this->store      = $store;
        $this->day        = $day;
        $this->storeGame  = $storeGame;
        $this->gameRate   = $gameRate;
        $this->gameWinner = $gameWinner;
        $this->userWinnersAmount = $userWinnersAmount;
        $this->payment  = $payment;
        $this->paymentHistory  = $paymentHistory;
        $this->debitPayment  = $debitPayment;
    }
    /**

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

          try
        {
            
            $input = $request->all();
           $relation = ['Stores','GameGroupName','GameName','Day','username','gameWinner'];
       
            #get all paymentUser resources

             $gamewinner = $this->userWinnersAmount->with($relation);
              $search_date = '';
            if(isset($input['search_date'])){
                $search_date = $input['search_date'];
                if(isset($search_date) && $search_date != null){
                $gamewinner->where('created_at','like',$search_date.'%');
                } 
            }else{
               $gamewinner->where('created_at','like',currentDate().'%');
            }
             $details['lists'] = $gamewinner->paginate(10);
            #render view
            return $this->sendResponse($details, 'Stores Game Schedule successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
   
      public function gameUserWinner(Request $request,$id)
    {
   

          try
        {
            
            $input = $request->all();
     
       
            #get all paymentUser resources

             $gamewinner = $this->userWinnersAmount->with('username')->where('time_id',$request->store)->where('game_id',$id)->where('type','=','open')->where('status',1);
              $search_date = '';
            if(isset($input['search_date'])){
                $search_date = $input['search_date'];
                if(isset($search_date) && $search_date != null){
                $gamewinner->where('created_at','like',$search_date.'%');
                } 
            }else{
               $gamewinner->where('created_at','like',currentDate().'%');
            }
             $details['lists'] = $gamewinner->paginate(10);
            #render view
            return $this->sendResponse($details, 'Stores Game Schedule successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
    
      public function gameUserWinnerClose(Request $request,$id)
    {
   

          try
        {
            
            $input = $request->all();
     
       
            #get all paymentUser resources

             $gamewinner = $this->userWinnersAmount->with('username')->where('time_id',$request->store)->where('game_id',$id)->where('type','=','close')->where('status',1);
              $search_date = '';
            if(isset($input['search_date'])){
                $search_date = $input['search_date'];
                if(isset($search_date) && $search_date != null){
                $gamewinner->where('created_at','like',$search_date.'%');
                } 
            }else{
               $gamewinner->where('created_at','like',currentDate().'%');
            }
             $details['lists'] = $gamewinner->paginate(10);
            #render view
            return $this->sendResponse($details, 'Stores Game Schedule successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
   
    
    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 userWinnerExport($search_date), 'user_winner.xlsx');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }

    /**
     * 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)
    {
        //
    }
     /**
     * Payment user
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function Payment(Request $request,$id)
    {
         DB::beginTransaction();
          try{
            $data = [
                    'payment_status'        => 1,
                    
                    ];
            #store the newly creted resoures
              $this->userWinnersAmount->whereId($id)->update($data);
          
            $game= $this->userWinnersAmount->find($id);

            $paymentchecck = $this->payment->where('user_id',$game->user_id)->first();
                if(!empty($paymentchecck)){
                        $paymentchecck->amount = $paymentchecck->amount+$game->amount;
                        $paymentchecck->save();
                }else{
                    #get the requested data in Data variable
                      $data = [
                        'payment_id' =>1,
                        'amount'       => $game->amount,
                        'user_id'    => $game->user_id,
                        ];
                    #store the newly creted resoures
                    $this->payment->create($data);
                }
                  $data = [
                    'debit_amount'       => 0,
                    'credit_amount'       => $game->amount,
                    'created_by'        =>Auth::user()->id,
                    'user_id'    => $game->user_id,
                    ];
                #store the newly creted resoures
                $this->debitPayment->create($data);
                $paymentHistorychecck = $this->paymentHistory->where('user_id',$game->user_id)->first();
                if(!empty($paymentHistorychecck)){
                        $paymentHistorychecck->total_amount = $paymentHistorychecck->total_amount+$game->amount;
                        $paymentHistorychecck->remain_amount = $paymentHistorychecck->remain_amount+$game->amount;
                        $paymentHistorychecck->save();
                }else{
                    #get the requested data in Data variable
                      $data = [
                        'total_amount'       => $game->amount,
                        'remain_amount'      => $game->amount,
                        'debit_total_amount' => 0,
                        'user_id'    => $game->user_id,
                        ];
                    #store the newly creted resoures
                    $this->paymentHistory->create($data);
                }
                DB::commit();
             toastr()->success('Payment Create Sucess fully ...');
                return redirect('/admin/user-winner');
                 
                  }catch(\Exception $ex)
        {
             DB::rollback();
            return $this->sendError($ex, 'Error');
        }
    }
}
