<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use App\User;
use App\YesPin;
use App\EvEvSolarModels;
use App\Http\Requests\StoreUsersRequest;
use App\Http\Requests\StoreBinUsersRequest;
use App\Http\Requests\UpdateUsersRequest;
use Yajra\Datatables\Datatables;
use Mail;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Validator;
use Image;


class UsersController extends Controller
{
    public function __construct() {
    }
    /**
     * Display a listing of User.
     *
     * @return \Illuminate\Http\Response
     */
     public function index()
     {
         $siteTitle = "Users";
         $users = Auth::user();
         $deal_types = \Config::get('settings.deal_types');$deal_types = \Config::get('settings.deal_types');
            $last_15_days = \App\YesIncome::where([
                ['created_at','>=',Carbon::now()->subdays(15)],
                ['payment_type', '=', 'matching'],
                ['associate_id', '=', $users->id]
                ])
                ->get();

         dd($last_15_days);

         return view('users.index', compact('users', 'siteTitle'));
     }

     public function getDirect()
     {
         $user = Auth::user();
         $users = User::where('sponsor_id', '=', $user->id);
         $siteTitle = "My DownLines";
         return view('users.getDirect', compact('users', 'siteTitle'));
     }

     public function getDownlines()
     {
         $user = Auth::user();
         $users = User::where('downlines', 'like', $user->id.'%');
         $siteTitle = "My DownLines";
         return view('users.getDownlines', compact('users', 'siteTitle'));
     }
     

     public function anyData()
     {
        $user = Auth::user();
         return Datatables::of(User::where('downlines', 'like', $user->downlines.'%'))
         ->addColumn('action',
         '<button class="btn btn-success btn-sm openModal" data-style="zoom-out" data-id="{{ $id }}">'
         .'  <span class="ladda-label">View Edit</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</button>')
         ->make(true);
     }

     public function getDownlinesAnyData(Request $request)
     {  
        $user = Auth::user();
        $user = User::where('id', '=', $user->id)->first();
        DB::statement(DB::raw('set @rownum=0'));
        $users = User::select([
            DB::raw('@rownum  := @rownum  + 1 AS rownum'),
            'users.id',
            'users.username',
            'users.full_name',
            'users.mobileno',
            'users.active',
            'users.email',
            'users.sponsor',
            'users.introducer',
            'users.created_at',
            'users.updated_at',
            'u2.full_name as u2full_name'])
        ->join('users as u2', 'users.sponsor_id', '=', 'u2.id')
        ->where('users.downlines', 'like', ''.$user->downlines.'%')
        ;
        
        $datatables = Datatables::of($users)->addColumn('action',
         '<button class="btn btn-success btn-sm openModal" data-style="zoom-out" data-id="{{ $id }}">'
         .'  <span class="ladda-label">View Edit</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</button>');

        // if ($keyword = $request->get('search')['value']) {
        //     $datatables->filterColumn('rownum', 'whereRaw', '@rownum  + 1 like ?', ["%{$keyword}%"]);
        // }
        return $datatables->make(true);
     }
     
     public function getDirectAnyData(Request $request)
     {  

        $user = Auth::user();
        DB::statement(DB::raw('set @rownum=0'));
        $users = User::select([
            DB::raw('@rownum  := @rownum  + 1 AS rownum'),
            'id',
            'username',
            'full_name',
            'mobileno',
            'active',
            'commission_rate',
            'email',
            'created_at',
            'updated_at'])->where('sponsor_id', '=', $user->id);
        
        $datatables = Datatables::of($users)->addColumn('action',
         '<button class="btn btn-success btn-sm openModal" data-style="zoom-out" data-id="{{ $id }}">'
         .'  <span class="ladda-label">View Edit</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</button>');

        // if ($keyword = $request->get('search')['value']) {
        //     $datatables->filterColumn('rownum', 'whereRaw', '@rownum  + 1 like ?', ["%{$keyword}%"]);
        // }
        return $datatables->make(true);
       }
     public function get_B_Downlines()
     {
         $user = Auth::user();
         $users = User::where('downlines', 'like', $user->id.'%');
         $siteTitle = "My DownLines";
         return view('users.get_b_Downlines', compact('users', 'siteTitle'));
     }
     
     public function get_B_Direct()
     {
         $user = Auth::user();
         $users = User::where('downlines', 'like', $user->id.'%');
         $siteTitle = "My DownLines";
         return view('users.get_b_Direct', compact('users', 'siteTitle'));
     }

     public function get_B_DirectAnyData(Request $request)
     {  

        $user = Auth::user();
        $bin_user = \App\BinaryUser::where('user_id', '=', $user->id)->first();
        DB::statement(DB::raw('set @rownum=0'));
        $users = \App\BinaryUser::select([
            DB::raw('@rownum  := @rownum  + 1 AS rownum'),
            'binary_users.id',
            'binary_users.username',
            'binary_users.full_name',
            'binary_users.active',
            'binary_users.sponsor',
            'binary_users.package_id',
            'binary_users.activated_at',
            'binary_users.created_at',
            'binary_users.updated_at',
            'binary_users.bin_tree',
            'u2.full_name as u2full_name',
            'u2.mobileno'
        ])
        ->join('users as u2', 'binary_users.user_id', '=', 'u2.id')
        ->where('binary_users.sponsor_id', '=', $user->id);
        
        $datatables = Datatables::of($users)->addColumn('action',
         '<button class="btn btn-success btn-sm openModal" data-style="zoom-out" data-id="{{ $id }}">'
         .'  <span class="ladda-label">View Edit</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</button>')
         ->addColumn('position',
         '@if(substr($bin_tree, strlen("'.$bin_user->bin_tree.'"), 1)=="l") Left @else Right @endif')
         ->editColumn('created_at', function ($user) {
                return $user->created_at; // no formatting, just returned $user->created_at; 
            });


        // if ($keyword = $request->get('search')['value']) {
        //     $datatables->filterColumn('rownum', 'whereRaw', '@rownum  + 1 like ?', ["%{$keyword}%"]);
        // }
        return $datatables->make(true);
       }


     public function get_B_DownlinesAnyData(Request $request)
     {  

        $user = Auth::user();
        $user = \App\BinaryUser::where('id', '=', $user->id)->first();
        $bin_user = \App\BinaryUser::where('user_id', '=', $user->id)->first();
        DB::statement(DB::raw('set @rownum=0'));
        $users = \App\BinaryUser::select([
            DB::raw('@rownum  := @rownum  + 1 AS rownum'),
            'binary_users.id',
            'binary_users.username',
            'binary_users.full_name',
            'binary_users.active',
            'binary_users.sponsor',
            'binary_users.package_id',
            'binary_users.activated_at',
            'binary_users.created_at',
            'binary_users.updated_at',
            'binary_users.bin_tree',
            'u2.full_name as u2full_name'])
        ->join('users as u2', 'binary_users.user_id', '=', 'u2.id')
        ->where([['binary_users.bin_tree', 'like', $bin_user->bin_tree.'%'], ['binary_users.id', '!=', $bin_user->id]])
        ;
        
        $datatables = Datatables::of($users)->addColumn('action',
         '<button class="btn btn-success btn-sm openModal" data-style="zoom-out" data-id="{{ $id }}">'
         .'  <span class="ladda-label">View Edit</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</button>')
         ->addColumn('position',
         '@if(substr($bin_tree, strlen("'.$bin_user->bin_tree.'"), 1)=="l") Left @else Right @endif')
         ->editColumn('created_at', function ($user) {
                return $user->created_at; // no formatting, just returned $user->created_at; 
            });

        // if ($keyword = $request->get('search')['value']) {
        //     $datatables->filterColumn('rownum', 'whereRaw', '@rownum  + 1 like ?', ["%{$keyword}%"]);
        // }
        return $datatables->make(true);
       }

    public function getSponsorsName($username){
        if(strlen($username)>=5){
            $username = str_replace('.json','',$username);
            $sponsors = DB::table('users')->select('username', 'full_name')
                          ->where('username', 'like', $username.'%')
                          ->orwhere('full_name', 'like', $username.'%')
                          ->get();
            $sponsors_array = array();
            foreach($sponsors as $sponsor){
                $sponsors_array[] = [ 'username' => $sponsor->username, 'full_name' => $sponsor->full_name ];
            }
            return response()->json($sponsors_array);
        }else{
            return response()->json([]);
        }
    }

    public function billSentReport($type="EV")
     {
         $user = Auth::user();

         $users = [];
         $siteTitle = "Bill Sent Report";
         if($type=="EV" || $type == "SOLAR"){
            $ev_ev_solar_model_ids = EvEvSolarModels::where('type', $type)->get();
        }else{
            dd("Invalid type");
        }
        
        $states = DB::table('states')->orderBy('name', 'asc')->get();
        $cities = \App\City::select(['cities.*'])->where('state_id', 23)->orderBy('name', 'asc')->get();
        
        return view('users.billSentReport', compact('users', 'siteTitle', 'ev_ev_solar_model_ids', 'type', 'states', 'cities'));
     
     }
    
    public function billSentReportOnly($type="EV")
     {
         $user = Auth::user();

         $users = [];
         $siteTitle = "Bill Sent Report";
        if($type=="EV" || $type == "SOLAR"){
            $ev_ev_solar_model_ids = EvEvSolarModels::get();
        }else{
            dd("Invalid type");
        }

        $states = DB::table('states')->orderBy('name', 'asc')->get();
        $cities = \App\City::select(['cities.*'])->where('state_id', 23)->orderBy('name', 'asc')->get();
        
        return view('users.billSentReportOnly', compact('users', 'siteTitle', 'ev_ev_solar_model_ids', 'type', 'states', 'cities'));
     
     }
     
     public function billSentReportAnyData(Request $request)
     {
        $user = Auth::user();
        $user_gen = \App\BinaryUser::where('user_id', '=', $user->id)->first();
        DB::statement(DB::raw('set @rownum=0'));
        $users = \App\EvUserActivation::select([
            DB::raw('@rownum  := @rownum  + 1 AS rownum'),
            'ev_user_activations.id',
            'u2.username',
            'ev_user_activations.amount',
            'ev_user_activations.user_comment',
            'ev_user_activations.admin_comment',
            'ev_user_activations.dealer_name',
            'ev_user_activations.kw_type',
            'ev_user_activations.kw',
            'u2.full_name',
            'u2.mobileno',
            'ev_user_activations.status',
            'u2.email',
            'ev_user_activations.updated_at'
        ])
        ->join('users as u2', 'u2.id', '=', 'ev_user_activations.user_id')
        ->where([['ev_user_activations.user_id', '=', $user_gen->id]])
        ->orderby('ev_user_activations.created_at', 'desc');
        
        $datatables = Datatables::of($users)->addColumn('action',
         '@if($status==0)<a class="btn btn-danger" href="{{ url("/")."/users/deleteBill/".$id }}">'
         .'Delete'
         .'</a>@endif');
        
        $datatables = $datatables
        // ->editColumn('img_path', '<a href="{{url(\'/\')}}'.'/uploads/proofs/{{$img_path}}" target="_blank"><img src="{{url(\'/\')}}'.'/uploads/proofs/{{$img_path}}" width="100"></a>'
        // )
        // ->rawColumns(['img_path', 'action'])
        ->editColumn('updated_at', '{{date(\'H:i:s d/m/Y\', strtotime($updated_at))}}');



        // if ($keyword = $request->get('search')['value']) {
        //     $datatables->filterColumn('rownum', 'whereRaw', '@rownum  + 1 like ?', ["%{$keyword}%"]);
        // }
        return $datatables->make(true);
    }

    public function upload_bill(Request $request){
        $user = Auth::user();
        if(isset($request->bill_amount)){

            $validator = Validator::make($request->all(), [
                'bill_amount' => 'required|numeric|min:5000',
                'imageFile' => 'required|image|mimes:jpeg,png,jpg,gif,JPEG,JPG|max:2048',
                'ev_ev_solar_model_id' => 'required|exists:ev_ev_solar_models,id',
                'state_id' => 'required|exists:states,id',
                'city_id' => 'required|exists:cities,id',
                'bill_comment' => ''
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
            $image = $request->file('imageFile');
            $file_name    = $image->getClientOriginalName();
            $image_resize = Image::make($image->getRealPath());
            $image_resize->resize(1024, 1024, function ($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize();
            });
            $file_name = $user->username.'_'.time().'.'.$image->getClientOriginalExtension();
            $image_resize->save(public_path('/uploads/proofs/' .$file_name));

                                    
            $bankDet = DB::table('users')->where('id', $user->id)->first();

            $ev_ev_solar_model = EvEvSolarModels::where('id', $request->ev_ev_solar_model_id)->first();
            $city = \App\City::where('id', $request->city_id)->first();

            $UserActivation = \App\EvUserActivation::create([
                                'user_id' => $user->id,
                                'level_type' => 1,
                                'to_user_id' => 1,
                                'amount' => $request->bill_amount,
                                'user_amount' => $request->bill_amount,
                                'city_id' => $city->id,
                                'city_name' => $city->name,
                                'status' => 0,
                                'paid_at' => date('Y-m-d G:i:s'),
                                'user_comment' => $request->bill_comment,
                                'admin_comment' => NULL,
                                'img_path' => $file_name,
                                'type' => 0,
                                'ev_ev_solar_model_id' => $request->ev_ev_solar_model_id,
                                'kw_type' => $ev_ev_solar_model->type,
                                'kw' => $ev_ev_solar_model->kw,
                                'bank_accnt_no'=>$bankDet->bank_accnt_no,
                                'bank_name'=>$bankDet->bank_name,
                                'branch_name'=>$bankDet->branch_name,
                                'accnt_type'=>$bankDet->accnt_type,
                                'ifsc'=>$bankDet->ifsc,
                                'name_bank_accnt'=>$bankDet->name_bank_accnt,
                              ]);
                return Redirect::to('/users/billSentReport')->with('message','Bill submitted successfully!');
            }
        }
    }

    public function deleteBill($id){
        $user = Auth::user();
        $userActivation = \App\EvUserActivation::where('id', $id)->first();
        if(isset($userActivation->id) && $userActivation->user_id==$user->id && false){
            @unlink(public_path('/uploads/proofs/' .$userActivation->img_path));
            \App\EvUserActivation::where('id', $id)->delete();
            return Redirect::to('/users/billSentReport')->with('message','Bill deleted successfully!');
        }else{
            return Redirect::to('/users/billSentReport')->with('errormessage','Not Allowed!');
        }
    }

    
    public function levelgeneology()
    {
        $user = Auth::user();
        $parent = DB::table('binary_users')->where('user_id', '=', $user->id)->first();
        $users = User::select([
            'id',
            'username',
            'full_name',
            'mobileno',
            'active',
            'commission_rate',
            'email',
            'created_at',
            'updated_at'])->where('sponsor_id', '=', $user->id)->get();
        return view('users.levelgeneology', [
            'users' => $users,
            ]);
    }
    
    public function levelgeneologyanydata($id)
    {
        $user = Auth::user();
        $parent = DB::table('binary_users')->where('user_id', '=', $user->id)->first();
        $users = User::select([
            'id',
            'username',
            'full_name',
            'mobileno',
            'active',
            'commission_rate',
            'email',
            'created_at',
            'updated_at'])
        ->where('sponsor_id', '=', $id)
        ->get();
        $content ='<ul>';
        foreach($users as $user){
        $content .='<li><span class="usrsname" onclick="initLevelGenealogyAjax('.$user->id.', $(this))" data-id="'.$user->id.'">'.$user->username.' ('.$user->full_name.')</span></li>';
        }
        $content .='</ul>';

        return $content;
    }

    public function geneology(\Illuminate\Http\Request $request, $username='')
    {
        $user = Auth::user();
        $username = (isset($request->username) && $request->username != '') ? $request->username : $username;
        $parent = DB::table('binary_users')->where('user_id', '=', $user->id)->first();
        if($username != '' )
        {
            $parent_search = DB::table('binary_users')
            ->where([
                ['username', '=', $username],
                ['bin_tree', 'like', $parent->bin_tree."%"]
                ])
            ->count();
            if($parent_search == 1)
            {
                $parent = DB::table('binary_users')
                ->where([
                    ['username', '=', $username],
                    ['bin_tree', 'like', $parent->bin_tree."%"]
                    ])
                ->first();
            }
        }


        $unord_childs = DB::table('binary_users')->where([['bin_tree', 'like', $parent->bin_tree."%"], ['id', '<>', $parent->id]])->get();
        $childs_left = DB::table('binary_users')->where([['bin_tree', 'like', $parent->bin_tree."l%"]])->get();
        $childs_right = DB::table('binary_users')->where([['bin_tree', 'like', $parent->bin_tree."r%"]])->get();
        $childs_today = DB::table('binary_users')->where([['bin_tree', 'like', $parent->bin_tree."%"]])->whereDate('created_at', '=', date('Y-m-d'))->get();
        $ord_childs = DB::table('binary_users')->where('parent_id', '=', $parent->id)->orderby('placement', 'ASC')->get();

        $treeHtml = $this->treeHtml3($parent->bin_tree);
        return view('users.geneology', [
            'childs' => $unord_childs,
            'childs_left' => $childs_left,
            'childs_right' => $childs_right,
            'user' => $user,
            'treeHtml' => $treeHtml,
            'curr_parent' => $parent->parent,
            'childs_today' => $childs_today,
            ]);
    }


    protected function treeElement($user, $key){
        if(isset($user[$key])){
        $package_income = \Config::get('settings.package_income');
        $childs_left = DB::table('binary_users')->where([['bin_tree', 'like', $user[$key]->bin_tree."l%"]])->count();
        $childs_right = DB::table('binary_users')->where([['bin_tree', 'like', $user[$key]->bin_tree."r%"]])->count();
        $evUserWallet = $this->getEvUserWallet($user[$key], true);
        $tot_curr_user = $user[$key]->curr_left_cnt + $user[$key]->curr_right_cnt;
        
        if($user[$key]->check_cap_dt!=date('Y').'-'.date('m').'-'.date('d')){
            if($tot_curr_user!=0){
                $user[$key]->curr_left_cnt = 0;
                $user[$key]->curr_right_cnt = 0;
            }
        }
        
        $style = $this->is_user_active($user[$key]) ? '<img src="'.url('/').'/assets/images/users/active.png">' : '<img src="'.url('/').'/assets/images/users/inactive.png">';
        //$style = $this->is_user_active($user[$key]) ? 'color: #18bc9c; text-shadow: 1px 1px 1px #11aa1c;' : 'color: #eb4444; text-shadow: 1px 1px 1px #ccc;';
        
        return '<li><a href="'.url('/').'/users/geneology/'.$user[$key]->username
        .'" data-html="true" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="'
        ."<table class='table table-bordered' style='margin-bottom:0px;'>"
        .'<tr>'
        ."<td>"
        .'Full Name'
        .'</td>'
        ."<td colspan='2'>"
        .$user[$key]->name
        .'</td>'
        .'</tr>'
        .'<tr>'
        ."<td>"
        .'Referral ID'
        .'</td>'
        ."<td colspan='2'>"
        .$user[$key]->sponsor
        .'</td>'
        .'</tr>'
        .'<tr>'
        ."<td>"
        .'Activation Date'
        .'</td>'
        ."<td colspan='2'>"
        .$user[$key]->activated_at
        .'</td>'
        .'</tr>'
        .'<tr>'
        ."<td>"
        .'Registration Status'
        .'</td>'
        ."<td>"
        .'Left: '.($childs_left - $user[$key]->left_cnt)
        .'</td>'
        ."<td>"
        .'Right: '.($childs_right - $user[$key]->right_cnt)
        .'</td>'
        .'</tr>'
        .'<tr>'
        ."<td>"
        .'Activation Status'
        .'</td>'
        ."<td>"
        .'Left: '.$user[$key]->left_cnt
        .'</td>'
        ."<td>"
        .'Right: '.$user[$key]->right_cnt
        .'</td>'
        .'</tr>'
        .'<tr>'
        ."<td>"
        .'Today Activation'
        .'</td>'
        ."<td>"
        .'Left: '.$user[$key]->curr_left_cnt
        .'</td>'
        ."<td>"
        .'Right: '.$user[$key]->curr_right_cnt
        .'</td>'
        .'</tr>'
        .'<tr>'
        ."<td>"
        .'Business Status'
        .'</td>'
        ."<td>"
        .'Left: '.(empty($evUserWallet->left_deal_count)?0:$evUserWallet->left_deal_count*11000)
        .'</td>'
        ."<td>"
        .'Right: '.(empty($evUserWallet->right_deal_count)?0:$evUserWallet->right_deal_count*11000)
        .'</td>'
        .'</tr>'
        .'</table>'
        .'">'
        .$style.'<br/>'
        .ucwords(strtolower($user[$key]->name)).' <br>'.$user[$key]->username .''.'</a>';
    }else{
        return '<li><a href="#"><img src="'.url('/').'/assets/images/users/vacant.png"><br/>vacant'.'</a>';
    }

    }

    protected function treeHtml3($user_bin){
            $childrens_raw = DB::table('binary_users')
                            ->join('users', 'users.id', '=', 'binary_users.user_id')
                            ->select('binary_users.*', 'users.full_name AS name')
                            ->where([['bin_tree', 'like', $user_bin."%"]])->get();

            $childrens = array();
                foreach($childrens_raw as $child){
                    $childrens[$child->bin_tree] = $child;
                }
        $html = '<ul>'.$this->treeElement($childrens, $user_bin).'
                    <ul>'.$this->treeElement($childrens, $user_bin.'l').'
                        <ul>'.$this->treeElement($childrens, $user_bin.'ll').'
                            <ul>'.$this->treeElement($childrens, $user_bin.'lll').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'llll').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'lllr').'</li>
                                //</ul>'.
                            '</li>
                            '.$this->treeElement($childrens, $user_bin.'llr').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'llrl').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'llrr').'</li>
                                //</ul>'.
                            '</li></ul>
                        </li>'.$this->treeElement($childrens, $user_bin.'lr').'
                            <ul>'.$this->treeElement($childrens, $user_bin.'lrl').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'lrll').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'lrlr').'</li>
                                //</ul>'.
                            '</li>
                            '.$this->treeElement($childrens, $user_bin.'lrr').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'lrrl').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'lrrr').'</li>
                                //</ul>'.
                            '</li></ul>
                        </li></ul>
                    </li>'.$this->treeElement($childrens, $user_bin.'r').'
                        <ul>'.$this->treeElement($childrens, $user_bin.'rl').'
                            <ul>'.$this->treeElement($childrens, $user_bin.'rll').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'rlll').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'rllr').'</li>
                                //</ul>'.
                            '</li>
                            '.$this->treeElement($childrens, $user_bin.'rlr').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'rlrl').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'rlrr').'</li>
                                //</ul>'.
                            '</li></ul>
                        </li>'.$this->treeElement($childrens, $user_bin.'rr').'
                            <ul>'.$this->treeElement($childrens, $user_bin.'rrl').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'rrll').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'rrlr').'</li>
                                //</ul>'.
                            '</li>
                            '.$this->treeElement($childrens, $user_bin.'rrr').
                                //'<ul>
                                //'.$this->treeElement($childrens, $user_bin.'rrrl').'</li>
                                //'.$this->treeElement($childrens, $user_bin.'rrrr').'</li>
                                //</ul>'.
                            '</li></ul>
                        </li></ul>
                    </li>
                </li></ul>';

            return $html;    
        }

    /**
     * Show the form for editing User.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $relations = [
            'roles' => \App\Role::get()->pluck('title', 'id')->prepend('Please select', ''),
        ];

        $user = User::findOrFail($id);

        return view('users.edit', compact('user') + $relations);
    }

    /**
     * Update User in storage.
     *
     * @param  \App\Http\Requests\UpdateUsersRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateUsersRequest $request, $id)
    {
        $user = User::findOrFail($id);
        $user->update($request->all());

        return redirect()->route('users.index');
    }

    /**
     * Display User.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $relations = [
            'roles' => \App\Role::get()->pluck('title', 'id')->prepend('Please select', ''),
        ];

        $user = User::findOrFail($id);

        return view('users.show', compact('user') + $relations);
    }

    public function tdsReport(){
        $SITE_TDS = \Config::get('settings.SITE_TDS');
        $relations['SITE_TDS'] = $SITE_TDS;
        return view('users.tdsReport', $relations);
    }
    
    public function paidTDSReportanyData(Request $request)
    {
        $user = Auth::user();
        $id = $user->id;

        $where = array();
        $where[] = ['yes_tds_transactions.associate_id','=', $id];
        // if(isset($request->from_date) && !is_null($request->from_date) && isset($request->to_date) && !is_null($request->to_date)){
        //  $where[] = ['yes_tds_transactions.created_at','>=', $request->from_date];
        //  $where[] = ['yes_tds_transactions.created_at','<=', $request->to_date];   
        // }
         return Datatables::of(
                \App\YesTdsTransaction::select('yes_tds_transactions.*', 'users.username', 'users.active', 'users.plan_id', 'users.full_name', 'users.panno')
                ->join('users', 'users.id', '=', 'yes_tds_transactions.associate_id')
                ->where($where)
                )
         ->addColumn('package',function(\App\YesTdsTransaction $user) {
            $package_income = \Config::get('settings.package_income');
            return (isset($package_income[$user->plan_id]['name']))?$package_income[$user->plan_id]['name']:'Undefined';
        })
        ->addColumn('total_admin_chrg', function(\App\YesTdsTransaction $YesIncome) {
                    return round($YesIncome->income_amount/2,2);
        })
        ->addColumn('income_amount', function(\App\YesTdsTransaction $YesIncome) {
                    return round($YesIncome->income_amount/2,2);
        })
        ->editColumn('created_at', function(\App\YesTdsTransaction $YesIncome) {
                    return date('Y-m-d H:i:s', strtotime($YesIncome->created_at));
        })
        //  ->addColumn('action',
        //  '<button class="btn btn-danger btn-sm mark_paid" data-style="zoom-out" data-id="{{ $associate_id }}" onclick="mark_tds_paid($(this), {{ $associate_id }})" data-active="1">'
        //  .'  <span class="ladda-label">Mark Paid</span>'
        //  .'  <span class="ladda-spinner"></span>'
        //  .'</button>'
        // )
         ->make(true);
    }

    public function getTdsReport(){
        $user = Auth::user();
        $id = $user->id;
        $SITE_TDS = \Config::get('settings.SITE_TDS');
        $bin_user = \App\BinaryUser::where('user_id', '=', $user->id)->first();

        $query = \App\BinaryIncomePayout::select(
                     'binary_income_payouts.*',
                     'binary_users.full_name as full_name',
                     'binary_users.username as username',
                     'weekly_payment_closings.start_date',
                     'weekly_payment_closings.end_date')
                    ->join('binary_users', 'binary_users.id', '=', 'binary_income_payouts.associate_id')
                    ->join('weekly_payment_closings', 'weekly_payment_closings.id', '=', 'binary_income_payouts.closing_id')
                    ->where([
                      ['binary_income_payouts.associate_id', '=', $bin_user->id],
                      ['binary_income_payouts.payment_status', '=', 1],
                    ])
                    ->orderBy('created_at', 'desc');

        $query = $query->get();
         
         return Datatables::of($query)
         ->addColumn('start_end', '{{date("d M Y", strtotime($start_date))}}'.'-'.'{{date("d M Y", strtotime($end_date))}}')
         ->addColumn('action',
         '<a class="btn btn-success btn-sm" data-style="zoom-out" href="{{ url("/")}}/users/processPayouts/{{ $id }}">'
         .'  <span class="ladda-label">View Details</span>'
         .'  <span class="ladda-spinner"></span>'
         .'</a>')
         ->make(true);
    }

public function kyc(){
        $user = Auth::user();
        $user = DB::table('users')->where('id', '=', $user['id'])->first();  
         return view('users.kyc', compact('user'));
     }
     
     public function updateKyc(Request $request){
        $user = Auth::user();
        $user = DB::table('users')->where('id', '=', $user['id'])->first();
        if($request->updateKyc){
            if($request->panno != $user->panno){
                $valid_panno = 'max:15';
            }else{
                $valid_panno = 'max:15';
            }

            $validator = Validator::make($request->all(), [
                'name_bank_accnt' => 'required',
                'bank_name' => 'required|min:1|max:255',
                'bank_accnt_no' => 'required|min:4|max:255',
                'branch_name' => 'required:max:255',
                'accnt_type' => 'required|max:255',
                'panno' => $valid_panno,
                'nom_name' => 'max:255',
                'nom_relation' => 'max:255',
                'nom_dob' => 'max:255',
                'ifsc' => 'required|min:4|max:255',
                'pass_file' => 'image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
                'pan_file' => 'image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{

                    $validatKycUserMobPan = $this->validatKycUserMobPan($request);
                            
                    if($validatKycUserMobPan->valid == false)
                    {   
                        return Redirect::back()
                                    ->with('errormessage', $validatKycUserMobPan->message)
                                    ->withInput();
                    }
                    elseif($validatKycUserMobPan->valid == true)
                    {

                        $updateArr = [];
                        if($user->name_bank_accnt==''){ $updateArr['name_bank_accnt'] = $request->name_bank_accnt; }
                        if($user->bank_name==''){ $updateArr['bank_name'] = $request->bank_name; }
                        if($user->bank_accnt_no==''){ $updateArr['bank_accnt_no'] = $request->bank_accnt_no;}
                        if($user->branch_name==''){ $updateArr['branch_name'] = $request->branch_name;}
                        if($user->accnt_type==''){ $updateArr['accnt_type'] = $request->accnt_type;}
                        if($user->panno==''){ $updateArr['panno'] = $request->panno;}
                        if($user->state==''){ $updateArr['state'] = $request->state; $updateArr['state_name'] = DB::table('states')->where('id', '=', $request->state)->first()->name; }
                        if($user->city==''){ $updateArr['city'] = $request->city;  $updateArr['city_name'] = DB::table('cities')->where('id', '=', $request->city)->first()->name; }
                        if($user->nom_name==''){ $updateArr['nom_name'] = $request->nom_name;}
                        if($user->nom_relation==''){ $updateArr['nom_relation'] = $request->nom_relation;}
                        if($user->nom_dob==''){ $updateArr['nom_dob'] = $request->nom_dob;}
                        if($user->ifsc==''){ $updateArr['ifsc'] = $request->ifsc;}

                    if ($request->hasFile('pan_file') && $user->pan_file=='') {
                        $pan_file = $request->file('pan_file');
                        $name = $user->id.'_pan'.'.'.$pan_file->getClientOriginalExtension();
                        $destinationPath = public_path('/storage/userimages/');
                        $pan_file->move($destinationPath, $name);
                        if($user->pan_file==''){ $updateArr['pan_file'] = $name;}
                      }
                      
                      if ($request->hasFile('pass_file') && $user->pass_file=='') {
                        $pass_file = $request->file('pass_file');
                        $name = $user->id.'_pass'.'.'.$pass_file->getClientOriginalExtension();
                        $destinationPath = public_path('/storage/userimages/');
                        $pass_file->move($destinationPath, $name);
                        if($user->pass_file==''){ $updateArr['pass_file'] = $name;}
                      }
                    
                    $user = User::where('id', '=', $user->id)->update($updateArr);
                    return Redirect::back()->with('message','KYC submitted successfully!');
                }
            }
        }
     }
    protected function validatKycUserMobPan($request){
        $validator = new \stdClass();
        $validator->valid = true;
        $validator->message = "";
        

        $panCnt = User::where([
            ['panno', '=',$request->panno],
            ['id', '!=', Auth::user()->id],
        ])->count();
        //$panCnt = User::where('mobileno', $request->mobileno)->count();

        if($panCnt > 0){
            $validator->valid = false;
            $validator->message = 'This PAN no. is already in use.';
        }
        return $validator;
    }

    public function urequests(){
        $user = Auth::user();
        $user = DB::table('users')->where('id', '=', $user['id'])->first();  
        return view('users.urequests', compact('user'));
     }
     
     public function sendUrequests(Request $request){
        $user = Auth::user();
        if($request->subject){

            $validator = Validator::make($request->all(), [
                'subject' => 'required|min:1|max:255',
                'message' => 'required|min:4|max:255',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                $prev_message = Carbon::now()."($user->username) :: $request->message\n\n";
                $ureq = \App\Urequest::insert([
                    'subject' => $request->subject,
                    'curr_message' => $request->message,
                    'past_message' => $prev_message,
                    'user_id' => $user->id,
                    'from_username' => $user->username,
                    'status' => 0,
                    'user_read' => 0,
                    'admin_read' => 1,
                    ]);
                return Redirect::back()->with('message','Request submitted successfully!');
            }
        }
     }
     
     public function getUrequest($limit=null){
        $user = Auth::user();
        $query = DB::table('urequests')->select('urequests.*')
            ->where(['user_id'=>$user->id])
            ->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(\'/\')}}/users/urequestsreply/{{ $id }}">'
                 .'  <span class="ladda-label">Reply</span>'
                 .'  <span class="ladda-spinner"></span>'
                 .'</a>');

        return $datatables->make(true);

     }
    
    public function urequestsreply($id){
        $user = Auth::user();
        $ureq = \App\Urequest::where(['id'=>$id],['user_id'=>$user->id])->first();
        $ureq->update([
                        'user_read' => 0,
                    ]);
        return view('users.urequestsReply', compact('user', 'ureq'));
    }
    public function sendUreqreply(Request $request){
        $user = Auth::user();
        if($request->message){

            $validator = Validator::make($request->all(), [
                'message' => 'required|min:4|max:255',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                $ureq = \App\Urequest::where(['id'=>$request->id])->first();
                $prev_message = Carbon::now()."($ureq->from_username) :: $ureq->curr_message\n\n". $ureq->past_message;
                $ureq->update([
                    'curr_message' => $request->message,
                    'past_message' => $prev_message,
                    'user_read' => 0,
                    'admin_read' => 1,
                    ]);
                return Redirect::back()->with('message','Request submitted successfully!');
            }
        }
    }
     
     public function complaints(){
        $user = Auth::user();
        $user = DB::table('users')->where('id', '=', $user['id'])->first();  
        return view('users.complaints', compact('user'));
     }
     
     public function sendUcomplaints(Request $request){
        $user = Auth::user();
        if($request->subject){

            $validator = Validator::make($request->all(), [
                'subject' => 'required|min:1|max:255',
                'message' => 'required|min:4|max:255',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                        $prev_message = Carbon::now()."($user->username) :: $request->message\n\n";
                        $ureq = \App\Complaint::insert([
                            'subject' => $request->subject,
                            'curr_message' => $request->message,
                            'past_message' => $prev_message,
                            'user_id' => $user->id,
                            'from_username' => $user->username,
                            'status' => 0,
                            'user_read' => 0,
                            'admin_read' => 1,
                            ]);
                    return Redirect::back()->with('message','Complaint submitted successfully!');
            }
        }
     }
     
     public function getComplaint($limit=null){
        $user = Auth::user();
        $query = DB::table('complaints')->select('complaints.*')
            ->where(['user_id'=>$user->id])
            ->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(\'/\')}}/users/complaintsreply/{{ $id }}">'
                 .'  <span class="ladda-label">Reply</span>'
                 .'  <span class="ladda-spinner"></span>'
                 .'</a>');

        return $datatables->make(true);

     }
    
    public function complaintsreply($id){
        $user = Auth::user();
        $ureq = \App\Complaint::where(['id'=>$id],['user_id'=>$user->id])->first();
        $ureq->update([
                        'user_read' => 0,
                        ]);
        return view('users.complaintsReply', compact('user', 'ureq'));
    }
    public function sendcomplaintreply(Request $request){
        $user = Auth::user();
        if($request->message){

            $validator = Validator::make($request->all(), [
                'message' => 'required|min:4|max:255',
            ]);

            if ($validator->fails()) {
                return Redirect::back()
                            ->withErrors($validator)
                            ->withInput();
            }else{
                        $ureq = \App\Complaint::where(['id'=>$request->id])->first();
                        $prev_message = Carbon::now()."($ureq->from_username) :: $ureq->curr_message\n\n". $ureq->past_message;
                        $ureq->update([
                            'curr_message' => $request->message,
                            'past_message' => $prev_message,
                            'user_read' => 0,
                            'admin_read' => 1,
                            ]);
                    return Redirect::back()->with('message','Complaints submitted successfully!');
            }
        }
    }


}
