<?php

namespace App\Http\Controllers\API;

# Models
use App\Models\Bit;
use App\Models\Store;
use App\Models\StoreGame;
use App\Models\TriplePattiBit;
use App\Models\TriplePattiPannaBit;

# 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 TripplePattiController extends BaseController
{

     #Bind Bit model
    protected $bit;
    
    #Bind Store model
    protected $store;

     #Bind TriplePattiBit model
    protected $triplePattiBit;

     #Bind TriplePattiPannaBit model
    protected $triplePattiPannaBit;


    /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                Bit $bit,
                                Store $store,
                                 StoreGame $storeGame,
                                 TriplePattiPannaBit $triplePattiPannaBit,
                                TriplePattiBit $triplePattiBit
                            )
    {
        $this->bit  = $bit;
        $this->store                = $store;
         $this->storeGame                = $storeGame;
        $this->triplePattiBit       = $triplePattiBit;
        $this->triplePattiPannaBit       = $triplePattiPannaBit;
        
    }
    /**
     * 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',
                'pati_name' => 'required',
                'bit_place' => 'required',
                // 'total_amount' => 'required',
            ]);

            if($validator->fails()){
                return $this->sendError('Validation Error.', $validator->errors());       
            }
            $time = '';
                
                $storess = $this->storeGame->where('stores_id',$request->stores_id)->first();
                if($request->type=='OPEN'){
                    $time = $storess->opent_time;
                    
                }else{
                      $time = $storess->close_time;
                }
                    if(timeComapre($time)){
                         return $this->sendError('Error.', "Time Out");   
                    }
                 $totalamount = totalAmount(auth('api')->user()->id);
           $bittotalamout =0;
             
           $bittotalamout = $request->amount;
            
             
            if($bittotalamout>$totalamount){
                return $this->sendError('Error.', "You have not sufficient balance");    
            }else{
                
            }
            //  foreach($request->stores_id as $key=>$storesid){
            $bitcheck = $this->bit->where('stores_id',$request->stores_id)->where('game_id',$request->game_id)->where('user_id',auth('api')->user()->id)->where('type',$request->type)->where('created_at','like',currentDate().'%')->first();
                if(!empty($bitcheck)){
                    $bitcheck->amount = $bitcheck->amount+$request->amount;
                    $bitcheck->save();
                   $bits_id = $bitcheck->id;
                }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;
                }
                //  foreach ($request->pati_name as $key => $pati_name) {
                       #get the requested data in Data variable
             debitAmount(auth('api')->user()->id, $request->amount);
                       $storess = $this->store->whereId($request->stores_id)->first();
                    $check = $this->triplePattiBit->where('created_at','like',currentDate().'%')->where('bit_id',$bits_id)->where('bit_place',$request->pati_name)->first();
                    if(!empty($check)){
                        $total = $check->amount + $request->amount;
                       $triplePattiBitid = $check;
                       $check->amount = $total;
                       $check->save();


                          $remark =  'Played '.$storess->name.' '.$request->type.' panna tp '. $request->pati_name.' of amount '. $total;
                             PaymentRemark(auth('api')->user()->id,$remark, $request->amount, $check->payment_new_history_id);
                        $payment_new_history_id = $check->payment_new_history_id;


                    }else{

                        $remark =  'Played '.$storess->name.' '.$request->type.' panna tp '. $request->pati_name.' of amount '. $request->amount;
                            $paymentremark = PaymentRemark(auth('api')->user()->id,$remark, $request->amount);
                        #get the requested data in Data variable
                        $data = [
                                'bit_id'          => $bits_id,
                                'bit_place'       => $request->pati_name, 
                                'amount'          => $request->amount, 
                                'user_id'         => auth('api')->user()->id ,
                                'payment_new_history_id' => $paymentremark->id,
                               
                                ];

                        #store the newly creted resoures
                         $triplePattiBitid= $this->triplePattiBit->create($data);
                            PaymentRemarkBit($paymentremark->id,$bits_id);
                         $payment_new_history_id = $paymentremark->id;
                    }
                    
                    
                    
                    $app = appDetail();
                    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}"
                            );
                        }
                     
                     $checkpannapatti = $this->triplePattiPannaBit->where('triple_patti_bit_id',$triplePattiBitid->id)->where('bit_place',$key)->where('created_at','like',currentDate().'%')->first();
                     
                        if(!empty($checkpannapatti)){
                            $total = $checkpannapatti->amount + $bit_place;
                            $checkpannapatti->amount = $total;
                            $checkpannapatti->save();
                        }else{
                            $pannapatti = [
                                'user_id' => auth('api')->user()->id,
                                'bit_place' => $key,
                                'amount' => $bit_place,
                                'triple_patti_bit_id'   => $triplePattiBitid->id,
                                'bit_id'        => $bits_id,
                                'payment_new_history_id' => $payment_new_history_id,
                                ];
                                $this->triplePattiPannaBit->create($pannapatti);
                                
                        }
                        
                    }
             
             
             
                  
                              
                            
                           
                 
                 DB::commit();
                $success['singleDigitBit'] =  $request->type;

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