<?php

namespace App\Http\Controllers\LocationAdmin;

use App\Http\Controllers\Controller;
use App\Models;
use Auth;
use App\Http\Requests\addEmployee;
use Illuminate\Http\Request;
use App\Models\CompanyLocation;
use App\Models\CompanyAdmin;
use App\Models\Company;
use App\Models\CompanyProfileImage;
use App\Models\User;
use App\Models\UserProfile;
use App\Models\CompanyEmployeeLocation;
use App\Models\RoleUser;
use App\Models\CompanyEmployee;
use App\Models\CompanyLocationAdmin;
use App\Models\CompanyFinding;
use App\Models\Challenge;
use App\Models\ChallengeEmployeeAnswer;
use App\Models\UserCreditPoint;
use App\Models\EmployeeMessage;
use App\Models\EmployeeMessageThread;
use App\Models\EmployeePointRedemption;
use App\Models\GiftCard;
use DB;
use Session;
use Validator;
use Exception;
use Mail;
use App\Services\DefaultServices;
use Illuminate\Support\Str;
use View;
use Hash;
use Yajra\Datatables\Datatables;

class EmployeeController extends Controller {

    protected $defaultServices;
    protected $messageType;
    protected $userRoleType;    

    public function __construct(DefaultServices $defaultServices)
    {
        $this->defaultServices = $defaultServices;
        $this->messageType = (new EmployeeMessage)->messageType;
        $this->userRoleType = (new EmployeeMessage)->userRoleType;
    }

    public function index(Request $request)
    {
        $userDetails    = Auth::guard('locationAdmin')->user();
        $locationAdmin = CompanyLocationAdmin::where('user_id',$userDetails->id)->get();
        $loc_arr = [];
        foreach($locationAdmin as $key=>$locAdmin){
            $company_id = $locAdmin->company_id;
            $loc_arr[$key] = $locAdmin->location_id ;
        }
       if($request->ajax()) {
       //dd('hi');
            $is_active = $request->checkstatus;
            $filters   = [];

            if($is_active != '') {
                $filters['is_active'] = $is_active;
            }

            $filters['is_delete'] = 0;

            $allData = User::leftJoin('user_profiles', function ($join) {
                            $join->on('users.id', '=', 'user_profiles.user_id');
                        })  
                        ->leftJoin('role_users', function ($join) {
                            $join->on('users.id', '=', 'role_users.user_id');
                        })  
                        ->leftJoin('company_employees', function ($join) {
                            $join->on('users.id', '=', 'company_employees.user_id');
                        })   
                        ->leftJoin('company_employee_locations', function ($join) {
                            $join->on('company_employee_locations.user_id', '=', 'company_employees.user_id');
                        })        
                ->select(DB::raw('DISTINCT users.name as employee_name,users.id as id,user_profiles.image as user_image'))
                ->where('company_employees.company_id',$company_id)
                ->whereIn('company_employee_locations.location_id',$loc_arr)
                ->where('role_users.role_id',4)
                ->where('users.is_active',1)
                ->where('users.is_delete',0)
                ->get();

            return Datatables::of($allData)
            ->addIndexColumn()
            ->addColumn('point', function($row){
                // dd($allData);
                $totalUserPoints = UserCreditPoint::where('user_id',$row->id)->where('is_active',1)->where('is_delete',0)->where('is_approved_point',1)->sum('earned_point');
                $button = $totalUserPoints.' pts.';

                return $button;
                // dd($allData);
            })
            ->addColumn('user_image', function($row){
                $button = '<a href="'.url('locationadmin/employee/employeeDetails/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/user/web/'.$row->user_image).'" alt=""></a>
                            <a href="'.url('locationadmin/employee/employeeDetails/'.encript_decript_data($row->id,'encript' ,2)).'">'.$row->employee_name.'</a>';

                return $button;
            })

            ->addColumn('location', function($row){
                $button = '';
                $employee_location = CompanyEmployeeLocation::leftJoin('company_locations', function ($join) {
                    $join->on('company_locations.id', '=', 'company_employee_locations.location_id');
                    })            
                    ->select(
                        'company_locations.name as location_name',
                        'company_locations.id as location_id'
                        )
                ->where('company_employee_locations.user_id',$row->id)->get();
                //dd($employee_location); 
                $loc_arr = [];
                foreach($employee_location as $key=>$loc){
                    $loc_arr[$key] = $loc->location_name;
                }                
                //$loc_arr_str = implode(',', $loc_arr);  
               // dd($loc_arr);
                if(count($loc_arr) > 2){
                    //$button .= $loc_arr[0].', '.$loc_arr[1].'...<span class="expand-btn float-right"></span>';
                    $button .= $loc_arr[0].', '.$loc_arr[1].'...<span class="expand-btn float-right"></span>';
                } else{

                    $button .= implode(', ' ,$loc_arr).'<span class="expand-btn float-right"></span>';
                }   
               // dd($button);
                return $button;
            })
             ->addColumn('listLocation', function($row){
                 $button ='';
                  $i = 1;
                  $employee_location = CompanyEmployeeLocation::leftJoin('company_locations', function ($join) {
                    $join->on('company_locations.id', '=', 'company_employee_locations.location_id');
                    })            
                    ->select(
                        'company_locations.name as location_name',
                        'company_locations.id as location_id'
                        )
                ->where('company_employee_locations.user_id',$row->id)->get();                 
                $loc_arr = [];
                foreach($employee_location as $key=>$loc){
                    $loc_arr[$key] = $loc->location_name;
                } 
                $loc_arr_str = implode(',', $loc_arr);      
                return $loc_arr_str;
            })
            ->addColumn('message', function($row){
                $button = '<a href="'.url('locationadmin/employee/employeeLocationMessage/'.encript_decript_data($row->id, 'encript', 2)).'"><img class="msg-icon" src="'.url('assets/images/chat.png').'" alt=""></a>';
                return $button;
            })
            
            ->rawColumns(['point','user_image','location','message','id'])
                ->make(true);
        }

        return view('locationAdmin.employee.index');
    }

    public function addEmployee(){
        $userDetails = Auth::guard('locationAdmin')->user();
        $locationDetails = CompanyLocationAdmin::leftJoin('company_locations', function ($join) {
            $join->on('company_locations.id', '=', 'company_location_admins.location_id');
            })            
            ->select(
                    'company_locations.name as location_name',
                    'company_locations.id as location_id'
                    )
            ->where('company_location_admins.user_id',$userDetails->id)
            ->where('company_location_admins.is_active',1)
            ->where('company_location_admins.is_delete',0)
            ->get(); 
        return View::make('locationAdmin.employee.add')->withLocationDetails($locationDetails);
    }

    
    public function saveEmployee(addEmployee $request){
        try {
            $userType = 'employee';
            $status = 0;
            $locations = $request->locations;
            $userDetails = Auth::guard('locationAdmin')->user();
            $locationAdminDetails = CompanyLocationAdmin::where('user_id',$userDetails->id)->first();
            $employee_location = array();
            //dd($companyDetails);

            if($request->isMethod('post')) {
                
                $request->validated();
                $employee_profile_image = $request->file('profile_image');
                $password               = random_password();

                $employeeArr['first_name'] = trim($request->first_name) ?: NULL;
                $employeeArr['last_name']  = trim($request->last_name) ?: NULL;
                $employeeArr['email']      = trim($request->email_address) ?: NULL;
                $employeeArr['name']       = trim($request->first_name.' '.$request->last_name) ?: NULL;
                $employeeArr['password']   = Hash::make($password);
                
                $employeeDetails = User::create($employeeArr);
                
                // company admin role
                RoleUser::create(['user_id' => $employeeDetails->id, 'role_id' => 4]);

                CompanyEmployee::create(['user_id' => $employeeDetails->id, 'company_id' => $locationAdminDetails->company_id]);

                if($employee_profile_image) {
                    $rootFolderPath               = public_path('/storage/images/user');
                    $employeeProfileArr['image'] = $this->defaultServices->imgUpload($rootFolderPath, $employee_profile_image);
                }
                $employeeProfileArr['user_id'] = $employeeDetails->id;
                UserProfile::create($employeeProfileArr);

                if (in_array($request->active_location, $locations)){
                 foreach($locations as $key=>$locationId){
                        $employee_location[$key]['company_id'] = $locationAdminDetails->company_id;
                        $employee_location[$key]['user_id'] = $employeeDetails->id;
                        $employee_location[$key]['location_id'] = $locationId;
                        $employee_location[$key]['active_location'] = ($locationId == $request->active_location) ? 1 : 0;
                        $employee_location[$key]['created_at'] = date('Y-m-d H:i:s');
                        $employee_location[$key]['updated_at'] = date('Y-m-d H:i:s');
                    }
                }else{
                    $request->session()->flash('error-message', 'Please Select Correct active location');
                    return redirect()->back();
                 }
                $employee_location_insert = CompanyEmployeeLocation::insert($employee_location);
                $to_email = $request->email_address;
                $to_name  = $request->first_name;
                $subject = 'User Credentials';

                $mail_data = array(
                    'email_address'   => $request->email_address,
                    'password'        => $password
                );

                Mail::send('emails.userCredentialEmail', $mail_data, function($message) use($to_name, $to_email, $subject) {
                    $message->to($to_email, $to_name??'4e Company Admin')->subject($subject);
                    $message->from(env('EMAIL_FROM', ''), env('EMAIL_FROM_NAME', '4e'));
                });

               
                $request->session()->flash('success-message', 'Employee added successfully');  
            }
            return redirect()->back();
            //return redirect()->route('companyAdmin.employeeList');
        }
        catch (Exception $ex) {
            return redirect()->back()->withErrors(['error-messsage' => [$ex->getMessage()]]);
        }
    }

    public function employeeDetails(Request $req){
        $adminDetails = Auth::guard('locationAdmin')->user();
        $user_id = encript_decript_data($req->id,'decript' ,2);
        $userDetails = User::leftJoin('user_profiles', function ($join) {
            $join->on('users.id', '=', 'user_profiles.user_id');
            })            
            ->select(
                'users.id as user_id',
                'users.name as name',
                'users.first_name as first_name',
                'users.last_name as last_name',
                'users.email as email',
                'user_profiles.address as user_address',
                'user_profiles.image as user_image',
                'user_profiles.about_me as user_about',
                'user_profiles.age as user_age',
                'user_profiles.gender as user_gender',
                'user_profiles.postal_code as postal_code'
            )
            ->where('users.id',$user_id)
            ->first(); 
            if($userDetails == null){
                return redirect()->back();
            } 
            $locationDetails = CompanyLocationAdmin::leftJoin('company_locations', function ($join) {
                $join->on('company_locations.id', '=', 'company_location_admins.location_id');
                })            
                ->select(
                        'company_locations.name as location_name',
                        'company_locations.id as location_id'
                        )
                ->where('company_location_admins.user_id',$adminDetails->id)
                ->where('company_location_admins.is_active',1)
                ->where('company_location_admins.is_delete',0)
                ->get(); 
            $assignLocation = array();
            $loc = CompanyEmployeeLocation::leftJoin('company_locations', function ($join) {
                $join->on('company_employee_locations.location_id', '=', 'company_locations.id');
            })
            ->leftJoin('company_location_admins', function ($join) {
                $join->on('company_location_admins.location_id', '=', 'company_locations.id');
            })
            ->select(                
                'company_employee_locations.active_location as active_location',
                'company_employee_locations.location_id as location_id',
                'company_locations.name as location_name'
            )
            ->where('company_employee_locations.user_id', $user_id) 
            ->where('company_location_admins.user_id',$adminDetails->id)
            ->get(); 
            $activeLocation = '';
            foreach($loc as $key => $value){        
                $assignLocation[$key]= $value->location_id;  
                if($value->active_location == 1){
                    $activeLocation =  $value->location_id;
                }              
            }
            //dd($activeLocation);
        $totalUserPoints = UserCreditPoint::where('user_id',$user_id)->where('is_active',1)->where('is_delete',0)->where('is_approved_point',1)->sum('earned_point');
        return view('locationAdmin.employee.employeeDetails')->withUserDetails($userDetails)->withtotalUserPoints($totalUserPoints)->withlocationDetails($locationDetails)->withassignLocation($assignLocation)->withactiveLocation($activeLocation);
    }

    public function updateEmployee(Request $request){
        //dd($request);
        try {
            $userType = 'locationAdmin';
            $status = 0;

            $emp_profile_image = $request->file('profile_image');
            $employee_details          = User::find($request->emp_id);   
            $employee_profile_details  = $employee_details->userProfile;
            $locations                 = $request->locations;
            $userDetails = Auth::guard('locationAdmin')->user();
            $locationAdminDetails = CompanyLocationAdmin::where('user_id',$userDetails->id)->first();
            //$companyDetails = $userDetails->getCompanies->first();
            $employeeArr['first_name'] = trim($request->first_name) ? : NULL;
            $employeeArr['last_name']  = trim($request->last_name) ?  : NULL;
            $employeeArr['name']       = $employeeArr['first_name'].' '.$employeeArr['last_name'];
            $user_update = User::where('id',$request->emp_id)->update($employeeArr);
            //dd($emp_profile_image);
            if($emp_profile_image) {
                $rootFolderPath =  public_path('/storage/images/user');

                if($employee_details->userProfile->image) {
                    $this->defaultServices->unlinkImg($rootFolderPath, $employee_details->userProfile->image);
                }

                $employeeProfileArr['image'] = $this->defaultServices->imgUpload($rootFolderPath, $emp_profile_image);
                $employeeProfileArr['updated_at'] = date('Y-m-d H:i:s');
                UserProfile::where('user_id',$request->emp_id)->update($employeeProfileArr);
            }

            if($locations){
                $delete_loc = CompanyEmployeeLocation::where('user_id',$request->emp_id)->delete();
                if (in_array($request->active_location, $locations)){
                    foreach($locations as $key=>$locationId){
                           $employee_location[$key]['company_id'] = $locationAdminDetails->company_id;
                           $employee_location[$key]['user_id'] = $request->emp_id;
                           $employee_location[$key]['location_id'] = $locationId;
                           $employee_location[$key]['active_location'] = ($locationId == $request->active_location) ? 1 : 0;
                           $employee_location[$key]['created_at'] = date('Y-m-d H:i:s');
                           $employee_location[$key]['updated_at'] = date('Y-m-d H:i:s');
                       }
                }else{
                      $request->session()->flash('error-message', 'Please Select Correct active location');
                       return redirect()->back();
                }
            }

            $employee_location_insert = CompanyEmployeeLocation::insert($employee_location);
            $request->session()->flash('success-message', 'Employee updated successfully');
            return redirect()->back();

        }catch (Exception $ex) {
            return redirect()->back()->withErrors(['error-messsage' => [$ex->getMessage()]]);
        }
    }

  

    public function employeeFindings(Request $req){
        $user_id = $req->user_id;
        //dd($user_id);
        if($req->ajax()) {

            $userCompanyFindings = CompanyFinding::leftJoin('company_finding_images', function ($join) {
            $join->on('company_findings.id', '=', 'company_finding_images.company_finding_id');
            })
            ->select(
                'company_findings.id',
                'company_findings.title as finding_title',
                'company_findings.description as finding_description',
                'company_findings.point as finding_point',
                'company_findings.submission_date as finding_submission_date',
                'company_finding_images.image as finding_image',
            )
            ->where('company_findings.is_active',1)
            ->where('company_findings.is_delete',0)
            ->where('company_findings.user_id',$user_id)
            ->groupBy('company_findings.id')
            ->get();
            //dd($userCompanyFindings);

            return Datatables::of($userCompanyFindings)
            ->addIndexColumn()
            ->addColumn('finding_title', function($row){                
                return $row->finding_title;
            })
            ->addColumn('finding_description', function($row){                
                return $row->finding_description;
            })
            ->addColumn('finding_point', function($row){
                if($row->finding_point <= 1){
                    return $row->finding_point.' pt';
                }else{
                    return $row->finding_point.' pts';  
                }

            })
            ->addColumn('finding_image', function($row){
                $finding_image = '<img class="" src="" alt="">';
                if($row->finding_image != ''){
                    $finding_image = '<img class="" src="'.url('storage/images/finding/web/'.$row->finding_image).'" alt="">';
                }
                return $finding_image;                
                
            })
            /*->addColumn('finding_submission_date', function($row){
                return  date('d/m/Y', strtotime($row->finding_submission_date)).' | '.date('G:i:s', strtotime($row->finding_submission_date));
            })*/
            ->addColumn('id', function($row){                
                return $row->id;
            })
            ->rawColumns(['finding_title', 'finding_description','finding_point', 'finding_image', 'finding_submission_date' , 'id'])
            ->make(true);
        }
        
    }

    public function employeeChallanges(Request $req){
        $user_id = $req->user_id;
        if($req->ajax()) {
           $userChallenges = Challenge::leftJoin('challenge_taking_types', function ($join) {
              $join->on('challenges.challenge_taking_type', '=', 'challenge_taking_types.id');
            })
            ->leftJoin('challenge_question_answers', function ($join) {
              $join->on('challenges.id', '=', 'challenge_question_answers.challenge_id')
                ->where('challenge_question_answers.is_correct',1);
            })
            ->leftJoin('challenge_employee_answers', function ($join) {
              $join->on('challenges.id', '=', 'challenge_employee_answers.challenge_id')
                ->where('challenge_employee_answers.is_active',1);
            })
            ->leftJoin('challenge_question_answers as a', function ($join) {
              $join->on('challenge_employee_answers.challenge_question_answer_id', '=', 'a.id');
                
            })
            ->select(
                'challenges.id',
                'challenges.challenge_name as challenge_name',
                'challenges.challenge_name as challenge_title',
                'challenges.challenge_question  as challenge_question',
                'challenges.challenge_question  as challenge_full_question',
                'challenges.challenge_desc as challenge_description',
                'challenge_taking_types.id as type_id',
                'challenge_taking_types.name as challenges_type',
                'challenges.point_value as challenge_point',
                //'challenges.created_at as challenge_submission_date',
                'challenges.challenge_question as challenge_question',
                'challenge_question_answers.answer as challenge_answer',
                'challenge_employee_answers.is_approved as is_answer_approved',
                'challenge_employee_answers.challenge_question_answer_id as challenge_question_answer_id',
                'challenge_employee_answers.is_correct_answer as is_correct_answer',
                'challenge_employee_answers.challenge_image as challenge_image',
                'a.answer as emp_answer',
                'challenge_employee_answers.submission_datetime as challenge_submission_date',
            )
            ->where('challenges.is_active',1)
            ->where('challenges.is_delete',0)
            ->where('challenge_employee_answers.user_id',$user_id)
            //->where('challenges.user_id',$user_id)
            //->groupBy('challenges.id')
            //->toSql();
            ->get();
            //dd('i am here');

            return Datatables::of($userChallenges)
            ->addIndexColumn()
            ->addColumn('challenge_name', function($row){   
                if($row->type_id == 1){
                    return substr($row->challenge_question,0,50).'...';
                   // return $row->challenge_question;
                } else{
                    return substr($row->challenge_name,0,50).'...';    
                     //return $row->challenge_name;               
                } 
            })
            ->addColumn('challenge_description', function($row){                
                return $row->challenge_description;
            })
            ->addColumn('challenges_type', function($row){                
                return $row->challenges_type;
            })
            ->addColumn('challenge_point', function($row){ 
                if($row->is_answer_approved==1){
                    if($row->is_correct_answer==1){
                        if($row->challenge_point <= 1){
                            return $row->challenge_point.' pt';
                        }else{
                          return $row->challenge_point.' pts';  
                        }
                        
                    }else{
                        return '0 pt';
                    }
                }else{
                    return '0 pt';
                }

                //return $row->challenge_point;
            })
            ->addColumn('challenge_question', function($row){                
                return $row->challenge_question;
            })
            ->addColumn('challenge_answer', function($row){                
                return $row->challenge_answer;                
            })
            /*->addColumn('challenge_submission_date', function($row){ 
                return $row->challenge_submission_date;
                //return  date('d/m/Y', strtotime($row->challenge_submission_date)).' | '.date('G:i:s', strtotime($row->challenge_submission_date));
            })*/
            ->addColumn('id', function($row){                
                return $row->id;
            })
            ->rawColumns(['challenge_name', 'challenge_description', 'challenges_type' , 'challenge_point', 'challenge_question', 'challenge_answer'  , 'id'])
            ->make(true);
        }
        
    }
    public function employeeMessageslist(Request $req){
       
        $user_id =  $req->user_id;    
        $userDetails = Auth::guard('locationAdmin')->user();
        $messageType    = $this->messageType;
       // $userRoleType   = $this->userRoleType;        
        $messageType    = $messageType['individual'];        
        
        if($req->ajax()) {
            $EmployeeMessages = EmployeeMessage::leftJoin('employee_message_threads', function ($join) {
            $join->on('employee_messages.id', '=', 'employee_message_threads.employee_message_id');
            })
            ->leftJoin('users', function ($join) {
                      $join->on('users.id', '=', 'employee_messages.sender_id');
              }) 
            ->leftJoin('user_profiles', function ($join) {
                      $join->on('users.id', '=', 'user_profiles.user_id');
              })
            ->select(
                'users.name as user_name',
                'user_profiles.image as user_image',
                'employee_message_threads.id as thread_id',
                'employee_message_threads.employee_message_id as parent_message_id',
                'employee_message_threads.message as emp_message',
                'employee_message_threads.image as emp_message_image',
                'employee_message_threads.created_at as created_at',
            )
            ->where('employee_messages.message_type',$messageType)
            ->where('employee_messages.is_active',1)
            ->where('employee_messages.is_delete',0)
            ->where('employee_message_threads.is_active',1)
            ->where('employee_message_threads.is_delete',0)
            ->where('employee_message_threads.sender_id',$user_id)
            //->orWhere('employee_messages.receiver_id',$userDetails->id)
            //->orWhere('employee_message_threads.sender_id',$userDetails->id)
            //->orWhere('employee_message_threads.receiver_id',$user_id)
            ->orderBy('employee_message_threads.created_at','desc')
            ->get();

            return Datatables::of($EmployeeMessages)
            ->addIndexColumn()
            ->addColumn('user_image', function($row){ 
                if($row->user_image != ''){
                    $user_image = '<img class="avtar" src="'.url('storage/images/user/web/'.$row->user_image).'" alt=""><a href="javascript:void(0)">'.$row->user_name.'</a>';
                }
                return $user_image;

            })
            ->addColumn('emp_message', function($row){       

                if($row->emp_message != ''){
                    return $row->emp_message;
                }else{
                    return '';
                }        
                
            })
            ->addColumn('created_at', function($row){              
                return $row->created_at;               

            })
            ->addColumn('emp_message_image', function($row){
                $emp_message_image = '<img class="" src="" alt="">';
                if($row->emp_message_image != '' || $row->emp_message_image = null){
                    $emp_message_image = url('storage/images/messages/web/'.$row->emp_message_image);
                   // $emp_message_image = '<img class="" src="'.url('storage/images/messages/web/'.$row->emp_message_image).'" alt="">';
                    return $emp_message_image;            
                }else{
                    return '';
                }
                
                
            })
            /*->addColumn('finding_submission_date', function($row){
                return  date('d/m/Y', strtotime($row->finding_submission_date)).' | '.date('G:i:s', strtotime($row->finding_submission_date));
            })*/
            ->addColumn('thread_id', function($row){                
                return $row->thread_id;
            })
            ->rawColumns(['user_image', 'emp_message','created_at',  'thread_id'])
            ->make(true);
        }

    }  

    public function employeeRedeemlist(Request $req){

        $userDetails    = Auth::guard('locationAdmin')->user();
        $locationAdmin = CompanyLocationAdmin::where('user_id',$userDetails->id)->first();
        //dd($locationAdmin);
       // dd($locationAdmin->location_id);
        $company_id = $locationAdmin->company_id;
        $company_location_id= $locationAdmin->location_id;
        $user_id= $req->user_id;
       // dd($locationAdmin->location_id);
        if($req->ajax()) {
        $redeemHistoryQuery = EmployeePointRedemption::leftJoin('gift_cards', function ($join) {
              $join->on('gift_cards.id', '=', 'employee_point_redemptions.giftcard_id');
            })
            ->leftJoin('users', function ($join) {
              $join->on('users.id', '=', 'employee_point_redemptions.user_id');
            })
            ->select(
                'employee_point_redemptions.id',
              //  'companies.company_name as company_name',
                'gift_cards.retailer_name as giftcard_name',
                'gift_cards.gift_desc as gift_desc',
                'gift_cards.gift_image as gift_image',
                'employee_point_redemptions.redeem_point as redeem_point',
                'employee_point_redemptions.redeem_amount as redeem_amount',
                'employee_point_redemptions.is_active as settle_status',
                'employee_point_redemptions.is_settle as is_settle',
                'employee_point_redemptions.created_at as created_at',
                'users.name as user_name',
                'users.email as user_email',
            )
            ->where('employee_point_redemptions.is_active',1)
            ->where('employee_point_redemptions.is_delete',0)
            ->where('employee_point_redemptions.company_id',$company_id)
            ->where('employee_point_redemptions.company_location_id',$company_location_id)
            ->where('employee_point_redemptions.user_id',$user_id)->get();
            
            /*if($company_id){
               $redeemHistoryQuery->where('employee_point_redemptions.company_id',$company_id);
            }    
            if($company_location_id){
               $redeemHistoryQuery->where('employee_point_redemptions.company_location_id',$company_location_id);
            }        
            if($user_id){
               $redeemHistoryQuery->where('employee_point_redemptions.user_id',$user_id);
            }
            $redeemHistories=$redeemHistoryQuery->get();*/
            //dd($redeemHistories);            
            return Datatables::of($redeemHistoryQuery)
            ->addIndexColumn()
            ->addColumn('giftcard_name', function($row){                
                $giftcard_name= $row->giftcard_name;
                if(strlen($giftcard_name) > 25){
                  $giftcard_name = substr($giftcard_name, 0, 25) . '...';
                }
                return $giftcard_name;
            })
            ->addColumn('redeem_point', function($row){ 

                return $row->redeem_point.' pts';;
            })
            ->addColumn('redeem_amount', function($row){                
                return $row->redeem_amount;
            })
            ->addColumn('gift_desc', function($row){                
                return $row->gift_desc;
            })
            ->addColumn('gift_image', function($row){                
                return $row->gift_image;
            })
            ->addColumn('created_at ', function($row){                
                return $row->created_at ;
            })
            ->addColumn('id', function($row){                
                return $row->id;
            })
            ->rawColumns([ 'giftcard_name' , 'redeem_point' , 'redeem_amount','created_at', 'id'])
            ->make(true);
        }
    } 
}