<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use App\User;
use App\Pin;
use Illuminate\Http\Request;
use Validator;
use App\Http\Requests\StoreUsersRequest;
use App\Http\Requests\UpdateUsersRequest;
use Yajra\Datatables\Datatables;
use Mail;
use Carbon\Carbon;

class PaymentsController extends Controller
{
    public function __construct() {
        $this->middleware(function($request, $next) {
            if(\Auth::user()->role_id != 1){
                return abort(404);
            }
            return $next($request);
        });
    }
    /**
     * Display a listing of User.
     *
     * @return \Illuminate\Http\Response
     */
     public function index()
     {
         $siteTitle = "Deals";
         return view('admin.deals.index', compact('users', 'siteTitle'));
     }



    public function generatePayout(){
        $paymentClosing = $this->getLastPaymentClosing();
        $totalAmountCredit = DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
                    ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
                    ->where([
                      ['ev_payouts.created_at', '<', $paymentClosing->end_date],
                      ['ev_payouts.closed_on', '=', NULL],
                      ['ev_payouts.closing_id', '=', 0],
                      ['ev_payouts.credit_debit', '=', 0],
                      ['users.active', '=', 1],
                    ])
                    ->sum('income_amount');
        $totalAmountDebit = DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
                    ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
                    ->where([
                      ['ev_payouts.created_at', '<', $paymentClosing->end_date],
                      ['ev_payouts.closed_on', '=', NULL],
                      ['ev_payouts.closing_id', '=', 0],
                      ['ev_payouts.credit_debit', '=', 1],
                      ['users.active', '=', 1],
                    ])
                    ->sum('income_amount');
        $totalAmount = $totalAmountCredit - $totalAmountDebit;
        $relations = [
            'ev_payouts' => DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
                    ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
                    ->where([
                      ['ev_payouts.created_at', '<', $paymentClosing->end_date],
                      ['ev_payouts.closed_on', '=', NULL],
                      ['ev_payouts.closing_id', '=', 0],
                      ['users.active', '=', 1],
                    ])
                    ->get(),
            'paymentClosing' => $paymentClosing,
            'payment_methods' => \Config::get('settings.payment_methods'),
            'date_now' => Carbon::now(),
            'totalAmountCredit' => $totalAmountCredit,
            'totalAmountDebit' => $totalAmountDebit,
            'totalAmount' => $totalAmount

        ];
        return view('admin.payments.generatePayout', $relations); 
    }
    
    public function generatePayoutStore(Request $request){
        $paymentClosing = $this->getLastPaymentClosing();
        if($request->payment_closing_id){
            $validator = Validator::make($request->all(), [
              'payment_closing_id' => 'required|exists:payment_closings,id',
            ]);
            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                $validatePaymentClosing = $this->validatePaymentClosing($paymentClosing);
                if($validatePaymentClosing->valid == false)
                {   
                    return Redirect::back()
                                ->with('errormessage', $validatePaymentClosing->message)
                                ->withInput();
                }
                elseif($validatePaymentClosing->valid == true)
                {
                  $totalAmountCredit = DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
                          ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
                          ->where([
                            ['ev_payouts.created_at', '<', $paymentClosing->end_date],
                            ['ev_payouts.closed_on', '=', NULL],
                            ['ev_payouts.closing_id', '=', 0],
                            ['ev_payouts.credit_debit', '=', 0],
                            ['users.active', '=', 1],
                          ])
                          ->sum('income_amount');
                  $totalAmountDebit = DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
                            ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
                            ->where([
                              ['ev_payouts.created_at', '<', $paymentClosing->end_date],
                              ['ev_payouts.closed_on', '=', NULL],
                              ['ev_payouts.closing_id', '=', 0],
                              ['ev_payouts.credit_debit', '=', 1],
                              ['users.active', '=', 1],
                            ])
                          ->sum('income_amount');
                  $totalAmount = $totalAmountCredit - $totalAmountDebit;
                  $ev_payouts = DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
                          ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
                          ->where([
                            ['ev_payouts.created_at', '<', $paymentClosing->end_date],
                            ['ev_payouts.closed_on', '=', NULL],
                            ['ev_payouts.closing_id', '=', 0],
                            ['users.active', '=', 1],
                          ])
                          ->get();
                  if($ev_payouts){
                    foreach($ev_payouts as $income){
                      $this->makePaymentAvailable($income, $paymentClosing);
                    }
                  }
                  $this->addNextPaymentClosing($paymentClosing);
                  $paymentClosing->update([
                    'completed_on' => Carbon::now(),
                    'total_amount' => $totalAmountCredit
                  ]);
                return Redirect::back()->with('message','Payment Closing Done successfully!');
                }
              }
            }
    }

    protected function validatePaymentClosing($paymentClosing){
        $validator = new \stdClass();
        $validator->valid = true;
        $validator->message = "";
        if($paymentClosing->completed_on != NULL){
          $validator->valid = false;
          $validator->message = "Closing is already done.";
        }
        if(Carbon::parse($paymentClosing->end_date) > Carbon::now()){
          $validator->valid = false;
          $daysRemaining = Carbon::parse($paymentClosing->end_date)->diffInDays(Carbon::now());
          $validator->message = "$daysRemaining days remaining.";
        }
        return $validator;
    }
    protected function makePaymentAvailable($income, $paymentClosing){
      \App\EvPayout::where('id', '=', $income->id)->update(['payment_status' => 1, 'closed_on'=>Carbon::now(), 'closing_id'=>$paymentClosing->id]);
      $user = \App\User::where('id', '=', $income->associate_id)->first();
      $wallet = \App\EvUsersWallet::where('user_id', '=', $user->id)->first();
      if(!isset($wallet->id)){
        $wallet = $this->createBlankWallet($user);
      }
      if($user->active==1){
        if($income->credit_debit == 0){
          $avbl_total_balance = $wallet->avbl_total_balance + $income->income_amount;
        }elseif($income->credit_debit == 1){
          $avbl_total_balance = $wallet->avbl_total_balance + $income->income_amount;
        }
        $wallet->update(['avbl_total_balance' => $avbl_total_balance]);
      }
    }
    
    protected function addNextPaymentClosing($paymentClosing){
      $nowDate = Carbon::parse($paymentClosing->end_date);
      if($nowDate->day <= 31 && $nowDate->day>15){
        $start_date = $nowDate->addMonths(1)->startOfMonth()->copy();
        $end_date = $nowDate->addDays(14)->copy();
        echo $start_date.'b';
      }else{
        $start_date = $nowDate->addDays(1)->copy();
        $end_date = $nowDate->endOfMonth()->copy();
      }
      $paymentClosing = \App\PaymentClosing::create([
          'start_date' => $start_date,
          'end_date' => $end_date,
          'completed_on' => NULL,
          'total_amount' => 0,
          'total_income' => 0,
          'total_credit' => 0,
          'total_debit' => 0,
          ]);
      return $paymentClosing;
    }

    protected function getGUIDnoHash($id, $deal_id){
      return 'BB-'.date('Y-m-d-').$deal_id.'-'.$id;
    }
    
    public function getLastPaymentClosing(){
      $paymentClosing = \App\PaymentClosing::where('end_date','<', Carbon::now())->orderBy('start_date', 'desc')->first();
      $paymentClosingEnd = \App\PaymentClosing::where('end_date', '>', Carbon::now())->orderBy('start_date', 'desc')->first();
      if(!isset($paymentClosing->id) && !isset($paymentClosingEnd->id)){
        $paymentClosing = $this->createBlankPaymentClosing();
      }elseif(!isset($paymentClosing->id) && isset($paymentClosingEnd->id)){
        $paymentClosing = $paymentClosingEnd;
      }
      return $paymentClosing;
    }
    
    protected function createBlankPaymentClosing(){
        $paymentClosing = \App\PaymentClosing::where('end_date','<', Carbon::now())->orderBy('start_date', 'desc')->first();
        if(!isset($paymentClosing->id)){
          if(date('d')<15){
            $start_date = Carbon::now()->startOfMonth();
            $end_date = Carbon::now()->startOfMonth()->addDays(15);
          }else{
            $start_date = Carbon::now()->startOfMonth()->addDays(15);
            $end_date = Carbon::now()->endOfMonth();
          }
        
        $paymentClosing = \App\PaymentClosing::create([
            'start_date' => $start_date,
            'end_date' => $end_date,
            'completed_on' => NULL,
            'total_amount' => 0,
            'total_income' => 0,
            'total_credit' => 0,
            'total_debit' => 0,
            ]);
      }
      return $paymentClosing;
    }
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $request
     * @return User
     */



    public function pendingPayouts()
    {
      return view('admin.payments.pendingpayouts');
    }


    public function processPayouts($id)
    {
      $income = \App\EvPayout::where('id', '=', $id)->first();
      $user = \App\User::where('id', '=', $income->associate_id)->first();
      $bin_user = \App\BinaryUser::where('user_id', '=', $user->id)->first();
      $wallet = \App\EvUsersWallet::where('user_id', '=', $user->id)->first();
      $totalPayouts = DB::table('ev_payouts')->select('ev_payouts.*')                    
                        ->where([                            
                          ['ev_payouts.payment_type_id', '=', 3],
                          ['ev_payouts.credit_debit', '=', 1],
                          ['ev_payouts.payment_status', '=', 1],
                          ['ev_payouts.associate_id', '=', $bin_user->id],
                        ])
                        ->orWhere([                            
                          ['ev_payouts.payment_type_id', '=', 3],
                          ['ev_payouts.credit_debit', '=', 1],
                          ['ev_payouts.payment_status', '=', 0],
                          ['ev_payouts.associate_id', '=', $bin_user->id],
                        ])
                        ->sum('income_amount');
        $relations = [
            'user' => $user,
            'income' => $income,
            'totalPayouts' => $totalPayouts,
            'bin_user' => $bin_user,
            'wallet' => $wallet
        ];
      return view('admin.payments.processpayouts', $relations);
    }

    public function doProcessPayouts($id, Request $request)
    {
        $income = \App\EvPayout::where('id', '=', $id)->first();
        $user = \App\User::where('id', '=', $income->associate_id)->first();
        $bin_user = \App\BinaryUser::where('user_id', '=', $user->id)->first();
        $wallet = \App\EvUsersWallet::where('user_id', '=', $user->id)->first();

        if($request->status){
            $validator = Validator::make($request->all(), [
              'status' => 'required|numeric',
              'remark' => 'required',
            ]);
            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                    if($request->status==1){

                      $income->update([
                                        'payment_status' => 1,
                                        'remark' => Carbon::now()." Admin: Processed Widthdrawal Request--\n".$request->remark."\n".$income->remark,
                                        'closed_on' => Carbon::now(),
                                      ]);
                        $new_withdrawal_amnt = $wallet->withdrawal_amnt+$income->income_amount;
                        $wallet->update([
                                  'withdrawal_amnt' => $new_withdrawal_amnt,
                                ]);

                    }elseif($request->status==2){
                      
                      $income->update([
                                        'payment_status' => 2,
                                        'remark' => Carbon::now()." Admin: Widthdrawal Request Cancelled--\n".$request->remark."\n".$income->remark,
                                        'closed_on' => Carbon::now(),
                                      ]);

                        
                        $new_available_amnt = $wallet->avbl_total_balance+$income->income_amount;
                        $wallet->update([
                                  'avbl_total_balance' => $new_available_amnt,
                                ]);

                    }
                    
                    return redirect()->route('admin.payments.pendingPayouts')->with('message','Widthdrawal processed successfully!');
            }
        }
    }

    public function processedPayouts()
    {
      return view('admin.payments.processedpayouts');
    }

    public function getPendingPayouts($limit=NULL){
                $query = DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
                    ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
                    ->where([
                      ['ev_payouts.credit_debit', '=', 1],
                      ['ev_payouts.payment_status', '=', 0],
                    ])
                    ->orderBy('created_at', 'desc');
                if($limit != NULL){
                    $query = $query->limit($limit);
                }
                $query = $query->get();
                $datatables = Datatables::of($query)->addColumn('action',
                     '<a class="btn btn-success btn-sm" href="{{url(\'/\')}}/admin/payments/processPayouts/{{ $id }}">'
                     .'  <span class="ladda-label">Process Payment</span>'
                     .'  <span class="ladda-spinner"></span>'
                     .'</a>');

                return $datatables->make(true);
    }

    public function getProcessedPayouts($limit=NULL){
        $query = DB::table('ev_payouts')->select('ev_payouts.*', 'users.full_name as full_name', 'users.username as username')
            ->join('users', 'users.id', '=', 'ev_payouts.associate_id')
            ->where([
              ['ev_payouts.credit_debit', '=', 1],
            ])
            ->orwhere([
              ['ev_payouts.payment_status', '=', 1],
              ['ev_payouts.payment_status', '=', 2],
            ])

            ->orderBy('created_at', 'desc');
        if($limit != NULL){
            $query = $query->limit($limit);
        }
        $query = $query->get();
        $datatables = Datatables::of($query);
        
        // ->addColumn('action',
        //      '@if($payment_status==1)<a class="btn btn-success btn-sm" href="{{url(\'/\')}}/admin/payments/refundIncome/{{ $id }}">'
        //      .'  <span class="ladda-label">Refund</span>'
        //      .'  <span class="ladda-spinner"></span>'
        //      .'</a>@endif');

        return $datatables->make(true);
    }

////Franchise Payout

    public function pendingPayoutsfrnchs()
    {
      return view('admin.payments.pendingpayoutsfrnchs');
    }


    public function processPayoutsfrnchs($id)
    {
      $income = \App\EvDealerPayout::where('id', '=', $id)->first();
      $user = \App\User::where('id', '=', $income->associate_id)->first();
      $bin_user = \App\BinaryUser::where('user_id', '=', $user->id)->first();
      $wallet = \App\EvUsersWallet::where('user_id', '=', $user->id)->first();
      $totalPayouts = DB::table('ev_frnchs_payouts')->select('ev_frnchs_payouts.*')                    
                        ->where([                            
                          ['ev_frnchs_payouts.payment_type_id', '=', 3],
                          ['ev_frnchs_payouts.credit_debit', '=', 1],
                          ['ev_frnchs_payouts.payment_status', '=', 1],
                          ['ev_frnchs_payouts.associate_id', '=', $bin_user->id],
                        ])
                        ->orWhere([                            
                          ['ev_frnchs_payouts.payment_type_id', '=', 3],
                          ['ev_frnchs_payouts.credit_debit', '=', 1],
                          ['ev_frnchs_payouts.payment_status', '=', 0],
                          ['ev_frnchs_payouts.associate_id', '=', $bin_user->id],
                        ])
                        ->sum('income_amount');
        $relations = [
            'user' => $user,
            'income' => $income,
            'totalPayouts' => $totalPayouts,
            'bin_user' => $bin_user,
            'wallet' => $wallet
        ];
      return view('admin.payments.processpayoutsfrnchs', $relations);
    }

    public function doProcessPayoutsfrnchs($id, Request $request)
    {
        $income = \App\EvDealerPayout::where('id', '=', $id)->first();
        $user = \App\User::where('id', '=', $income->associate_id)->first();
        $bin_user = \App\BinaryUser::where('user_id', '=', $user->id)->first();
        $wallet = \App\EvUsersWallet::where('user_id', '=', $user->id)->first();

        if($request->status){
            $validator = Validator::make($request->all(), [
              'status' => 'required|numeric',
              'remark' => 'required',
            ]);
            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                    if($request->status==1){

                      $income->update([
                                        'payment_status' => 1,
                                        'remark' => Carbon::now()." Admin: Processed Widthdrawal Request--\n".$request->remark."\n".$income->remark,
                                        'closed_on' => Carbon::now(),
                                      ]);
                        $new_withdrawal_amnt = $wallet->withdrawal_amnt_frnchs+$income->income_amount;
                        $wallet->update([
                                  'withdrawal_amnt_frnchs' => $new_withdrawal_amnt,
                                ]);

                    }elseif($request->status==2){
                      
                      $income->update([
                                        'payment_status' => 2,
                                        'remark' => Carbon::now()." Admin: Widthdrawal Request Cancelled--\n".$request->remark."\n".$income->remark,
                                        'closed_on' => Carbon::now(),
                                      ]);

                        
                        $new_available_amnt = $wallet->avbl_total_balance_frnchs+$income->income_amount;
                        $wallet->update([
                                  'avbl_total_balance_frnchs' => $new_available_amnt,
                                ]);

                    }
                    
                    return redirect()->route('admin.payments.pendingPayoutsfrnchs')->with('message','Widthdrawal processed successfully!');
            }
        }
    }

    public function processedPayoutsfrnchs()
    {
      return view('admin.payments.processedpayoutsfrnchs');
    }

    public function getPendingPayoutsfrnchs($limit=NULL){
                $query = DB::table('ev_frnchs_payouts')->select('ev_frnchs_payouts.*', 'users.full_name as full_name', 'users.username as username')
                    ->join('users', 'users.id', '=', 'ev_frnchs_payouts.associate_id')
                    ->where([
                      ['ev_frnchs_payouts.credit_debit', '=', 1],
                      ['ev_frnchs_payouts.payment_status', '=', 0],
                    ])
                    ->orderBy('created_at', 'desc');
                if($limit != NULL){
                    $query = $query->limit($limit);
                }
                $query = $query->get();
                $datatables = Datatables::of($query)->addColumn('action',
                     '<a class="btn btn-success btn-sm" href="{{url(\'/\')}}/admin/payments/processPayoutsfrnchs/{{ $id }}">'
                     .'  <span class="ladda-label">Process Payment</span>'
                     .'  <span class="ladda-spinner"></span>'
                     .'</a>');

                return $datatables->make(true);
    }

    public function getProcessedPayoutsfrnchs($limit=NULL){
        $query = DB::table('ev_frnchs_payouts')->select('ev_frnchs_payouts.*', 'users.full_name as full_name', 'users.username as username')
            ->join('users', 'users.id', '=', 'ev_frnchs_payouts.associate_id')
            ->where([
              ['ev_frnchs_payouts.credit_debit', '=', 1],
            ])
            ->orwhere([
              ['ev_frnchs_payouts.payment_status', '=', 1],
              ['ev_frnchs_payouts.payment_status', '=', 2],
            ])

            ->orderBy('created_at', 'desc');
        if($limit != NULL){
            $query = $query->limit($limit);
        }
        $query = $query->get();
        $datatables = Datatables::of($query);
        
        // ->addColumn('action',
        //      '@if($payment_status==1)<a class="btn btn-success btn-sm" href="{{url(\'/\')}}/admin/payments/refundIncome/{{ $id }}">'
        //      .'  <span class="ladda-label">Refund</span>'
        //      .'  <span class="ladda-spinner"></span>'
        //      .'</a>@endif');

        return $datatables->make(true);
    }
////End Franchise Payout
////Dealer Payout

    public function pendingPayoutsdealer()
    {
      return view('admin.payments.pendingpayoutsdealer');
    }


    public function processPayoutsdealer($id)
    {
      $income = \App\EvDealerPayout::where('id', '=', $id)->first();
      $user = \App\EvDealer::where('id', '=', $income->associate_id)->first();
      $totalPayouts = DB::table('ev_dealer_payouts')->select('ev_dealer_payouts.*')                    
                        ->where([                            
                          ['ev_dealer_payouts.payment_type_id', '=', 3],
                          ['ev_dealer_payouts.credit_debit', '=', 1],
                          ['ev_dealer_payouts.payment_status', '=', 1],
                          ['ev_dealer_payouts.associate_id', '=', $user->id],
                        ])
                        ->orWhere([                            
                          ['ev_dealer_payouts.payment_type_id', '=', 3],
                          ['ev_dealer_payouts.credit_debit', '=', 1],
                          ['ev_dealer_payouts.payment_status', '=', 0],
                          ['ev_dealer_payouts.associate_id', '=', $user->id],
                        ])
                        ->sum('income_amount');
        $relations = [
            'user' => $user,
            'income' => $income,
            'totalPayouts' => $totalPayouts,
        ];
      return view('admin.payments.processpayoutsdealer', $relations);
    }

    public function doProcessPayoutsdealer($id, Request $request)
    {
        $income = \App\EvDealerPayout::where('id', '=', $id)->first();
        $user = \App\EvDealer::where('id', '=', $income->associate_id)->first();

        if($request->status){
            $validator = Validator::make($request->all(), [
              'status' => 'required|numeric',
              'remark' => 'required',
            ]);
            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                    if($request->status==1){

                      $income->update([
                                        'payment_status' => 1,
                                        'remark' => Carbon::now()." Admin: Processed Widthdrawal Request--\n".$request->remark."\n".$income->remark,
                                        'closed_on' => Carbon::now(),
                                      ]);
                        $new_withdrawal_amnt = $user->withdrawal_amount+$income->income_amount;
                        $user->update([
                                  'withdrawal_amount' => $new_withdrawal_amnt,
                                ]);

                    }elseif($request->status==2){
                      
                      $income->update([
                                        'payment_status' => 2,
                                        'remark' => Carbon::now()." Admin: Widthdrawal Request Cancelled--\n".$request->remark."\n".$income->remark,
                                        'closed_on' => Carbon::now(),
                                      ]);

                        
                        $new_available_amnt = $user->available_amount+$income->income_amount;
                        $user->update([
                                  'available_amount' => $new_available_amnt,
                                ]);

                    }
                    
                    return redirect()->route('admin.payments.pendingPayoutsdealer')->with('message','Widthdrawal processed successfully!');
            }
        }
    }

    public function processedPayoutsdealer()
    {
      return view('admin.payments.processedpayoutsdealer');
    }

    public function getPendingPayoutsdealer($limit=NULL){
                $query = DB::table('ev_dealer_payouts')->select('ev_dealer_payouts.*', 'ev_dealers.full_name as full_name', 'ev_dealers.username as username')
                    ->join('ev_dealers', 'ev_dealers.id', '=', 'ev_dealer_payouts.associate_id')
                    ->where([
                      ['ev_dealer_payouts.credit_debit', '=', 1],
                      ['ev_dealer_payouts.payment_status', '=', 0],
                    ])
                    ->orderBy('created_at', 'desc');
                if($limit != NULL){
                    $query = $query->limit($limit);
                }
                $query = $query->get();
                $datatables = Datatables::of($query)->addColumn('action',
                     '<a class="btn btn-success btn-sm" href="{{url(\'/\')}}/admin/payments/processPayoutsdealer/{{ $id }}">'
                     .'  <span class="ladda-label">Process Payment</span>'
                     .'  <span class="ladda-spinner"></span>'
                     .'</a>');

                return $datatables->make(true);
    }

    public function getProcessedPayoutsdealer($limit=NULL){
        $query = DB::table('ev_dealer_payouts')->select('ev_dealer_payouts.*', 'ev_dealers.full_name as full_name', 'ev_dealers.username as username')
            ->join('ev_dealers', 'ev_dealers.id', '=', 'ev_dealer_payouts.associate_id')
            ->where([
              ['ev_dealer_payouts.credit_debit', '=', 1],
            ])
            ->orwhere([
              ['ev_dealer_payouts.payment_status', '=', 1],
              ['ev_dealer_payouts.payment_status', '=', 2],
            ])

            ->orderBy('created_at', 'desc');
        if($limit != NULL){
            $query = $query->limit($limit);
        }
        $query = $query->get();
        $datatables = Datatables::of($query);
        
        // ->addColumn('action',
        //      '@if($payment_status==1)<a class="btn btn-success btn-sm" href="{{url(\'/\')}}/admin/payments/refundIncome/{{ $id }}">'
        //      .'  <span class="ladda-label">Refund</span>'
        //      .'  <span class="ladda-spinner"></span>'
        //      .'</a>@endif');

        return $datatables->make(true);
    }
////End Dealer Payout


}
