<?php

namespace App\Http\Controllers\AdminAPI\Customer;

# Models
use App\User;
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;
use App\Models\Game;
use App\Models\Store;


# Other Classes
use DB;
use Excel;
use Carbon\Carbon;
use App\Traits\FirebaseTraits;
use Illuminate\Support\Arr;
use App\Traits\WinnerTrait;
use Illuminate\Http\Request;
use Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

use App\Http\Controllers\API\BaseController as BaseController;


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

    #Bind User model
    protected $user;
    
           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;

  #Bind Game model
  protected $game;

  #Bind Store model
  protected $store;
    
      /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
        RateType $rateType,
        WithdrawStatus               $withdrawStatus,
        Withdraw $withdraw,
        UserBanks $userBank,
        PaymentHistory $paymentHistory,
        PaymentNewHistory $paymentNewHistory,
    Store $store,
    Game $game,
        User $user,
        Bit $bit
        )
    {
        
        $this->user                 = $user;
        $this->withdrawStatus        = $withdrawStatus;
        $this->withdraw    = $withdraw;
        $this->userBank    = $userBank;
        $this->paymentHistory    = $paymentHistory;
        $this->paymentNewHistory    = $paymentNewHistory;
        $this->bit                 = $bit;
        $this->rateType            = $rateType;
    $this->game       = $game;
    $this->store      = $store;
        
    }
   /**
     * 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'];
            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']) ){

                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);
                 
                }
            }  
            $details['lists'] = $users->orderBy('id', 'DESC')->paginate($page);
          

            return $this->sendResponse($details, 'Admin Login successfully.');
         }catch(\Exception $ex)
        {
            toastr()->success($ex->getMessage());
            return $this->sendError($ex, 'Error');

        }
    }
    
  public function resetPassword(Request $request)
        {
            $validate = Validator::make($request->all(), [
                'current_password' => 'required',
                'password' => [
                    'required',
                    'string',
                    'confirmed',
                    'different:current_password',
                ],
                'password_confirmation' => 'required|string',
            ]);
        
            if ($validate->fails()) {
                return $this->sendError(
                    $validate->messages(),
                    'Please Fill Mandatory field'
                );
            }
        
            $user = Auth::user();
        
            // Check current password
            if (!Hash::check($request->current_password, $user->password)) {
        
                toastr()->error('Current Password is incorrect.');
        
                return $this->sendError(
                    'The provided current password is incorrect.',
                    'The provided current password is incorrect.'
                );
            }
        
            // Update password
            $user->password = Hash::make($request->password);
            $user->save();
        
            toastr()->success('Password has been updated successfully.');
        
            return $this->sendResponse(
                'success',
                'Admin Password Changed successfully.'
            );
        }
    
    
     public function customerDrop(Request $request)
    {
        
       
                    
                    
        try{
            $dateFilter = isset($request->date) ? $request->date : currentdate();
            $input = $request->all();
            #get all paymentUser resources
           
            if(isset($input['search_status'])){
                $page = (int)$input['search_status'];
            }else{
                $page = 10;
            }
            $users = $this->user->where('type','=','customer');
 
            if(isset($input['search_name']) || isset($input['search_mobile'])  || isset($input['status'])){

                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'].'%');
                }
                
                
            } 
            $details['lists'] = $users->orderBy('id', 'DESC')->get();
          

            return $this->sendResponse($details, 'Admin Login successfully.');
         }catch(\Exception $ex)
        {
            toastr()->success($ex->getMessage());
            return $this->sendError($ex, 'Error');

        }
    }
    
     public function fundReport(Request $request){
            
            //   try{
            
            
            $query = $this->paymentNewHistory->with('username');
            
            if(isset($request->transaction_type)){
                
                
                if($request->transaction_type == 'credit'){
                    $query = $query->whereIn('type',['add','win']);
                }else{
                    $query = $query->whereIn('type',['bit','withdraw']);
                }
                
                
                
            }
            
            
            /* 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 $this->sendResponse($details, 'Admin Login successfully.');
        //  }catch(\Exception $ex)
        // {
        //     return $this->sendError($ex, 'Error');
        // }
            
        }
    public function chatImage(Request $request)
    {
      
            #validate the request
            $validate = Validator::make($request->all(),
            [
                    'image'      => 'required|file',

            ]);

            if($validate->fails())
            {

                return $this->sendError($validate->messages(), 'Please Fill Mandatory field');
            }
            
            
      
                    
                    if(isset($request->image)){
                       $url = fileUpload('admin/home/chat',$request->file('image'));
                    }else{
                        $url = null;
                    }

           

            #return redirect back to view
            return $this->sendResponse($url, 'Result Get successfully.');
        
    }
    
       
    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 $this->sendResponse($details, 'Played get successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
    
    
      public function customersPlay(Request $request)
    {
       
         try
        {
            $details['types'] = [
                'singledigit',
                'pannafamily',
                'singlepanna',
                'doublepanna',
                'triplepanna',
                'singlepatti',
                'doublepatti',
                'triplepatti',
                'fullsangam',
                'halfsangam',
                'cyclepatti',
                'jodi',
                'jodifamily',
                'redjodi',
                'redjodifamily',
                'spmotor',
                'dpmotor'
            ];
            
            $details['users'] = $this->user->where('type','!=','admin')->get();
            $details['stores'] = $this->store->where('status',1)->get();
            
            
           $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 $this->sendResponse($details, 'Played get successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
    
    
    
      public function Transcation(Request $request,$id){
         try
        {
           
              $query = $this->paymentNewHistory
                    ->with([
                        'bit' => function ($q) {
                            $q->with(['game', 'store']);
                        },
                        'new_bit' => function ($q) {
                            $q->with(['game', 'store','timename']);
                        },
                        'win' => function ($q) {
                            $q->with(['Stores', 'GameName']);
                        },
                        'new_win' => function ($q) {
                            $q->with(['Stores', 'GameName','timename']);
                        },
                    ])
                    ->where('user_id', $id);
            
            if(isset($request->filter)){
                $query = $query->where('type',$request->filter);
            }
            
            $details['lists'] = $query->orderBy('id', 'DESC')->paginate(10);
            
            
            foreach($details['lists'] as $key => $value){
                if($value->type == 'bit' || $value->type == 'win'){
                    if($value->win){
                         $details['lists'][$key]->store = $value->win->stores->name;
                  $details['lists'][$key]->game = $value->win->GameName->name;
                  $details['lists'][$key]->time = null;
                    }else if($value->new_win){
                         $details['lists'][$key]->store = $value->new_win->stores->name;
                  $details['lists'][$key]->game = $value->new_win->GameName->name;
                  $details['lists'][$key]->time = $value->new_win->timename->opent_time;
                    }else if($value->bit){
                         $details['lists'][$key]->store = $value->bit->store->name;
                  $details['lists'][$key]->game = $value->bit->game->name;
                  $details['lists'][$key]->time = null;
                    }else if($value->new_bit){
                         $details['lists'][$key]->store = $value->new_bit->store->name;
                  $details['lists'][$key]->game = $value->new_bit->game->name;
                  $details['lists'][$key]->time = $value->new_bit->timename->opent_time;
                    }else{
                        $details['lists'][$key]->store = null;
                  $details['lists'][$key]->game = null;
                  $details['lists'][$key]->time = null;
                    }
                }else{
                  $details['lists'][$key]->store = null;
                  $details['lists'][$key]->game = null;
                  $details['lists'][$key]->time = null;
                }
            }
            
            
            
            
            
             $details['storess'] = $this->user->whereId($id)->first();
            
            #render view
            return $this->sendResponse($details, 'Transaction get successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
    

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
         try{
            $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
        {
        
          
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'mobile_number' => 'required|digits:10',
                'password' => 'required|same:confirm-password',
            ]);
    
            if ($validator->fails()) {
                return $this->sendError($validator->messages(), 'Please Fill Mandatory field');
            }
            
            
            $checkMobile = User::where(
                'mobile_number',
                $request->mobile_number
            )->exists();
            
            if ($checkMobile) {
                return $this->sendError(
                    'Mobile number already exists.',
                    'Mobile number already exists.'
                );
            }
        
            $input = $request->all();
            if(!empty($input['password'])){ 
               
            }else{
                $input = Arr::except($input,array('password'));    
            }

            $this->user->create($input);
        
           

               toastr()->success('Updated Successfully');
               return $this->sendResponse(true, 'Add successfully.');
            }catch(\Exception $ex)
           {
               toastr()->success($ex->getMessage());
               return $this->sendError($ex, 'Error');
   
           }
    }

    /**
     * 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 $this->sendResponse($details, 'Get successfully.');
            }catch(\Exception $ex)
           {
               toastr()->success($ex->getMessage());
               return $this->sendError($ex, 'Error');
   
           }
    }

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

            $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();
            
            
            $details['types'] = [
                'singledigit',
                'pannafamily',
                'singlepanna',
                'doublepanna',
                'triplepanna',
                'singlepatti',
                'doublepatti',
                'triplepatti',
                'fullsangam',
                'halfsangam',
                'cyclepatti',
                'jodi',
                'jodifamily',
                'redjodi',
                'redjodifamily',
                'spmotor',
                'dpmotor'
            ];
            
           $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 =  $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 $this->sendResponse($details, 'Add successfully.');
        //  }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
        {
        
            

            $validator = Validator::make($request->all(), [
                    'name' => 'required',
                    'mobile_number' => 'required|digits:10',
                    'password' => 'nullable|same:confirm-password',
                ]);
                
                if ($validator->fails()) {
                    return $this->sendError(
                        $validator->messages(),
                        'Please Fill Mandatory field'
                    );
                }
                
                // Handle unique mobile number manually
                $checkMobile = User::where('mobile_number', $request->mobile_number)
                    ->where('id', '!=', $id)
                    ->exists();
                
                if ($checkMobile) {
                
                    return $this->sendError(
                        'Mobile number already exists.',
                        'Mobile number already exists.'
                    );
                }
        
            $input = $request->all();
            if(!empty($input['password'])){ 
              
            }else{
                $input = Arr::except($input,array('password'));    
            }
            //   $input['password']        = Hash::make($input['password']);
            
            $user = User::find($id);
           
            $user->update($input);
        
           

               toastr()->success('Updated Successfully');
               return $this->sendResponse(true, 'Update successfully.');
            }catch(\Exception $ex)
           {
               toastr()->success($ex->getMessage());
               return $this->sendError($ex, 'Error');
   
           }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $caste = User::find($id);
        $caste ->delete();
         toastr()->success('You are successfully Deleted');
         return $this->sendResponse(true, 'Deleted successfully.');
    }
    
     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 $this->sendResponse(true, 'Update successfully.');
    }
}
