<?php

namespace App\Http\Controllers\Admin;

# Models
use App\Models\Users;
use App\Models\UserRefer;
use App\Models\Bit;
use App\Models\RateType;
use App\Models\PaymentNewHistory;
use App\Models\UserBanks;
use App\Models\PaymentHistory;
use App\Models\Withdraw;
use App\Models\WithdrawStatus;
# Other Classes
use DB;
use Excel;
use Hash;
use Auth;
use Carbon\Carbon;
use Validator;
use App\Traits\FirebaseTraits;
use Illuminate\Support\Arr;
use App\Traits\WinnerTrait;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class CustomerController extends Controller
{
     # Define Base view
    protected $view = 'admin.customer.';

    #Bind Users model
    protected $user;
    
    #Bind UserRefer model
    protected $userRefer;
    
           use FirebaseTraits;
    
    #Bind Withdraw model
    protected $withdraw;
    
    #Bind PaymentHistory model
    protected $paymentHistory;
    
    #Bind UserBanks model
    protected $userBank;
    
    #Bind RateType model
    protected $rateType;
    
    #Bind Bit model
    protected $bit;
    
    #Bind PaymentNewHistory model
    protected $paymentNewHistory;

    #Bind WithdrawStatus model
    protected $withdrawStatus;
    
      /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
        RateType $rateType,
        WithdrawStatus               $withdrawStatus,
        Withdraw $withdraw,
        UserBanks $userBank,
        PaymentHistory $paymentHistory,
        PaymentNewHistory $paymentNewHistory,
        Users $user,
        UserRefer $userRefer,
        Bit $bit
        )
    {
        
        $this->user                 = $user;
        $this->userRefer                 = $userRefer;
        $this->withdrawStatus        = $withdrawStatus;
        $this->withdraw    = $withdraw;
        $this->userBank    = $userBank;
        $this->paymentHistory    = $paymentHistory;
        $this->paymentNewHistory    = $paymentNewHistory;
        $this->bit                 = $bit;
        $this->rateType            = $rateType;
        
    }
   /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
               
                    
        try{
            $date = isset($request->date) ? $request->date : currentDate();
            $input = $request->all();
            #get all paymentUser resources
            $realtion = ['paymentHistory','bit','headUser.refer'];
            if(isset($input['search_status'])){
                $page = (int)$input['search_status'];
            }else{
                $page = 10;
            }
            $users = $this->user->with($realtion)->where('type','=','customer');
 
            if(isset($input['search_name']) || isset($input['search_mobile']) || isset($input['status']) || isset($input['play'])|| isset($input['register'])  || isset($input['agent_id'])){

                if(isset($input['search_name'])){

                 $users->where('name','LIKE','%'.$input['search_name'].'%');
                }
                 if(isset($input['search_mobile'])){

                 $users->where('mobile_number','LIKE','%'.$input['search_mobile'].'%');
                }
                if(isset($input['status'])){
                        $status = $input['status'];
                        
                 $users->where('status',$input['status']);
                 
                }
                if(isset($input['play'])){
                        $play = $input['play'];
                        
                 $users->whereHas('bit',function ($q) use ($date){
                     $q->whereDate('created_at', '=', $date);
                 });
                 
                }
                if(isset($input['register'])){
                        
                 $users->whereDate('created_at', '=', $date);
                 
                }
                
                if (isset($input['agent_id'])) {
                    $refer_id = $input['agent_id'];
                    $users->whereHas('headUser', function ($q) use ($refer_id){
                        $q->where('reffered_by',$refer_id);
                    });
                }
            }  
            $details['lists'] = $users->orderBy('id', 'DESC')->paginate($page);
          

           return view($this->view.'index',$details);
         }catch(\Exception $ex)
        {
            toastr()->success($ex->getMessage());
            return back()->with('error', $ex->getMessage());
        }
    }
    
       
    public function customerPlay(Request $request,$id)
    {
         
         try
        {
            $input = $request->all();
            $realtion = ['username','game','store'];
            $details['lists'] = $this->bit->where('created_at','like',currentDate().'%')->with($realtion)->where('user_id',$id)->paginate(150);
            
             $details['storess'] = $this->user->whereId($id)->first();
             $details['totalamount'] = $this->bit->where('created_at','like',currentDate().'%')->where('user_id',$id)->sum('amount');
            #render view
            return view($this->view.'playedgame',$details);
        }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    
    
      public function customersPlay(Request $request)
    {
       
         try{
            
           $date = isset($request->date) ? $request->date : currentDate();
            $bitKeys = [
                'singledigit',
                'pannafamily',
                'singlepanna',
                'doublepanna',
                'triplepanna',
                'singlepatti',
                'doublepatti',
                'triplepatti',
                'fullsangam',
                'halfsangam',
                'cyclepatti',
                'jodi',
                'jodifamily',
                'redjodi',
                'redjodifamily',
                'spmotor',
                'dpmotor'
            ];
            
            $withRelations = [];
            
            foreach ($bitKeys as $k) {
                $withRelations[] = $k . '.bit.store';
                $withRelations[] = $k . '.bit.game';
            }
            
            
            $withRelations = array_unique($withRelations);
            
            $query = $this->paymentNewHistory
                ->where('created_at', 'like', $date . '%')
                ->where('type', 'bit')
                ->with(array_merge(['username', 'userwin'], $withRelations));
                
                if(isset($request->game_id)){
                    $game_id = $request->game_id;
                    $query = $query->whereHas($game_id);
                }
                if(isset($request->stores_id)){
                    $store_id = $request->stores_id;
                    $query = $query->whereHas('bit',function($q) use($store_id){
                        $q->where('stores_id',$store_id);
                    });
                }
                
                if(isset($request->min_amount)){
                    $query = $query->where('amount', '>=' ,$request->min_amount);
                }
                
                if(isset($request->user_id)){
                    $query = $query->where('user_id',$request->user_id);
                }
            
            $details['lists'] = $query->orderBy('id','DESC')
                ->paginate(20);
                
                
            
            $details['lists']->getCollection()->transform(function ($item) use ($bitKeys) {
            
                $item->bit_details = null;
            
                foreach ($bitKeys as $key) {
                    if ($item->$key) {
                        
                        
                            $item->bit_details = $item->$key;
                        
                       
                        break;
                    }
                }
            
                foreach ($bitKeys as $key) {
                    unset($item->$key);
                }
            
                return $item;
            });
            #render view
            return view($this->view.'allcustomer',$details);
        }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    
    
    
      public function Transcation(Request $request,$id){
         try
        {
           
            $input = $request->all();
            $details['lists'] = $this->paymentNewHistory->where('user_id',$id)->orderBy('id', 'DESC')->paginate(10);
            
             $details['storess'] = $this->user->whereId($id)->first();
            
            #render view
            return view($this->view.'transcation',$details);
        }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
         try{
            $details['users'] = $this->user->where('type','agent')->where('status',1)->get();
            $details['ratetype'] = $this->rateType->where('status',1)->get();

            #render view
            return view($this->view.'create',$details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
         try
        {
        
            $this->validate($request, [
                'name' => 'required',
                'mobile_number' => 'required|digits:10|unique:users,mobile_number',
                'password' => 'same:confirm-password',
            ]);
        
            $input = $request->all();
            if(!empty($input['password'])){ 
               
            }else{
                $input = Arr::except($input,array('password'));    
            }

            $user = $this->user->create($input);
        
        
        if(isset($request->refer_id)){
            $refer = [
                'user_id' => $user->id,
                'reffered_by'   => $request->refer_id,
                ];
                
                $this->userRefer->create($refer);
            
            $paymentHistorydata = [
                                'total_amount'       => 0,
                                'remain_amount'      => 0,
                                'debit_total_amount' => 0,
                                'user_id'    => $user->id,
                                ];
                            #store the newly creted resoures
                            PaymentHistory::create($paymentHistorydata);
        }
           

               toastr()->success('Updated Successfully');
            return redirect('/admin/customer');
        }catch(\Exception $ex)
        {
            toastr()->success($ex->getMessage());
            return back()->with('error', $ex->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
         try{
            $details['detail'] = $this->user->whereId($id)->first();
            $details['ratetype'] = $this->rateType->where('status',1)->get();

            #render view
            return view($this->view.'view',$details);
         }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request,$id)
    {
        //   try{
        
        $relation = ['headUser'];
            $details['users'] = $this->user->where('type','agent')->where('status',1)->get();
            $details['detail'] = $this->user->with($relation)->whereId($id)->first();
            $details['ratetype'] = $this->rateType->where('status', 1)->get();
            
            
            $details['bank_account'] = $this->userBank->where('user_id',$id)->first();
            $details['ratetype'] = $this->rateType->where('status',1)->get();
            $details['total_deposit'] = $this->paymentNewHistory->where('user_id',$id)->where('type', '=', 'add')->sum('amount');
            $details['total_withdraw'] = $this->withdraw->where('user_id',$id)->where('withdraw_status_id', 2)->sum('amount');
            
            $realtion = ['withdrawStatus'];
            
            $withdraws = $this->withdraw->with($realtion)->where('user_id',$id);
            
            if(isset($request->withdraw_status_id)){
                $withdraws = $withdraws->where('withdraw_status_id', $request->withdraw_status_id);
            }

            $details['withdraw_lists'] = $withdraws->orderBy('id', 'DESC')->paginate(10, ['*'], 'withdraw_page');
            
            
            $details['withdraw'] = $this->withdrawStatus->where('id', '<>', 1)->where('status', 1)->get();
            
            $details['wallet_balance'] = $this->paymentHistory->where('user_id',$id)->orderBy('id','DESC')->first();
            
            // $details['bid_lists'] = $this->bit->where('created_at','like',currentDate().'%')->with($bidrealtion)->where('user_id',$id)->get();
            
            
           $bitKeys = [
                'singledigit',
                'pannafamily',
                'singlepanna',
                'doublepanna',
                'triplepanna',
                'singlepatti',
                'doublepatti',
                'triplepatti',
                'fullsangam',
                'halfsangam',
                'cyclepatti',
                'jodi',
                'jodifamily',
                'redjodi',
                'redjodifamily',
                'spmotor',
                'dpmotor'
            ];
            
            $withRelations = [];
            
            foreach ($bitKeys as $k) {
                $withRelations[] = $k . '.bit.store';
                $withRelations[] = $k . '.bit.game';
            }
            
            $withRelations = array_unique($withRelations);
            
            $query = $this->paymentNewHistory
                ->where('type', 'bit')
                ->where('user_id', $id)
                ->with(array_merge(['username', 'userwin'], $withRelations));
            
            if (!empty($request->game_id) && in_array($request->game_id, $bitKeys)) {
                $query->whereHas($request->game_id);
            }
            
            $details['bid_lists'] = $query->paginate(10);
            
            $details['bid_lists']->getCollection()->transform(function ($item) use ($bitKeys) {
            
                $item->bit_details = null;
            
                foreach ($bitKeys as $key) {
                    if (!empty($item->$key)) {
                        $item->bit_details = $item->$key;
                        break;
                    }
                }
            
                foreach ($bitKeys as $key) {
                    unset($item->$key);
                }
            
                return $item;
            });
                
            
            
            $transactions = $this->paymentNewHistory->where('user_id',$id);
            
             if(isset($request->transaction_type)){
                
                
                if($request->transaction_type == 'credit'){
                    $transactions = $transactions->whereIn('type',['add','win']);
                }else{
                    $transactions = $transactions->whereIn('type',['bit','withdraw']);
                }
                
            }
            
            $details['transaction_lists'] = $transactions->orderBy('id', 'DESC')->paginate(10, ['*'], 'transaction_page');

            #render view
            return view($this->view.'edit',$details);
        //  }catch(\Exception $ex)
        // {
        //     return back()->with('error', $ex->getMessage());
        // }
    }


        public function fundReport(Request $request){
            
            //   try{
            
            
            $query = $this->paymentNewHistory;
            
            if(isset($request->transaction_type)){
                
                
                if($request->transaction_type == 'credit'){
                    $query = $query->whereIn('type',['add','win']);
                }else{
                    $query = $query->whereIn('type',['bit','withdraw']);
                }
                
                
                
            }
            
            if(isset($request->admin)){
                
                    $query = $query->where('remark','LIKE','%'.'admin'.'%');
                
            }
            
            
            /* Filters */
            $dateRange = $request->date_range;

            // Default = current month
            if (empty($dateRange)) {
            
                $startDate = Carbon::now()->startOfMonth();
                $endDate   = Carbon::now()->endOfMonth();
            
            } else {
            
                [$start, $end] = explode(' - ', $dateRange);
            
                $startDate = Carbon::createFromFormat('m/d/Y', $start)->startOfDay();
                $endDate   = Carbon::createFromFormat('m/d/Y', $end)->endOfDay();
            }
            
             $query = $query->whereBetween('created_at', [$startDate, $endDate]);


                 $details['lists'] = $query->orderBy('id', 'DESC')->paginate(10);

            #render view
            return view($this->view.'fund_report',$details);
        //  }catch(\Exception $ex)
        // {
        //     return back()->with('error', $ex->getMessage());
        // }
            
        }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
       try
        {
        
            $this->validate($request, [
                'name' => 'required',
                'mobile_number' => 'required|digits:10|unique:users,mobile_number,'.$id,
                'password' => 'same:confirm-password',
            ]);
        
            $input = $request->all();
            $input = Arr::except($request->all(), ['_token', '_method','password_confirmation']);
            if(!empty($input['password'])){ 
              
            }else{
                $input = Arr::except($input,array('password'));    
            }
            
            //   $input['password']        = Hash::make($input['password']);
            
            $user = $this->user->find($id);
           
            $user->update($input);
        
        
        if(isset($request->refer_id)){
             $checkRefer = $this->userRefer->where('user_id',$id)->first();
                if($checkRefer){
                    if($checkRefer->reffered_by != $request->refer_id){
                            $this->userRefer->whereId($checkRefer->id)->update([
                                'reffered_by'       => $request->refer_id,
                                ]);
                    }
                }else{
                    $refer = [
                            'user_id' => $id,
                            'reffered_by'   => $request->refer_id,
                            ];
                            
                            $this->userRefer->create($refer);
                }
        }
           
           

               toastr()->success('Updated Successfully');
            return redirect('/admin/customer');
        }catch(\Exception $ex)
        {
            toastr()->success($ex->getMessage());
            return back()->with('error', $ex->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $caste = $this->user->find($id);
        $caste ->delete();
         toastr()->success('You are successfully Deleted');
       return redirect('admin/customer');
    }
    
     public function changeStatus(Request $request,$id)
    {

        #get the detail of requested resources
        $users = $this->user->whereId($request->id)->first();

        if($users->status == 1){
             $status = '0';
           
        }else{
              $status = '1';
        }        
        #get the status in data variable
        $data = ['status' => $status];

        #update status
        $this->user->whereId($request->id)->update($data);
          $users = $this->user->whereId($request->id)->first();
          $message = $users->status ==0 ? 'InActive' : 'Active';
       toastr()->success('You are successfully '.$message);
       return redirect('admin/customer');
    }
}
