<?php

namespace App\Http\Controllers\AdminAPI\Wallet;

# Models
use App\Models\Payment;
use App\Models\PaymentHistory;
use App\Models\PaymentNewHistory;
use App\User;
use App\Models\GamePlace;
use App\Models\Withdraw;
use App\Models\DebitPayment;

# Other Classes
use DB;
use Carbon\Carbon;
use Validator;
use App\Traits\FirebaseTraits;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use Auth;

class PaymentController extends BaseController
{
        use FirebaseTraits;
    # Define Base view
    protected $view = 'admin.payment.';

     #Bind Payment model
    protected $payment;
     #Bind PaymentHistory model
    protected $paymentHistory;
    
         #Bind Withdraw model
    protected $withdraw;

       #Bind DebitPayment model
    protected $debitPayment;

    /**
      * Defining the default constructor for controller
      *
      */
    public function __construct(
                                 User $user,
                                Withdraw $withdraw,
                                Payment $payment,
                                PaymentHistory $paymentHistory,
                                 PaymentNewHistory $paymentNewHistory,
                                DebitPayment $debitPayment
                            )
    {
        $this->paymentNewHistory  = $paymentNewHistory;
        $this->payment            = $payment;
        $this->paymentHistory     = $paymentHistory;
        $this->debitPayment       = $debitPayment;
        $this->user               = $user;
        $this->withdraw           = $withdraw;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        
     
       
         try
        {
            
            
            $relation = ['username','paymenthistory'];
            #get all paymentUser resources
            $details['lists'] = $this->payment->with($relation)->paginate(10);
            $details['userlist'] = User::get();

           
            #render view
            return view($this->view.'index',$details);
        }catch(\Exception $ex)
        {
            return back()->with('error', $ex->getMessage());
        }
    }
    
      public function reportMoney(Request $request)
    {
        
       
         try
        {
            $relation = ['username'];

            /* Base Query */
            $query = $this->paymentNewHistory
                ->with($relation)
                ->where('type', 'add');
            
            /* 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->whereBetween('created_at', [$startDate, $endDate]);
            
            if ($request->filled('type')) {
                if ($request->type == 'manual') {
                    $query->where('remark', 'LIKE', '%admin%');
                } else {
                    $query->where('remark', 'LIKE', '%you%');
                }
            }
            
            /* Total Amount */
            $details['total_amount'] = (int)(clone $query)->sum('amount');
            $details['total_transactions'] = (int)(clone $query)->count();
            
            $details['admin_count'] = (int)(clone $query)
                ->where('remark', 'LIKE', '%admin%')
                ->count();
            
            $details['admin_amount'] = (int)(clone $query)
                ->where('remark', 'LIKE', '%admin%')
                ->sum('amount');
            
            $details['you_count'] = (int)(clone $query)
                ->where('remark', 'LIKE', '%you%')
                ->count();
            
            $details['you_amount'] = (int)(clone $query)
                ->where('remark', 'LIKE', '%you%')
                ->sum('amount');
            
            /* List Data */
            $details['lists'] = $query
                ->orderBy('id', 'DESC')
                ->paginate(15);
            $details['userlist'] = User::get();
                
                
           $details['user'] = User::where('type','!=','admin')->where('status',1)->get();

           
            #render view
            return $this->sendResponse($details, 'successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
    
     public function reportDeductMoney(Request $request)
        {
            // try {
        
                $relation = ['username'];
        
                $details['userlist'] = User::get();
        
                /*
                |--------------------------------------------------------------------------
                | Date Range
                |--------------------------------------------------------------------------
                */
        
                $dateRange = $request->date_range;
        
                // Default = This 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();
                }
        
                /*
                |--------------------------------------------------------------------------
                | Main Query
                |--------------------------------------------------------------------------
                */
        
                $query = $this->withdraw
                    ->with($relation)
                    ->where('amount', '>', 0)
                    ->whereBetween('created_at', [$startDate, $endDate]);
        
                /*
                |--------------------------------------------------------------------------
                | Report Lists
                |--------------------------------------------------------------------------
                */
        
                $details['lists'] = $query
                    ->orderBy('id', 'DESC')
                    ->paginate(15);
        
                /*
                |--------------------------------------------------------------------------
                | Summary Counts & Amounts
                |--------------------------------------------------------------------------
                */
        
                $summaryQuery = $this->withdraw
                    ->where('amount', '>', 0)
                    ->whereBetween('created_at', [$startDate, $endDate]);
        
                // Total
                $details['total_transactions'] = (int)(clone $summaryQuery)->count();
                $details['total_amount'] = (int)(clone $summaryQuery)->sum('amount');
        
                // Pending
                $details['pending_count'] = (int)(clone $summaryQuery)
                    ->where('withdraw_status_id', 1)
                    ->count();
        
                $details['pending_amount'] = (int)(clone $summaryQuery)
                    ->where('withdraw_status_id', 1)
                    ->sum('amount');
        
                // Successful
                $details['success_count'] = (int)(clone $summaryQuery)
                    ->where('withdraw_status_id', 2)
                    ->count();
        
                $details['success_amount'] = (int)(clone $summaryQuery)
                    ->where('withdraw_status_id', 2)
                    ->sum('amount');
        
                // Cancelled
                $details['cancelled_count'] = (int)(clone $summaryQuery)
                    ->where('withdraw_status_id', 3)
                    ->count();
        
                $details['cancelled_amount'] = (int)(clone $summaryQuery)
                    ->where('withdraw_status_id', 3)
                    ->sum('amount');
        
                /*
                |--------------------------------------------------------------------------
                | Users
                |--------------------------------------------------------------------------
                */
        
                $details['user'] = User::where('type', '!=', 'admin')
                    ->where('status', 1)
                    ->get();
        
                $details['date_range'] =
                    $startDate->format('m/d/Y') . ' - ' . $endDate->format('m/d/Y');
        
                return $this->sendResponse($details, 'successfully.');
        
            // } catch (\Exception $ex) {
        
            //     return $this->sendError($ex, 'Error');
            // }
        }
    
    public function reportBonus(Request $request)
    {
        
       
         try
        {
            $date = isset($request->date) ? $request->date : currentDate();
            $relation = ['username'];
            #get all paymentUser resources
            $query = $this->paymentNewHistory->with($relation)->where('created_at','like',$date.'%')->where('type','=','bonus');
            
            if(isset($request->type)){
                if($request->type == 'manual'){
                    $query = $query->where('remark','LIKE','%admin%');
                }else{
                    
                    $query = $query->where('remark','LIKE','%you%');
                }
            }
            
            $details['lists'] = $query->paginate(10);
            $details['userlist'] = User::get();

           
            #render view
            return $this->sendResponse($details, 'successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }
    
      public function reportWithdraw(Request $request)
    {
        
     
       
         try
        {
                $date = isset($request->date) ? $request->date : currentDate();
            
            $relation = ['username'];
            #get all paymentUser resources
            $details['lists'] = $this->withdraw->with($relation)->where('created_at','like',$date.'%')->where('withdraw_status_id',2)->paginate(10);
            
          
          
           
            #render view
            return $this->sendResponse($details, 'successfully.');
        }catch(\Exception $ex)
        {
            return $this->sendError($ex, 'Error');
        }
    }

    /**
     * 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{
             #validate the request
            
          
            $validator = Validator::make($request->all(), [
                'amount'          => 'required',
                'user_id'          => 'required',
            ]);
    
            if ($validator->fails()) {
                return $this->sendError($validator->messages(), 'Please Fill Mandatory field');
            }


            $paymentchecck = $this->payment->where('user_id',$request->user_id)->first();
            if(!empty($paymentchecck)){
                    $paymentchecck->amount = $paymentchecck->amount+$request->amount;
                    $paymentchecck->save();
                    $paymentid = $paymentchecck->id;
            }else{
                #get the requested data in Data variable
                  $data = [
                    'payment_id' =>1,
                    'amount'       => $request->amount,
                    'user_id'    => $request->user_id,
                    ];
                #store the newly creted resoures
               $paymentchecck = $this->payment->create($data);
                 $paymentid = $paymentchecck->id;
            }


            $data = [
                    'debit_amount'       => 0,
                    'credit_amount'       => $request->amount,
                    'user_id'    => $request->user_id,
                    'created_by'        =>Auth::user()->id,
                    ];
                #store the newly creted resoures
                $this->debitPayment->create($data);

            $paymentHistorychecck = $this->paymentHistory->where('user_id',$request->user_id)->first();
       
            if(!empty($paymentHistorychecck)){
                $remainamount =$paymentHistorychecck->remain_amount+$request->amount;
                    $paymentHistorychecck->total_amount = $paymentHistorychecck->total_amount+$request->amount;
                    $paymentHistorychecck->remain_amount =  $remainamount;
                    $paymentHistorychecck->save();
                   
            }else{
                #get the requested data in Data variable
                  $data = [
                    'total_amount'       => $request->amount,
                    'remain_amount'      => $request->amount,
                    'debit_total_amount' => 0,
                    'user_id'    => $request->user_id,
                    ];
                #store the newly creted resoures
                $this->paymentHistory->create($data);
                 $remainamount = $request->amount;
            }
            
               $data = [
                    'reamount' =>$remainamount ,
                        'remark' => $request->amount.' Points added by admin	',
                    'amount'       => $request->amount,
                    'payment_id'      => $paymentid,
                    'type'            => 'add',
                    'user_id'    => $request->user_id,
                    ];
                #store the newly creted resoures
                $this->paymentNewHistory->create($data);
                
                
                  $postcust = $this->user->whereId($request->user_id)->first();
                    $user_id = $request->user_id;
                    $name = $postcust->name;
                    $body = 'Dear '.$name .' '.$request->amount.' Points added by admin	';
                    $title = "Point Added";
                    $this->notificationUser($title,$body,$user_id);
                
            DB::commit();
            // #return redirect back to view
             toastr()->success('Payment Create Sucess fully ...');
            
        
        return $this->sendResponse(true, 'Add Point successfully.');
         }catch(\Exception $ex)
        {
            DB::rollback();
            toastr()->success($ex->getMessage());
            return $this->sendError($ex, 'Error');

        }
    }
    
     public function addBonus(Request $request)
    {
        
       
        DB::beginTransaction();
         try{
             #validate the request
            
          
            $validator = Validator::make($request->all(), [
                'amount'          => 'required',
                'user_id'          => 'required',
            ]);
    
            if ($validator->fails()) {
                return $this->sendError($validator->messages(), 'Please Fill Mandatory field');
            }


            $paymentchecck = $this->payment->where('user_id',$request->user_id)->first();
            if(!empty($paymentchecck)){
                    $paymentchecck->amount = $paymentchecck->amount+$request->amount;
                    $paymentchecck->save();
                    $paymentid = $paymentchecck->id;
            }else{
                #get the requested data in Data variable
                  $data = [
                    'payment_id' =>1,
                    'amount'       => $request->amount,
                    'user_id'    => $request->user_id,
                    ];
                #store the newly creted resoures
               $paymentchecck = $this->payment->create($data);
                 $paymentid = $paymentchecck->id;
            }


            $data = [
                    'debit_amount'       => 0,
                    'credit_amount'       => $request->amount,
                    'user_id'    => $request->user_id,
                    'created_by'        =>Auth::user()->id,
                    ];
                #store the newly creted resoures
                $this->debitPayment->create($data);

            $paymentHistorychecck = $this->paymentHistory->where('user_id',$request->user_id)->first();
       
            if(!empty($paymentHistorychecck)){
                $remainamount =$paymentHistorychecck->remain_amount+$request->amount;
                    $paymentHistorychecck->total_amount = $paymentHistorychecck->total_amount+$request->amount;
                    $paymentHistorychecck->remain_amount =  $remainamount;
                    $paymentHistorychecck->save();
                   
            }else{
                #get the requested data in Data variable
                  $data = [
                    'total_amount'       => $request->amount,
                    'remain_amount'      => $request->amount,
                    'debit_total_amount' => 0,
                    'user_id'    => $request->user_id,
                    ];
                #store the newly creted resoures
                $this->paymentHistory->create($data);
                 $remainamount = $request->amount;
            }
            
               $data = [
                    'reamount' =>$remainamount ,
                        'remark' => $request->amount.' Bonus added by admin	',
                    'amount'       => $request->amount,
                    'payment_id'      => $paymentid,
                    'type'            => 'bonus',
                    'user_id'    => $request->user_id,
                    ];
                #store the newly creted resoures
                $this->paymentNewHistory->create($data);
                
                
                  $postcust = $this->user->whereId($request->user_id)->first();
                    $user_id = $request->user_id;
                    $name = $postcust->name;
                    $body = 'Dear '.$name .' '.$request->amount.' Bonus added by admin	';
                    $title = "Bonus Added";
                    $this->notificationUser($title,$body,$user_id);
                
            DB::commit();
            // #return redirect back to view
             toastr()->success('Payment Create Sucess fully ...');
            
        
        return $this->sendResponse(true, 'Add Bonus successfully.');
         }catch(\Exception $ex)
        {
            DB::rollback();
            toastr()->success($ex->getMessage());
            return $this->sendError($ex, 'Error');

        }
    }
    
      /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function removePoint(Request $request)
    {
        DB::beginTransaction();
         try{
             #validate the request
            
             $validator = Validator::make($request->all(), [
                'amount'          => 'required',
                'user_id'          => 'required',
            ]);
    
            if ($validator->fails()) {
                return $this->sendError($validator->messages(), 'Please Fill Mandatory field');
            }
            $totalamount = totalAmount($request->user_id);
          
            if($request->amount>$totalamount){
                 toastr()->success('You have not sufficient balance');
                
                return $this->sendError('You have not sufficient balance', 'You have not sufficient balance');
            }else{
                debitAmount($request->user_id,$request->amount);
            }
            
              $data = [
                    'reamount' =>$totalamount- $request->amount ,
                        'remark' => $request->amount.' Points withdraw by admin	',
                    'amount'       => $request->amount,
                    'type'            => 'withdraw',
                    'user_id'    => $request->user_id,
                    ];
                #store the newly creted resoures
                $this->paymentNewHistory->create($data);
                
            DB::commit();
            // #return redirect back to view
             toastr()->success('Payment Debit Sucess fully ...');
             return $this->sendResponse(true, 'Remove Point successfully.');
            }catch(\Exception $ex)
           {
               DB::rollback();
               toastr()->success($ex->getMessage());
               return $this->sendError($ex, 'Error');
   
           }
    }

    /**
     * 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)
    {
        //
    }
}
