<?php

namespace App\Http\Controllers\API;

# Models
use App\Models\Store;
use App\Models\Bit;
use App\Models\StoreGame;
use App\Models\RedJodiBit;

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

class RedJodiController extends BaseController
{
      #Bind Bit model
    protected $bit;

     #Bind RedJodiBit model
    protected $redJodiBit;
    
        #Bind Store model
    protected $store;


    /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                Bit $bit,
                                Store $store,
                                 StoreGame $storeGame,
                                RedJodiBit $redJodiBit
                            )
    {
        $this->bit  = $bit;
        $this->redJodiBit       = $redJodiBit;
          $this->storeGame                = $storeGame;
        $this->store                = $store;
        
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * 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)
    {
         DB::beginTransaction();
        try{
             $validator = Validator::make($request->all(), [
                'stores_id' => 'required',
                'game_id' => 'required',
                'type' => 'required',
                'amount' => 'required',
                'bit_place' => 'required',
            ]);

            if($validator->fails()){
                return $this->sendError('Validation Error.', $validator->errors());       
            }
              $time = '';
                
                $storess = $this->storeGame->where('stores_id',$request->stores_id)->first();
             
                    $time = $storess->opent_time;
                    
                
                    if(timeComapre($time)){
                         return $this->sendError('Error.', "Time Out");   
                    }
                
                 $totalamount = totalAmount(auth('api')->user()->id);
           $bittotalamout =0;
             
             foreach ($request->bit_place as $key => $bit_place) {
                  $bittotalamout =  $bittotalamout+ $bit_place;
             }
            
             
            if($bittotalamout>$totalamount){
                return $this->sendError('Error.', "You have not sufficient balance");    
            }else{
                
            }
              
                $bitcheck = $this->bit->where('created_at','like',currentDate().'%')->where('stores_id',$request->stores_id)->where('game_id',$request->game_id)->where('day_id',$request->day_id)->where('user_id',auth('api')->user()->id)->first();
                if(!empty($bitcheck)){
                    $bitcheck->amount = $bitcheck->amount+$request->amount;
                    $bitcheck->save();
                   $bits_id = $bitcheck->id;
                     $bits  =  $bitcheck;
                }else{
                    #get the requested data in Data variable
                    $data = [
                            'stores_id'     => $request->stores_id,
                            'game_id'       => $request->game_id ,
                            'date'          => now() ,
                            'type'          => $request->type ,
                            'amount'        => $request->amount ,
                            'user_id'       => auth('api')->user()->id ,
                            'day_id'        => $request->day_id  ,
                            'open_time'        => $request->open_time  ,
                           
                            ];
                    #store the newly creted resoures
                     $bits= $this->bit->create($data); 
                     $bits_id = $bits->id;
                }
                    $app = appDetail();
                $storess = $this->store->whereId($request->stores_id)->first();
                 foreach ($request->bit_place as $key => $bit_place) {
                       if ($bit_place < $app->min_bet_amount || $bit_place > $app->max_bet_amount) {
                            return $this->sendError(
                                'Error.',
                                "Bet amount must be Minimum - ₹{$app->min_bet_amount} and Maximum - ₹{$app->max_bet_amount}"
                            );
                        }
                      #get the requested data in Data variable
                          debitAmount(auth('api')->user()->id,$bit_place);
                    $check = $this->redJodiBit->where('created_at','like',currentDate().'%')->where('bit_place',$key)->where('user_id',auth('api')->user()->id)->where('bit_id', $bits->id)->first();
                    if(!empty($bit_place)){
                         if(!empty($check)){
                            $total = $check->amount + $bit_place;
                            $check->amount = $check->amount+$bit_place;
                            $check->save();

                            $remark =  'Played '.$storess->name.'Red Jodi '.$key.' of amount '.$total;
                            $paymentremark = PaymentRemark(auth('api')->user()->id,$remark,$bit_place, $check->payment_new_history_id);

                        }else{

                            $remark =  'Played '.$storess->name.'Red Jodi '.$key.' of amount '.$bit_place;
                            $paymentremark = PaymentRemark(auth('api')->user()->id,$remark,$bit_place);

                            $data = [
                                    'bit_id'          => $bits->id,
                                    'bit_place'       => $key,
                                    'amount'          => $bit_place , 
                                    'user_id'         => auth('api')->user()->id ,
                                    'payment_new_history_id' => $paymentremark->id,
                                   
                                    ];
                            #store the newly creted resoures
                             $redJodiBit = $this->redJodiBit->create($data);
                             PaymentRemarkBit($paymentremark->id,$bits->id);
                              
                             
                            
                          }
                          
                           
                               
                             
                    }
                       
                 

              }
                 DB::commit();
                $success['singleDigitBit'] =  $request->type;

            return $this->sendResponse($success, ' successfully.');
             }catch(\Exception $ex){
            DB::rollback();
             return $this->sendError('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)
    {
        //
    }

    /**
     * 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)
    {
        //
    }
}
