<?php


namespace App\Http\Controllers\API;

# Models
use App\Models\NewBit;
use App\Models\NewStore;
use App\Models\NewStoreGame;
use App\Models\NewHalfSangamBit;

# 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 NewHalfSangamController extends BaseController
{
      #Bind Bit model
      protected $bit;
    
      #Bind Store model
      protected $store;
            #Bind StoreGame model
      protected $storeGame;
  
       #Bind HalfSangamBit model
      protected $halfSangamBit;
  
  
      /**
        * Defining the default constructor for controller
        *
        */
      public function __construct(
                                  NewBit $bit,
                                  NewStore $store,
                                  NewStoreGame $storeGame,
                                  NewHalfSangamBit $halfSangamBit
                              )
      {
          $this->bit                  = $bit;
          $this->store                = $store;
          $this->storeGame            = $storeGame;
          $this->halfSangamBit        = $halfSangamBit;
          
      }
  
      /**
       * 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',
              'time_id' => 'required',
                  ]);
  
                  if($validator->fails()){
                      return $this->sendError('Validation Error.', $validator->errors());       
                  }
                       $time = '';
                  
                  $storess = $this->storeGame->where('id',$request->time_id)->first();
                 
                      $time = $storess->opent_time;
                      
                   $total_amount =0;
                    // Check if $request->amount_open is a valid JSON string
                        $amount_open = json_decode($request->amount_open, true); 
                        $amount_close = json_decode($request->amount_close, true); 
                        
                        
                    $total_open = array_sum(array_map('intval', $amount_open));
                    $total_close = array_sum(array_map('intval', $amount_close));
                    
                    $total_amount = $total_open + $total_close;
                    
                      if(timeComapre($time)){
                           return $this->sendError('Error.', "Time Out");   
                      }
                  
                        $totalamount = totalAmount(auth('api')->user()->id);
                        
              if($total_amount>$totalamount){
                  return $this->sendError('Error.', "You have not sufficient balance");    
              }
              
                        $openpanna = json_decode($request->openpanna, true); 
                        $singleclose = json_decode($request->singleclose, true); 
                        $closepanna = json_decode($request->closepanna, true); 
                        $singleopen = json_decode($request->singleopen, true); 
                        $amount_open = json_decode($request->amount_open, true); 
                        $amount_close = json_decode($request->amount_close, true); 
                        
                         foreach($openpanna as $openkey => $openvalue){
                        
                    $bitcheck = $this->bit->where('stores_id',$request->stores_id)->where('game_id',$request->game_id)->where('time_id',$request->time_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+$amount_open[$openkey];
                      $bitcheck->save();
                    $bit = $bitcheck;
                  }else{
                      #get the requested data in Data variable
                      $data = [
                              'stores_id'     => $request->stores_id,
                              'game_id'       => $request->game_id ,
                              'day_id'        => $request->day_id  ,
                              'open_time'     => $request->open_time  ,
                              'date'          => now() ,
                              'type'          => 'open' ,
                              'amount'        => $amount_open[$openkey] ,
                              'user_id'       => auth('api')->user()->id ,
                            'time_id'       => $request->time_id,
                             
                              ];
                      #store the newly creted resoures
                       $bit= $this->bit->create($data);
                  }
  
                 
                        #get the requested data in Data variable
                             $check = $this->halfSangamBit->where('bit_place_panna',$openvalue)->where('ptype','=','open')->where('bit_place_single',$singleclose[$openkey])->where('stype','=','close')->where('user_id',auth('api')->user()->id)->where('created_at','like',currentDate().'%')->first();
                          
                          if(!empty($check)){
                               $check->amount = $check->amount+$amount_open[$openkey];
                               $check->save();
                          }else{
                               $data = [
                                  'bit_id'                 => $bit->id,
                                  'bit_place_panna'        => $openvalue,
                                  'ptype'       => 'open', 
                                  'bit_place_single'       => $singleclose[$openkey],
                                  'stype'                  => 'close',
                                  'amount'                 => $amount_open[$openkey] , 
                                  'user_id'                => auth('api')->user()->id ,
                                 
                                  ];
                          #store the newly creted resoures
                            $halfSangamBit = $this->halfSangamBit->create($data); 
                          
                          }
                          
                           debitAmount(auth('api')->user()->id,$amount_open[$openkey]);
                           
                             
                               $storess = $this->store->whereId($request->stores_id)->first();
                              $remark =  'Played '.$storess->name.' Half sangam of open panna'.$openvalue.' single close '.$singleclose[$openkey].' of amount '.$amount_open[$openkey];
                              $paymentremark = PaymentRemark(auth('api')->user()->id,$remark,$amount_open[$openkey]);
                              PaymentRemarkBit($paymentremark->id,null,$bit->id);
                        
                       
                        
                        
                         }
                         foreach($closepanna as $closekey => $closevalue){
                             
                              $bitcheck = $this->bit->where('stores_id',$request->stores_id)->where('game_id',$request->game_id)->where('time_id',$request->time_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+$amount_close[$closekey];
                                      $bitcheck->save();
                                    $bit = $bitcheck;
                                  }else{
                                      #get the requested data in Data variable
                                      $data = [
                                              'stores_id'     => $request->stores_id,
                                              'game_id'       => $request->game_id ,
                                              'day_id'        => $request->day_id  ,
                                              'open_time'     => $request->open_time  ,
                                              'date'          => now() ,
                                              'type'          => 'open' ,
                                              'amount'        => $amount_close[$closekey] ,
                                              'user_id'       => auth('api')->user()->id ,
                                            'time_id'       => $request->time_id,
                                             
                                              ];
                                      #store the newly creted resoures
                                       $bit= $this->bit->create($data);
                                  }
                        
                             $check = $this->halfSangamBit->where('bit_place_panna',$closevalue)->where('ptype','=','close')->where('bit_place_single',$singleopen[$closekey])->where('stype','=','open')->where('user_id',auth('api')->user()->id)->where('created_at','like',currentDate().'%')->first();
                          
                          if(!empty($check)){
                               $check->amount = $check->amount+$amount_close[$closekey];
                               $check->save();
                          }else{
                               $data = [
                                  'bit_id'                 => $bit->id,   
                                  'bit_place_panna'        => $closevalue,
                                  'ptype'       => 'close', 
                                  'bit_place_single'       => $singleopen[$closekey],
                                  'stype'                  => 'open',
                                  'amount'                 => $amount_close[$closekey] , 
                                  'user_id'                => auth('api')->user()->id ,
                                 
                                  ];
                          #store the newly creted resoures
                             $halfSangamBit = $this->halfSangamBit->create($data); 
                          
                          }
                          
                           debitAmount(auth('api')->user()->id,$amount_close[$closekey]);
                           
                             
                               $storess = $this->store->whereId($request->stores_id)->first();
                              $remark =  'Played '.$storess->name.' Half sangam of close panna'.$closevalue.' single open '.$singleopen[$closekey].' of amount '.$amount_close[$closekey];
                              $paymentremark = PaymentRemark(auth('api')->user()->id,$remark,$amount_close[$closekey]);
                              PaymentRemarkBit($paymentremark->id,null,$bit->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)
      {
          //
      }
  }
  
