<?php

namespace App\Http\Controllers\CompanyAdmin;

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\Http\Requests\LocationAdminAdd;
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 LocationAdminController extends Controller {

    protected $defaultServices;

    public function __construct(DefaultServices $defaultServices)
    {
        $this->defaultServices = $defaultServices;
    }

    public function index(Request $request)
    {
        //dd("Hello");
        $userDetails    = Auth::guard('companyAdmin')->user();
        $companyDetails = $userDetails->getCompanies->first();
       if($request->ajax()) {
            $is_active = $request->checkstatus;
            $filters   = [];

            if($is_active != '') {
                $allLocationAdmin = CompanyLocationAdmin::leftJoin('company_locations', function ($join) {
                    $join->on('company_location_admins.location_id', '=', 'company_locations.id');
                    })
                    ->leftJoin('users', function ($join) {
                        $join->on('company_location_admins.user_id', '=', 'users.id');
                    })
                    ->leftJoin('user_profiles', function ($join) {
                        $join->on('company_location_admins.user_id', '=', 'user_profiles.user_id');
                    })
                    ->select(
                        'company_location_admins.id as id',
                        'company_locations.name as location_name',
                        'company_location_admins.user_id as admin_user_id',
                        'users.name as user_name',
                        'user_profiles.image as user_image'
                    )
                    ->where('company_location_admins.company_id',$companyDetails->id)
                    ->where('company_location_admins.is_default',1)
                    ->where('company_location_admins.is_active',$is_active)
                    ->where('company_location_admins.is_delete',0)
                    ->get();
            }else{
                $allLocationAdmin = CompanyLocationAdmin::leftJoin('company_locations', function ($join) {
                    $join->on('company_location_admins.location_id', '=', 'company_locations.id');
                    })
                    ->leftJoin('users', function ($join) {
                        $join->on('company_location_admins.user_id', '=', 'users.id');
                    })
                    ->leftJoin('user_profiles', function ($join) {
                        $join->on('company_location_admins.user_id', '=', 'user_profiles.user_id');
                    })
                    ->select(
                        'company_location_admins.id as id',
                        'company_locations.name as location_name',
                        'company_location_admins.user_id as admin_user_id',
                        'users.name as user_name',
                        'user_profiles.image as user_image'
                    )

                    ->where('company_location_admins.company_id',$companyDetails->id)
                    ->where('company_location_admins.is_default',1)
                    ->where('company_location_admins.is_delete',0)
                    ->get();
                //dd($allLocationAdmin);
            }
            return Datatables::of($allLocationAdmin)
            ->addIndexColumn()
            ->addColumn('user_image', function($row){
                $button = '<a href="'.url('companyadmin/locationAdmin/locationAdminList/messages/companyAdminToLocationAdmin/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="avtar" src="'.url('storage/images/user/web/'.$row->user_image).'" alt=""></a>
                            <a href="">'.$row->user_name.'</a>';
                return $button;
                
            })
            ->addColumn('type', function($row){
                return  'Location Admin';
            })
            ->addColumn('location', function($row){
                $locations = CompanyLocationAdmin::select('location_id')->where('user_id',$row->admin_user_id)->get();
                if(count($locations) > 1){
                    $button ='<a href="javascript:void(0)" class="showloc" data-userId ="'.$row->admin_user_id.'" >'.$row->location_name.'...<span class="expand-btn"></span></a>';
                }else{
                    $button ='<a href="javascript:void(0)" class="showloc" data-userId ="'.$row->admin_user_id.'" >'.$row->location_name.'<span class="expand-btn"></span></a></a>';
                }
                
                return  $button;
            })
            ->addColumn('listLocation', function($row){
                $button ='';
                $i = 1;
                $locations = CompanyLocationAdmin::select('location_id')->where('user_id',$row->admin_user_id)->get();
                if(count($locations) > 0){                
                    foreach($locations as $loc){ 
                        $button .= $loc->getLocations->name;   
                        if( $i <= count($locations)-1 ){
                            $button .=',';
                        }               
                        $i++;
                    }    
                }
                return  $button;
            })
            //=============== need to add after message section complete======================//
            
            ->addColumn('message', function($row){
                $button = '<a href="'.url('companyadmin/locationAdmin/locationAdminList/messages/companyAdminToLocationAdmin/'.encript_decript_data($row->id,'encript' ,2)).'"><img class="msg-icon" src="'.url('assets/images/chat.png').'" alt=""></a>';
                return $button;
            })

            //=============== need to add after message section complete======================//
            ->addColumn('id', function($row){
                
                return $row->id;
            })
            ->rawColumns(['user_image','type','location','message','id'])
            ->make(true);
        }

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

    public function addLocationAdmin(Request $request){
        $userDetails = Auth::guard('companyAdmin')->user();
        $companyDetails = $userDetails->getCompanies->first();
        $not_assigned   = [];
        $allAssignedLocation = [];
        $getLocation = CompanyLocation::with(['getCompany'])
        ->whereHas("getCompany", function ($query) use($companyDetails) {
            $query->where([
                ['companies.id', '=', $companyDetails->id]
            ]);
        })
        ->get();
        $allCompanyLocationAdmin = CompanyLocationAdmin::select('location_id')->get();
        foreach($allCompanyLocationAdmin as $key=>$value){
            array_push($allAssignedLocation,$value->location_id);
        }
        foreach($getLocation as $key=>$location){
            if (!in_array($location->id, $allAssignedLocation)) {
                $not_assigned[$key]['location_id'] = $location->id; 
                $not_assigned[$key]['location_name'] = $location->name; 
            }
        }
        if(empty($not_assigned)){
            $request->session()->flash('error-message', 'All locations are assigned to add new location admin please add location first');
            return redirect()->back();
        }else{
            return View::make('companyAdmin.locationAdmin.add')->withLocationDetails($not_assigned);
        }
       
    }

    public function saveLocationAdmin(LocationAdminAdd $request){
        try {
            $userType = 'company-admin';
            $status = 0;
            $userDetails = Auth::guard('companyAdmin')->user();
            $companyDetails = $userDetails->getCompanies->first();
            $employee_location = array();
            $locations = $request->locations;
            //dd($locations);
            if($request->isMethod('post')) {

                $request->validated();
                $location_admin_image = $request->file('profile_image');
                $password            = random_password();



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

                if (in_array($request->active_location, $locations)){
                    foreach($locations as $key=>$locationId){
                        //dd($locationId);
                           $location_admin_arr[$key]['user_id'] = $locAdminDetails->id;
                           $location_admin_arr[$key]['company_id'] = $companyDetails->id;
                           $location_admin_arr[$key]['location_id'] = $locationId;
                           $location_admin_arr[$key]['is_default'] = ($locationId == $request->active_location) ? 1 : 0;
                           $location_admin_arr[$key]['created_at'] = date('Y-m-d H:i:s');
                           $location_admin_arr[$key]['updated_at'] = date('Y-m-d H:i:s');
                       }
                   }else{
                       $request->session()->flash('error-message', 'Please Select Correct active location');
                       return redirect()->back();
                    }
                    //dd($location_admin_arr);
                CompanyLocationAdmin::insert($location_admin_arr);

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


                $to_email = $request->email_address;
                $to_name  = $request->first_name;
                $subject = 'Location Admin Credential';

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

                Mail::send('emails.locationAdminCredential', $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'));
                    $message->from('noreply@gmail.com', 'Foure WebAdmin');
                });

               
                $request->session()->flash('success-message', 'Location Admin added successfully');  
            }

            //return redirect()->back();
            return redirect()->route('companyAdmin.locationAdminList');

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

    // public function updateEmployee(Request $request) {
    //     try {
    //         $userType = 'employee';
    //         $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('companyAdmin')->user();
    //         $companyDetails = $userDetails->getCompanies->first();
    //         $employeeArr['first_name'] = trim($request->first_name) ? : NULL;
    //         $employeeArr['last_name']  = trim($request->last_name) ?  : NULL;
    //         $user_update = User::where('id',$request->emp_id)->update($employeeArr);
    //         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'] = $companyDetails->id;
    //                        $employee_location[$key]['user_id'] = $employee_details->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()]]);
    //     }
    // }

}
