<?php

namespace App\Http\Controllers\API;

# Models
use App\Models\Bit;
use App\Models\Store;
use App\Models\StoreGame;
use App\Models\KPPattiBit;
use App\Models\KPPattiPannaBit;

# 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 KPPattiController extends BaseController
{
     #Bind Bit model
    protected $bit;
    
         #Bind Store model
    protected $store;

     #Bind KPPattiBit model
    protected $kpPattiBit;

         #Bind KPPattiPannaBit model
    protected $kpPattiPannaBit;


    /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                Bit $bit,
                                Store $store,
                                StoreGame $storeGame,
                                KPPattiBit $kpPattiBit,
                                KPPattiPannaBit $kpPattiPannaBit
                            )
    {
        $this->bit  = $bit;
        $this->store                = $store;
        $this->kpPattiBit       = $kpPattiBit;
         $this->storeGame                = $storeGame;
        $this->kpPattiPannaBit       = $kpPattiPannaBit;
    }
    /**
     * 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;
                }
                
                
                        debitAmount(auth('api')->user()->id, $request->amount);
               $storess = $this->store->whereId($request->stores_id)->first();
                    $check = $this->kpPattiBit->where('bit_id',$bits_id)->where('bit_place',$request->pati_name)->where('created_at','like',currentDate().'%')->first();
                    if(!empty($check)){

                        $total = $check->amount + $request->amount;
                       $kpPattiBitid = $check;
                       $check->amount = $total;
                       $check->save();

                       $remark =  'Played '.$storess->name.' '.$request->type.' panna kp '. $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 kp '. $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
                         $kpPattiBitid= $this->kpPattiBit->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->kpPattiPannaBit->where('kp_patti_bit_id',$kpPattiBitid->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,
                                'kp_patti_bit_id'   => $kpPattiBitid->id,
                                'bit_id'        => $bits_id,
                                'payment_new_history_id' => $payment_new_history_id,
                                ];
                                $this->kpPattiPannaBit->create($pannapatti);
                                
                        }
                        
                    }
                    
                          
                              
                            
                          
          
                         
                     
                 
                 
                 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)
    {
        //
    }
}
