Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1496
HomeController
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 23
97656
0.00% covered (danger)
0.00%
0 / 1496
 __construct
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getAllAttendanceRequests
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getTeamAttendanceRequests
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 getAssignedEmployeeAttendanceRequests
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 getAllLeaveRequests
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getAllLeaveRequestsOfTeam
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 getAllLeaveRequestsOfAssignedEmployees
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 index
0.00% covered (danger)
0.00%
0 / 1
1332
0.00% covered (danger)
0.00%
0 / 288
 checkincheckoutDetail
0.00% covered (danger)
0.00%
0 / 1
182
0.00% covered (danger)
0.00%
0 / 46
 teamStatus
0.00% covered (danger)
0.00%
0 / 1
42
0.00% covered (danger)
0.00%
0 / 32
 teamSelected
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 36
 getTeamAttendanceDetails
0.00% covered (danger)
0.00%
0 / 1
2970
0.00% covered (danger)
0.00%
0 / 250
 getAttendanceDetails
0.00% covered (danger)
0.00%
0 / 1
2550
0.00% covered (danger)
0.00%
0 / 243
 createRole
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 4
 getProfilePicturePath
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 10
 usersOnLeave
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 10
 teamUsersOnLeave
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 14
 getLeaveRequest
0.00% covered (danger)
0.00%
0 / 1
870
0.00% covered (danger)
0.00%
0 / 111
 getAttendanceRequest
0.00% covered (danger)
0.00%
0 / 1
930
0.00% covered (danger)
0.00%
0 / 105
 lateCheckinEarlyCheckout
0.00% covered (danger)
0.00%
0 / 1
420
0.00% covered (danger)
0.00%
0 / 32
 PlatformCheck
0.00% covered (danger)
0.00%
0 / 1
812
0.00% covered (danger)
0.00%
0 / 144
 getCompOffBalanceRequest
0.00% covered (danger)
0.00%
0 / 1
870
0.00% covered (danger)
0.00%
0 / 149
 updateMethod
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 4
<?php
namespace App\Http\Controllers\Dashboard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Admin\Team;
use App\Models\BiometricData\BiometricData;
use App\Models\Dashboard\AttendanceDetail;
use App\Models\Admin\UserDetail;
use App\Models\Admin\Organisation;
use App\Models\Auth\User;
use App\Helpers\HolidayHelper;
use App\Helpers\LeaveHelper;
use App\Models\AttendanceRequests\UserAttendanceRequests;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Session;
use Illuminate\Support\Facades\View;
use Notification;
use App\Notifications\SubscriptionRenewalFailed;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Dashboard\AttendanceDetailController;
use App\Models\Admin\Shift;
use App\Models\Admin\Holiday;
use App\Models\Leave\ApplyLeave;
use App\Models\Leave\CompOffLeave;
use App\Models\Auth\UserWeeklyOff;
use App\Models\Auth\UserShift;
use GetShiftDetailHelper;
use App\Models\Admin\Leave;
use App\Models\Auth\UserRequestDiscuss;
use App\Models\Auth\userRequestCollaborator;
use Illuminate\Support\Facades\Log;
use App\Helpers\AttendanceHelper;
use App\Models\Admin\TeamSetting;
use App\Models\Admin\userSetting;
use App\Models\Admin\Setting;
use DB;
use App\Helpers\PlatformHelper;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Artisan;
use App\Http\Controllers\Auth\PumbleController;
class HomeController extends Controller
{
    private $check_in, $check_out, $totalPresent, $totalEmployees, $lateCount;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    function getAllAttendanceRequests()
    {
        $request_attendances = UserAttendanceRequests::where('status', 'pending')->orderBy('created_at', 'DESC')->limit(5)->get();
    }
    function getTeamAttendanceRequests()
    {
        $userIds = GetShiftDetailHelper::getMyteamMembers();
        $request_attendances = UserAttendanceRequests::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->limit(5)->get();
        return $request_attendances;
    }
    function getAssignedEmployeeAttendanceRequests()
    {
        $userIds = GetShiftDetailHelper::getMyReportingEmployees();
        $request_attendances = UserAttendanceRequests::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->limit(5)->get();
        return $request_attendances;
    }
    function getAllLeaveRequests()
    {
        $leave_reports = ApplyLeave::where('status', 'pending')->orderBy('created_at', 'DESC')->orderBy('created_at', 'DESC')->limit(5)->get();
    }
    function getAllLeaveRequestsOfTeam()
    {
        $userIds =  GetShiftDetailHelper::getMyteamMembers();
        $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->orderBy('created_at', 'DESC')->limit(5)->get();
    }
    function getAllLeaveRequestsOfAssignedEmployees()
    {
        $userIds =  GetShiftDetailHelper::getMyReportingEmployees();
        $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->orderBy('created_at', 'DESC')->limit(5)->get();
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $id)
    {
        Artisan::call('cache:clear');
        Artisan::call('config:clear');
        Artisan::call('route:clear');
        Artisan::call('view:clear');
        $requestType = $id->requestType;   /// request type form app
        // $ob = new PumbleController();
        // $ob->sendMessage("","");
        $title = '/Dashboard';
        $roles = Role::all();
        $teams = Team::all();
        $organisations = Organisation::all();
        $currUser = Auth::user()->id;
        $currentDates = [];
        $type = null;
        $dateFormat = config('settings.php_date_format');
        $attendanceDetail = UserAttendanceRequests::where('user_id', '=', $currUser)
            ->where('status', '=', 'pending')
            ->get();
        for ($i = 0; $i < count($attendanceDetail); $i++) {
            $current_date[$i] = $attendanceDetail[$i]->getAttribute('created_at');
            $currentDates[$i] = Carbon::parse($current_date[$i])->format('d-m-Y');
        }
        // Compare the current dates to find pairs with "pending" status
        $pendingDates = [];
        for ($i = 0; $i < count($currentDates); $i++) {
            for ($j = $i + 1; $j < count($currentDates); $j++) {
                if ($attendanceDetail[$i]->status == 'pending' && $attendanceDetail[$j]->status == 'pending') {
                    $pendingDates[] = [$currentDates[$i], $currentDates[$j]];
                }
            }
        }
        // Delete UserAttendanceRequests where requested_for = "late check in" and "both" request is present
        foreach ($attendanceDetail as $attendance) {
            if ($attendance->requested_for == 'Late Checkin' && in_array(Carbon::parse($attendance->created_at)->format('d-m-Y'), $currentDates)) {
                // Check if a "both" request exists for the same date
                $bothRequestExists = UserAttendanceRequests::where('user_id', '=', $attendance->user_id)
                    ->where('requested_for', '=', 'both')
                    ->whereDate('check_in', Carbon::parse($attendance->created_at)->format('Y-m-d'))
                    ->exists();
                if ($bothRequestExists) {
                    $attendance->delete();
                }
            }
        }
        //$request_attendances = UserAttendanceRequests::where('status','pending')->orderBy('created_at','DESC')->limit(5)->get();
        //$leave_reports = ApplyLeave::where('status', 'pending')->orderBy('created_at','DESC')->limit(5)->get();
        ///  for Attendance requests 
        if (auth()->user()->can('View All Attendance request')) {
            $request_attendances = UserAttendanceRequests::where('status', 'pending')->orderBy('created_at', 'DESC')->get();
        } else if (auth()->user()->can('View All Attendance requests of team')) {
            $userIds = GetShiftDetailHelper::getMyteamMembers();
            $request_attendances = UserAttendanceRequests::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->get();
        } else if (auth()->user()->can('View All Attendance requests of assigned employees')) {
            $userIds = GetShiftDetailHelper::getMyReportingEmployees();
            $request_attendances = UserAttendanceRequests::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->get();
        } else {
            $request_attendances = [];
        }
        ///  for leave requests 
        // if (auth()->user()->can('View All leave requests')) {
        //     $leave_reports = ApplyLeave::where('status', 'pending')->orderBy('created_at', 'DESC')->orderBy('created_at', 'DESC')->get();
        // } else if (auth()->user()->can('View All leave requests of team')) {
        //     $userIds =  GetShiftDetailHelper::getMyteamMembers();
        //     $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->orderBy('created_at', 'DESC')->get();
        // } else if (auth()->user()->can('View All leave requests of assigned employees')) {
        //     //View All leave requests of assigned employees
        //     $userIds =  GetShiftDetailHelper::getMyReportingEmployees();
        //     $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->orderBy('created_at', 'DESC')->get();
        // } else {
        //     $leave_reports = [];
        // }
        // if (auth()->user()->can('View All leave requests')) {
        //     $leave_reports = ApplyLeave::where('status', 'pending')->orderBy('created_at', 'DESC')->get();
        // } else if (auth()->user()->can('View All leave requests of team')) {
        //     $userIds = GetShiftDetailHelper::getMyteamMembers();
        //     $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->get();
        // } else if (auth()->user()->can('View All leave requests of assigned employees')) {
        //     // View All leave requests of assigned employees
        //     $userIds = GetShiftDetailHelper::getMyReportingEmployees();
        //     $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->orderBy('created_at', 'DESC')->get();
        // } else {
        //     $leave_reports = [];
        // }
        if (auth()->user()->can('View All leave requests')) {
            $leave_reports = ApplyLeave::join('users', 'apply_leaves.user_id', '=', 'users.id')
                ->where('apply_leaves.status', 'pending')
                ->whereNull('users.deleted_at')
                ->orderBy('apply_leaves.created_at', 'DESC')
                ->get();
                // dd($leave_reports);
        } else if (auth()->user()->can('View All leave requests of team')) {
            $userIds = GetShiftDetailHelper::getMyteamMembers();
            $leave_reports = ApplyLeave::join('users', 'apply_leaves.user_id', '=', 'users.id')
                ->whereIn('apply_leaves.user_id', $userIds)
                ->where('apply_leaves.status', 'pending')
                ->whereNull('users.deleted_at')
                ->orderBy('apply_leaves.created_at', 'DESC')
                ->get();
        } else if (auth()->user()->can('View All leave requests of assigned employees')) {
            $userIds = GetShiftDetailHelper::getMyReportingEmployees();
            $leave_reports = ApplyLeave::join('users', 'apply_leaves.user_id', '=', 'users.id')
                ->whereIn('apply_leaves.user_id', $userIds)
                ->where('apply_leaves.status', 'pending')
                ->whereNull('users.deleted_at')
                ->orderBy('apply_leaves.created_at', 'DESC')
                ->get();
        } else {
            $leave_reports = [];
        }
        //  dd($leave_reports);
        // Now $leave_reports contains the desired results
        
        /// for comp off balance request
        if (auth()->user()->can('View All CompOff requests')) {
            $compoffBalance_reports = CompOffLeave::join('users', 'comp_off_leaves.user_id', '=', 'users.id')
             ->where('status', 'pending')
             ->whereNull('users.deleted_at')
             ->orderBy('comp_off_leaves.created_at', 'DESC') // Specify the table for created_at
             ->get();
             // dd($compoffBalance_reports);
           } else if (auth()->user()->can('View All CompOff requests of team')) {
            $userIds = GetShiftDetailHelper::getMyteamMembers();
            $compoffBalance_reports = CompOffLeave::whereIn('user_id', $userIds)
             ->where('status', 'pending')
             ->whereNull('users.deleted_at')
             ->orderBy('comp_off_leaves.created_at', 'DESC') // Specify the table for created_at
             ->get();
           } else if (auth()->user()->can('View All CompOff requests of assigned employees')) {
            $userIds = GetShiftDetailHelper::getMyReportingEmployees();
            $compoffBalance_reports = CompOffLeave::whereIn('user_id', $userIds)
             ->where('status', 'pending')
             ->whereNull('users.deleted_at')
             ->orderBy('comp_off_leaves.created_at', 'DESC') // Specify the table for created_at
             ->get();
           } else {
            $compoffBalance_reports = [];
           }
      
        // If the user is a reporting manager, exclude admin-marked leaves
        if (auth()->user()->hasRole('Reporting Manager')) {
            $adminMarkedLeaves = ApplyLeave::where('status', 'pending')->where('requested_by', 'admin')->pluck('id')->toArray();
            $leave_reports = $leave_reports->whereNotIn('id', $adminMarkedLeaves);
        }
        $this->checkincheckoutDetail();
        $dcheck_in = null;
        $dcheck_out = null;
        if ($this->check_in != null) {
            $dcheck_in = Carbon::parse($this->check_in);
            $dcheck_in->setTimezone(config('settings.time_zone'));
            $dcheck_in = $dcheck_in->format(config('settings.php_date_format') . ' ' . config('settings.time_format'));
        }
        if ($this->check_out != null) {
            $dcheck_out = Carbon::parse($this->check_out);
            $dcheck_out->setTimezone(config('settings.time_zone'));
            $dcheck_out = $dcheck_out->format(config('settings.php_date_format') . ' ' . config('settings.time_format'));
        }
        //get all attedance details
        $this->getAttendanceDetails($id);
        $totalEmployees = $this->totalEmployees;
        $noCheckinUsers = $this->noCheckinUsers;
        $noCheckinUsersCount = $this->noCheckinUsersCount;
        //late checkin users
        $lateCheckinUsers = $this->lateCheckinUsers;
        $lateCheckinCount = $this->lateCheckinCount;
        //available users
        $totalPresent = $this->totalPresent;
        $avialableUsers = $this->avialable_users;
        //early checkout users
        $earlyCheckoutUsers = $this->earlyCheckoutUsers;
        $earlyCheckoutCount = $this->earlyCheckoutCount;
        //user on weekend
        $usersOnWeekend = $this->usersOnWeekend;
        $usersOnWeekendCount = $this->usersOnWeekendCount;
        //on leave
        $this->usersOnLeave();
        $usersOnLeave = $this->usersOnLeave;
        $usersOnLeaveCount = $this->usersOnLeaveCount;
    
        
        $dobnow = Carbon::now('UTC')->format('Y-m-d');
        $dobmonth = Carbon::now('UTC')->format('m');
        $dobday = Carbon::now('UTC')->format('d');
        $birthdayusers = UserDetail::whereMonth('dob', $dobmonth)
            ->whereDay('dob', $dobday)
            ->get();
        $birthdayuserIds = $birthdayusers->pluck('user_id');
        $birthdayUsers = User::whereIn('id', $birthdayuserIds)->get();
        $userid = Auth::user()->id;
        $holidayIds = HolidayHelper::getholidayList($userid);
        $holiday = Holiday::where('date', '>', $dobnow)
                            ->whereIn('id', $holidayIds)
                            ->orderBy('date', 'asc') 
                            ->take(2) 
                            ->get();
        //$currentime = Carbon::now(config('settings.time_zone'));
        //$currentTime =  $currentime->format(config('settings.time_format'));
        $startDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $todayShiftTime = GetShiftDetailHelper::getShiftDetail(auth()->id(), $startDate, $endDate);
        $todayShiftStartTime = '';
        $todayShiftEndTime = '';
        if ($todayShiftTime != null) {
            // $todayShiftStartTime = $todayShiftTime->shift_start;
            // $todayShiftStartTime = Carbon::parse($todayShiftStartTime,config('app.timezone'));
            // $todayShiftStartTime->setTimezone(Config('settings.time_zone'));
            // $todayShiftStartTime = Carbon::parse($todayShiftStartTime)->toTimeString(); //user checkout time
            $todayShiftStartTime = $todayShiftTime['shiftStartTime'];
            $todayShiftStartTime = date(Config('settings.time_format'), strtotime($todayShiftStartTime));
            // $todayShiftEndTime = $todayShiftTime->shift_end;
            // $todayShiftEndTime = Carbon::parse($todayShiftEndTime,config('app.timezone'));
            // $todayShiftEndTime->setTimezone(Config('settings.time_zone'));
            // $todayShiftEndTime = Carbon::parse($todayShiftEndTime)->toTimeString(); //user checkout time
            $todayShiftEndTime = $todayShiftTime['shiftEndTime'];
            $todayShiftEndTime = date(Config('settings.time_format'), strtotime($todayShiftEndTime));
        }
        $userAttendanceSelfService = [];
        $userInfo = UserDetail::where('user_id', Auth()->user()->id)->first();
        if (!empty($userInfo)) {
            $userAttendanceSelfService = $userInfo->attendanceRequests->where('name', 'Self Service');
        }
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($id);
        $valUser = AttendanceHelper::getAttendanceUser($id);
        /// generating response for app
        if($requestType=="api"){
            return json_encode([
                "val" =>$val, 
                "valTeam" =>$valTeam, 
                "valUser" =>$valUser
            ]);
         }
        //getting check_out week data for particular user 
        $startDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->subDay(5)->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        //$endDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDate = Carbon::now(config('settings.time_zone'))->endOfDay();
        $checkOutDate = array();
        $markValue = AttendanceDetail::where('user_id', Auth::user()->id)
            ->value('attendance_setting');
        //dd($markValue);      
        $Checkindata = AttendanceDetail::where('user_id', '=', Auth::user()->id)
            ->where('attendance_setting', 1)
            ->exists();
        if ($Checkindata) {
            $noCheckindata = AttendanceDetail::where('user_id', '=', Auth::user()->id)
                ->where('attendance_setting', 1)
                ->get();
            for ($i = 0; $i < count($noCheckindata); $i++) {
                $thisDay[$i] = $noCheckindata[$i]->getAttribute('created_at');
                $NocheckInDate[$i] = Carbon::parse($thisDay[$i])->format('d-m-Y');
                $type = null;
            }
        } else {
            $NocheckInDate = '0-0-0';
        }
        $ocheckindata = AttendanceDetail::where('user_id', '=', Auth::user()->id)
            ->where('attendance_setting', 2)
            ->exists();
        if ($ocheckindata) {
            $onlyCheckindata = AttendanceDetail::where('user_id', '=', Auth::user()->id)
                ->where('attendance_setting', 2)
                ->get();
            for ($i = 0; $i < count($onlyCheckindata); $i++) {
                $thisDay[$i] = $onlyCheckindata[$i]->getAttribute('check_in');
                $date[$i] = Carbon::createFromFormat('Y-m-d H:i:s', $thisDay[$i]);
                $date[$i]->setTimezone('Asia/Kolkata');
                $formattedDate[$i] = $date[$i]->toDateString();
                $OnlycheckInDate[$i] = Carbon::parse($formattedDate[$i])->format('d-m-Y');
                $type = null;
            }
        } else {
            $OnlycheckInDate = '0-0-0';
        }
        //to get the Date of the checkin for calendar
        $sevenDays = AttendanceDetail::where('user_id', '=', Auth::user()->id)
            ->select('check_in')
            ->where('check_out', '<>', NULL)
            ->whereBetween('check_in', [$startDate, $endDate])
            ->get();
        //  dd($sevenDays);
        for ($i = 0; $i < count($sevenDays); $i++) {
            $thisDay[$i] = $sevenDays[$i]->getAttribute('check_in');
            $date[$i] = Carbon::createFromFormat('Y-m-d H:i:s', $thisDay[$i]);
            $date[$i]->setTimezone('Asia/Kolkata');
            $formattedDate[$i] = $date[$i]->toDateString();
            $checkOutDate[$i] = Carbon::parse($formattedDate[$i])->format('d-m-Y');
            $type = null;
        }
        //dd($thisDay);
        //to get the leave values
        $leave_dates = ApplyLeave::where('user_id', '=', Auth::user()->id)
            ->select('from_date','to_date')
            ->where('status', '=', 'Approve')
            ->get();
        $leaveDates[] = [];
        foreach ($leave_dates as $leave) {
            $fromDate = Carbon::parse($leave->from_date);
            $toDate = Carbon::parse($leave->to_date);
            
            while ($fromDate->lte($toDate)) {
                $leaveDates[] = $fromDate->format('d-m-Y');
                $fromDate->addDay();
            }
        }
        //to get the holidays dates
        $holidays = Holiday::all('date');
        $holidayDates = array();
        for ($i = 0; $i < count($holidays); $i++) {
            $holidaydate[$i] = $holidays[$i]->getAttribute('date');
            $holidayDates[$i] = Carbon::parse($holidaydate[$i])->format('d-m-Y');
            $type = null;
        }
        //to get the approve attendance records
        $attendance_approved_dates = UserAttendanceRequests::where('user_id', Auth::user()->id)
            ->where('check_in', '>=', $startDate)
            ->where('check_in', '<=', $endDate)
            ->where('status', '=', 'approved')
            ->where('requested_for', '<>', 'Late Checkin')
            ->get();
        $approved_dates = array();
        for ($i = 0; $i < count($attendance_approved_dates); $i++) {
            $approveDate[$i] = $attendance_approved_dates[$i]->getAttribute('check_in');
            $approved_dates[$i] = Carbon::createFromFormat('Y-d-m H:i:s', $approveDate[$i])->format('d-m-Y');
            $type = null;
        }
        // to get the weekly off dates
        $startingDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->subDay(5)->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endingDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $userWeeklyOff = UserWeeklyOff::where('user_id', Auth::user()->id)
            ->whereBetween('created_at', [$startingDate, $endingDate])
            ->where('weekly_off', 1)
            ->get();
        $weeklyOff_dates = array();
        for ($i = 0; $i < count($userWeeklyOff); $i++) {
            $weekOff[$i] = $userWeeklyOff[$i]->getAttribute('date');
            $weeklyOff_dates[$i] = Carbon::parse($weekOff[$i])->format('d-m-Y');
            $type = null;
        }
        $type = '';
        // if (auth()->user()->can('Super Admin')) {
        //     $type = 'admin';
        //     $checkOutDate = '0-0-0';
        //     $leaveDates = '0-0-0';
        //     $approved_dates = '0-0-0';
        //     $holidayDates = '0-0-0';
        //     $weeklyOff_dates = '0-0-0';
        //     $NocheckInDate = '0-0-0';
        //     $OnlycheckInDate = '0-0-0';
        // }
        $currentDate = Carbon::now(config('settings.time_zone'))->toDateString();
        $requests = UserAttendanceRequests::select(DB::raw('DATE(check_in) as check_in_date'))
            ->where('user_id', '=', $currUser)
            ->where(DB::raw('DATE(check_in)'), '=', $currentDate)
            ->where('requested_for', '=', 'Late Checkin')
            ->where('status', '=', 'pending')
            ->first();
        if (empty($requests)) {
            $requests = "1";
        }
        //dd($userAttendanceSelfService);
        return view(
            'dashboard.layout',
            compact(
                'val',
                'valTeam',
                'valUser',
                'title',
                'roles',
                'teams',
                'dcheck_in',
                'dcheck_out',
                'totalPresent',
                'avialableUsers',
                'lateCheckinUsers',
                'totalEmployees',
                'lateCheckinCount',
                'earlyCheckoutUsers',
                'earlyCheckoutCount',
                'noCheckinUsers',
                'noCheckinUsersCount',
                'usersOnLeave',
                'usersOnLeaveCount',
                'usersOnWeekend',
                'usersOnWeekendCount',
                'birthdayUsers',
                'holiday',
                'request_attendances',
                'leave_reports',
                'todayShiftStartTime',
                'todayShiftEndTime',
                'userAttendanceSelfService',
                'checkOutDate',
                'leaveDates',
                'holidayDates',
                'approved_dates',
                'weeklyOff_dates',
                'requests',
                'currentDate',
                'type',
                'markValue',
                'NocheckInDate',
                'OnlycheckInDate',
                'compoffBalance_reports',
                'dateFormat'
            )
        );
    }
    public function checkincheckoutDetail()
    {
        $user = auth()->user();
        $currentDateTime = Carbon::now('UTC');
        $startDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $today_date_time = Carbon::now(config('settings.time_zone'));
        $time_now = $today_date_time->toTimeString();
        if (isset($user->userdetail)) {
            //get shift details
            $shift = GetShiftDetailHelper::getShiftDetail($user->id, $startDate, $endDate);
            if ($shift != null) {
                $shiftStartTime = $shift['shiftStartTime'];
                $shiftEndTime = $shift['shiftEndTime'];
                // $bufferTime =  $shift['bufferTime'];
                $bufferCheckinTime = $shift['bufferCheckinTime'];
                $bufferCheckoutTime = $shift['bufferCheckoutTime'];
                $query = AttendanceDetail::query();
                $query->where('user_id', '=', $user->id);
                $offsetStartTime = Carbon::parse($shiftStartTime);
                $offsetStartTime = $offsetStartTime->subHours(4)->toTimeString();
                $offsetEndTime = Carbon::parse($shiftEndTime);
                $offsetEndTime = $offsetEndTime->addHours(4)->toTimeString();
                if ($shiftStartTime > $shiftEndTime) // to check if the shift ends the next day
                {
                    $user_id = $user->id;
                    $query->whereBetween('check_in', [$startDate, $endDate]);
                    $attendanceDetail = $query->get();
                    if ($attendanceDetail->isEmpty()) //if no attendance is marked for the user that particular day
                    {
                        if (
                            ($time_now < $shiftStartTime && $time_now > $offsetStartTime) ||
                            ($time_now == $shiftStartTime) || ($time_now > $shiftStartTime && ($offsetEndTime < $time_now))
                        ) {
                            $attendanceDetail = AttendanceDetail::where('user_id', '=', $user->id)
                                ->whereBetween('check_in', [$startDate, $endDate])
                                ->get();
                        } else {
                            $subday_date = Carbon::now(config('settings.time_zone'))->subday()->toDateString();
                            $startDateForSubday = Carbon::parse($subday_date . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                            $endDateForSubday = Carbon::parse(Carbon::parse($subday_date)->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                            $attendanceDetail = AttendanceDetail::where('user_id', '=', $user->id)
                                ->whereBetween('check_in', [$startDateForSubday, $endDateForSubday])
                                ->get();
                        }
                    }
                } else {
                    //  $query->whereDate('check_in', '=', $currentDateTime->toDateString());
                    //  $attendanceDetail = $query->get();
                    $startDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                    $endDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                    $query->whereBetween('check_in', [$startDate, $endDate]);
                    $attendanceDetail = $query->get();
                }
            }
            if (!empty($attendanceDetail)) {
                foreach ($attendanceDetail as $value) {
                    if (isset($value->user_id)) {
                        $this->check_in = $value->check_in;
                        $this->check_out = $value->check_out;
                    }
                }
            }
        } else {
            return; // user/userdetail not entered in AMS
        }
    }
    public function teamStatus(Request $request,String $requesttype="api",int $opcode=0)
    {
        $title = '/Dashboard';
        $roles = Role::all();
        $teams = Team::all();
        $teamId = $request->teamId;
        $team_details_hashmap = array();
       
        if ($teamId == 0) {
            $this->getAttendanceDetails($request);
            $this->usersOnLeave();
        } else {
            $this->getTeamAttendanceDetails($teamId);
            $this->teamUsersOnLeave($teamId);
        }
        if($opcode==0){
            //users
            $team_details_hashmap['noCheckinUsers'] =  $this->noCheckinUsers;
            $team_details_hashmap['lateCheckinUsers'] = $this->lateCheckinUsers;
            $team_details_hashmap['availableUsers'] = $this->avialable_users;
            $team_details_hashmap['earlyCheckoutUsers'] = $this->earlyCheckoutUsers;
            $team_details_hashmap['usersOnWeekend'] = $this->usersOnWeekend;
            $team_details_hashmap['usersOnLeave'] = $this->usersOnLeave;
            
        }
        $team_details_hashmap["status"] = 200;
        //counts
        $team_details_hashmap['totalEmployees'] = $this->totalEmployees;
        $team_details_hashmap['noCheckinUsersCount'] = $this->noCheckinUsersCount;
        //late checkin users
        $team_details_hashmap['lateCheckinCount'] = $this->lateCheckinCount;
        //available users
        $team_details_hashmap['totalPresent'] = $this->totalPresent;
        //early checkout users
        $team_details_hashmap['earlyCheckoutCount'] = $this->earlyCheckoutCount;
        //user on weekend
        $team_details_hashmap['usersOnWeekendCount'] = $this->usersOnWeekendCount;
        //on leave
        $team_details_hashmap['usersOnLeaveCount'] = $this->usersOnLeaveCount;
        if($requesttype=="web"){
            return $team_details_hashmap;
        }
        elseif ($requesttype=="api")
        {
            if($opcode==1) {
                return $team_details_hashmap;
            }
            return json_encode($team_details_hashmap);
        }
    }
    public function teamSelected(Request $request)
    {
        $title = '/Dashboard';
        $roles = Role::all();
        $teams = Team::all();
        $team_details = $this->teamStatus($request,"web");
        $totalEmployees = $team_details['totalEmployees'];
        $noCheckinUsers =  $team_details['noCheckinUsers'];
        $noCheckinUsersCount = $team_details['noCheckinUsersCount'];
        //late checkin users
        $lateCheckinUsers = $team_details['lateCheckinUsers'];
        $lateCheckinCount = $team_details['lateCheckinCount'];
        //available users
        $totalPresent = $team_details['totalPresent'];
        $avialableUsers = $team_details['avialable_users'];
        //early checkout users
        $earlyCheckoutUsers = $team_details['earlyCheckoutUsers'];
        $earlyCheckoutCount = $team_details['earlyCheckoutCount'];
        //user on weekend
        $usersOnWeekend = $team_details['usersOnWeekend'];
        $usersOnWeekendCount = $team_details['usersOnWeekendCount'];
        //on leave
        $usersOnLeave = $team_details['usersOnLeave'];
        $usersOnLeaveCount = $team_details['usersOnLeaveCount'];
        return view(
            'dashboard.topFourSection',
            compact(
                'title',
                'roles',
                'teams',
                'totalPresent',
                'avialableUsers',
                'lateCheckinUsers',
                'totalEmployees',
                'lateCheckinCount',
                'earlyCheckoutUsers',
                'earlyCheckoutCount',
                'noCheckinUsers',
                'noCheckinUsersCount',
                'usersOnLeave',
                'usersOnLeaveCount',
                'usersOnWeekend',
                'usersOnWeekendCount'
            )
        );
    }
    public function getTeamAttendanceDetails($teamId, $id)
    {
        $users = User::all();
        $currentTime = Carbon::now('UTC')->toTimeString();
        $currentDate = Carbon::now('UTC')->toDateString();
        $startDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $currentTimeWithTimezone = Carbon::now(config('settings.time_zone'))->toTimeString();
        $currentDateWithTimezone = Carbon::now(config('settings.time_zone'))->toDateString();
        $holiday = Holiday::where('date', $currentDateWithTimezone)->first();
        $noCheckinUsers = [];
        $available_users = [];
        $lateCheckinUsers = [];
        $user_attendance = [1];
        $usersOnWeekend = [];
        $earlyCheckout = 0;
        $earlyCheckoutUsers = [];
        $totalEmployees = 0;
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($id);
        $valUser = AttendanceHelper::getAttendanceUser($id);
        $attendanceValue = null;
        if ($valUser) {
            $attendanceValue = $valUser;
        } elseif ($valTeam) {
            $attendanceValue = $valTeam;
        } elseif ($val) {
            $attendanceValue = $val;
        } else {
            $attendanceValue = null;
        }
        foreach ($users as $key => $user) {
            if (!empty($user->userdetail)) {
                $userWeeklyOff = UserWeeklyOff::where('user_id', $user->id)
                    ->whereBetween('created_at', [$startDate, $endDate])
                    ->where('weekly_off', 1)->first();
                // dd($userWeeklyOff);
                //check user on leave
                $holidayIds = HolidayHelper::getholidayList($user->id);
                $holiday = Holiday::where('date', $currentDateWithTimezone)->whereIn('id', $holidayIds)->first();
                $user_leave = ApplyLeave::where('user_id', $user->id)
                    ->where('from_date', '<=', $currentDateWithTimezone)
                    ->where('to_date', '>=', $currentDateWithTimezone)
                    ->where('status', 'Approve')
                    ->first();
                // $userAttendanceTeam = $user->userdetail->teams;
                // foreach ($userAttendanceTeam as $userTeam) {
                //     $userInTeam = $userTeam->team;
                //     $userInTeamId = $userTeam->id;
                // }
                //primary team id
                $userInTeamId = $user->userdetail->primary_team_id;
                //primary team name
                $userInTeam = $user->userdetail->primaryTeamName->team;
                if ($userInTeamId == $teamId) {
                    $totalEmployees = $totalEmployees + 1;
                    //get shift details
                    $shift = GetShiftDetailHelper::getShiftDetail($user->id, $startDate, $endDate);
                    if ($shift != null) {
                        $shiftStartTime = $shift['shiftStartTime'];
                        $shiftEndTime = $shift['shiftEndTime'];
                        //$bufferTime =  $shift['bufferTime'];
                        $bufferCheckinTime = $shift['bufferCheckinTime'];
                        $bufferCheckoutTime = $shift['bufferCheckoutTime'];
                        $bufferCheckinSecs = strtotime($bufferCheckinTime) - strtotime("00:00:00");
                        $bufferCheckoutSecs = strtotime($bufferCheckoutTime) - strtotime("00:00:00");
                        $timeWithBuffer = date("H:i:s", strtotime($shiftStartTime) + $bufferCheckinSecs);
                        $shiftEndTimeWithBuffer = date("H:i:s", strtotime($shiftEndTime) + $bufferCheckoutSecs);
                        //time for early checkout
                        $timeWithBuffer_earlyCheckout = date("H:i:s", strtotime($shiftEndTime));
                        $offsetStartTime = Carbon::parse($shiftStartTime, config('settings.time_zone'));
                        $offsetStartTime = $offsetStartTime->subHours(2)->toTimeString();
                        $offsetEndTime = Carbon::parse($shiftEndTimeWithBuffer, config('settings.time_zone'));
                        $offsetEndTime = $offsetEndTime->addHours(2)->toTimeString();
                        $time = Carbon::now(config('settings.time_zone'));
                        $day = $time->day + 1;
                        //set time to shift start time
                        $setShiftStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $time->year . '-' . $time->month . '-' . $time->day . ' ' . $shiftStartTime, config('settings.time_zone'));
                        //set time to next day 12am
                        $set12am = Carbon::createFromFormat('Y-m-d H:i:s', $time->year . '-' . $time->month . '-' . $day . ' 00:00:00', config('settings.time_zone'));
                        if ($shiftStartTime > $shiftEndTime) // to check if the shift ends the next day
                        {
                            //$subday_date_time = Carbon::now('UTC')->toDateString();
                            //sub day start and end time for timezone
                            $subdayStartDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->subDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                            $subdayEndDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                            $subdayWithTimezone = Carbon::now(config('settings.time_zone'))->subday()->toDateString();
                            //if user is on leave
                            $userOnLeaveSubday = ApplyLeave::where('from_date', '<=', $subdayWithTimezone)
                                ->where('to_date', '>=', $subdayWithTimezone)
                                ->where('status', 'Approve')
                                ->where('user_id', $user->id)
                                ->first();
                            //check holiday
                            $holidayIds = HolidayHelper::getholidayList($user->id);
                            $holidaySubday = Holiday::where('date', $subdayWithTimezone)->whereIn('id', $holidayIds)->first();
                            //no checkin
                            $userWeeklyOffSubday = UserWeeklyOff::where('user_id', $user->id)
                                ->whereBetween('created_at', [$subdayStartDate, $subdayEndDate])
                                ->where('weekly_off', 1)->first();
                            //check holiday
                            //no checkin
                            // check user is on leave yesterday and check current time is not between shift start time and morning 00:00 && before shift time
                            if (!$time->between($setShiftStartTime, $set12am, true) && $currentTimeWithTimezone < $shiftEndTimeWithBuffer) {
                                if (empty($userWeeklyOffSubday) && empty($userOnLeaveSubday) && empty($holidaySubday)) {
                                    $user_attendance = AttendanceDetail::where('user_id', '=', $user->id)
                                        ->whereBetween('check_in', [$subdayStartDate, $subdayEndDate])
                                        ->first();
                                } else {
                                    $user_attendance = [1];
                                }
                            } else {
                                if (empty($userWeeklyOff) && empty($user_leave) && empty($holiday)) {
                                    if ($currentTimeWithTimezone > $timeWithBuffer) {
                                        $user_attendance = AttendanceDetail::where('user_id', $user->id)
                                            ->whereBetween('check_in', [$startDate, $endDate])
                                            ->first();
                                    } else {
                                        $user_attendance = [1];
                                    }
                                } else {
                                    $user_attendance = [1];
                                }
                            }
                            //avialble user
                            if (!$time->between($offsetStartTime, $set12am, true) && $currentTimeWithTimezone < $offsetEndTime) {
                                //check if user is available
                                $availableUsersAttendance = AttendanceDetail::where('user_id', $user->id)
                                    ->whereBetween('check_in', [$subdayStartDate, $subdayEndDate])
                                    ->where('check_out', '=', NULL)->first();
                            } else {
                                //check if user is available
                                $availableUsersAttendance = AttendanceDetail::where('user_id', $user->id)
                                    ->whereBetween('check_in', [$startDate, $endDate])
                                    ->where('check_out', '=', NULL)->first();
                            }
                            //early checkout
                            // check current time is not between shift start time and morning 00:00 && before end time + 2 hours
                            if (!$time->between($offsetStartTime, $set12am, true) && $currentTimeWithTimezone < $offsetEndTime) {
                                $earlyCheckouAtttendanceDetail = AttendanceDetail::where('user_id', $user->id)
                                    ->whereBetween('check_in', [$subdayStartDate, $subdayEndDate])
                                    ->first();
                                if (isset($earlyCheckouAtttendanceDetail->check_out)) {
                                    $checkOutTime = Carbon::parse($earlyCheckouAtttendanceDetail->check_out, config('app.timezone'));
                                    $checkOutTime->setTimezone(Config('settings.time_zone'));
                                    $checkOutTime = Carbon::parse($checkOutTime)->toTimeString(); //user checkout time
                                    //$checkOutTime = date(Config('settings.time_format'), strtotime($checkOutTime));
                                } else {
                                    $checkOutTime = null;
                                }
                                if ($checkOutTime != null && ($checkOutTime < $timeWithBuffer_earlyCheckout || Carbon::parse($checkOutTime)->between($offsetStartTime, $set12am, true))) {
                                    $earlyCheckout = 1;
                                } else {
                                    $earlyCheckout = 0;
                                }
                            } else {
                                //dd($attendance);
                                $earlyCheckouAtttendanceDetail = AttendanceDetail::where('user_id', $user->id)
                                    ->whereBetween('check_in', [$startDate, $endDate])
                                    ->first();
                                if (isset($earlyCheckouAtttendanceDetail->check_out)) {
                                    $checkOutTime = Carbon::parse($earlyCheckouAtttendanceDetail->check_out, config('app.timezone'));
                                    $checkOutTime->setTimezone(Config('settings.time_zone'));
                                    $checkOutTime = Carbon::parse($checkOutTime)->toTimeString(); //user checkout time
                                    //$checkOutTime = date(Config('settings.time_format'), strtotime($checkOutTime));
                                } else {
                                    $checkOutTime = null;
                                }
                                if ($checkOutTime != NULL && Carbon::parse($checkOutTime)->between($offsetStartTime, $set12am, true)) {
                                    $earlyCheckout = 1;
                                } else {
                                    $earlyCheckout = 0;
                                }
                            }
                        } else {
                            if (empty($userWeeklyOff) && empty($user_leave) && empty($holiday)) {
                                if ($currentTimeWithTimezone > $timeWithBuffer) {
                                    $user_attendance = AttendanceDetail::where('user_id', $user->id)
                                        ->whereBetween('check_in', [$startDate, $endDate])
                                        ->first();
                                } else {
                                    $user_attendance = [1];
                                }
                            } else {
                                $user_attendance = [1];
                            }
                            //check if user is available
                            $availableUsersAttendance = AttendanceDetail::where('user_id', $user->id)
                                ->whereBetween('check_in', [$startDate, $endDate])
                                ->where('check_out', '=', NULL)->first();
                            $earlyCheckouAtttendanceDetail = AttendanceDetail::where('user_id', $user->id)
                                ->whereBetween('check_in', [$startDate, $endDate])
                                ->first();
                            if (isset($earlyCheckouAtttendanceDetail->check_out)) {
                                $checkOutTime = Carbon::parse($earlyCheckouAtttendanceDetail->check_out, config('app.timezone'));
                                $checkOutTime->setTimezone(Config('settings.time_zone'));
                                $checkOutTime = Carbon::parse($checkOutTime)->toTimeString(); //user checkout time
                                //$checkOutTime = date(Config('settings.time_format'), strtotime($checkOutTime));
                            } else {
                                $checkOutTime = null;
                            }
                            if ($checkOutTime != NULL && $checkOutTime < $timeWithBuffer_earlyCheckout) {
                                $earlyCheckout = 1;
                            } else {
                                $earlyCheckout = 0;
                            }
                        }
                        //no checkin
                        if (empty($user_attendance)) {
                            if ($val == "1") {
                                $noCheckinUsers[$key]['id'] = '';
                                $noCheckinUsers[$key]['name'] = '';
                                $noCheckinUsers[$key]['team'] = '';
                            } elseif ($val != "1") {
                                if (empty($attendanceValues)) {
                                    $userIds = User::pluck('id');
                                    $attendanceUserValues = [];
                                    foreach ($userIds as $userId) {
                                        $attendanceMarkUser = userSetting::where('name', 'attendance')
                                            ->where('category', 'User')
                                            ->where('user_id', $userId)
                                            ->first();
                                        if ($attendanceMarkUser) {
                                            $attendanceUserValues[] = $attendanceMarkUser->value;
                                            if ($attendanceMarkUser->value == "1") {
                                                // Exclude this user from $noCheckinUsers
                                                $noCheckinUsers = array_filter($noCheckinUsers, function ($user) use ($userId) {
                                                    return $user['id'] != $userId;
                                                });
                                            } else {
                                                $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                                $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                                $noCheckinUsers[$key]['team'] = $userInTeam;
                                            }
                                        } else {
                                            $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                            $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                            $noCheckinUsers[$key]['team'] = $userInTeam;
                                        }
                                    }
                                }
                                $teamIds = Team::pluck('id');
                                $attendanceValues = [];
                                foreach ($teamIds as $teamId) {
                                    $attendanceMarkTeam = TeamSetting::where('name', 'attendance')
                                        ->where('category', 'Team')
                                        ->where('team_id', $teamId)
                                        ->first();
                                    if ($attendanceMarkTeam) {
                                        $attendanceValues[] = $attendanceMarkTeam->value;
                                        if ($attendanceMarkTeam->value == "1") {
                                            // Exclude all members of this team from $noCheckinUsers
                                            $noCheckinUsers = array_filter($noCheckinUsers, function ($user) use ($teamId) {
                                                return $user['team'] != $teamId;
                                            });
                                        } else {
                                            $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                            $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                            $noCheckinUsers[$key]['team'] = $userInTeam;
                                        }
                                    } else {
                                        $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                        $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                        $noCheckinUsers[$key]['team'] = $userInTeam;
                                    }
                                }
                            } else {
                                $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                $noCheckinUsers[$key]['team'] = $userInTeam;
                            }
                        }
                        //early checkout
                        if ($earlyCheckout == 1) {
                            $earlyCheckoutUsers[$key]['id'] = $user->userdetail->user_id;
                            $earlyCheckoutUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                            $earlyCheckoutUsers[$key]['time'] = date(Config('settings.time_format'), strtotime($checkOutTime));
                        }
                        if (!empty($availableUsersAttendance)) {
                            $userId = $user->userdetail->user_id;
                            $userDetails = AttendanceDetail::where('user_id',$userId)
                                                            ->latest('created_at')
                                                            ->first();
                            $userCheckin = $userDetails->check_in;
                            $userCheckin = Carbon::parse($userCheckin, config('app.timezone'));
                            $userCheckin->setTimezone(Config('settings.time_zone'));
                            $userCheckin = Carbon::parse($userCheckin)->toTimeString();
                            $userCheckout = $userDetails->check_out;
                            if($userCheckout != null){
                            $userCheckout = Carbon::parse($userCheckout, config('app.timezone'));
                            $userCheckout->setTimezone(Config('settings.time_zone'));
                            $userCheckout = Carbon::parse($userCheckout)->toTimeString();
                            }
                            $userProfilePicDetail = User::where('id',$userId)
                                                ->get();
                                            
                            if(!empty($userProfilePicDetail->profile_pic)) 
                            {         
                            $userProfilePic = $userProfilePicDetail->profile_pic;
                            }
                            else
                            {
                                
                            $avatarPic = UserDetail::where('user_id',$userId)
                                                    ->value('gender');
                           
                            if($avatarPic == 'Male')
                            {
                                $userProfilePic = "global_assets/images/favicon_io/default-avatar-boy.png";
                            }
                            else{
                                $userProfilePic = "global_assets/images/favicon_io/default-avatar-girl.png";
                            }
                            }
                            $available_users[$key]['profilePic'] = $userProfilePic;
                            $available_users[$key]['id'] = $userId;
                            $available_users[$key]['name'] = $user->name . ' ' . $user->lastName;
                            $available_users[$key]['team'] = $userInTeam;
                            $available_users[$key]['checkin'] = $userCheckin;
                            $available_users[$key]['checkout'] = $userCheckout;
                            if (isset($availableUsersAttendance->check_in)) {
                                $checkInTime = Carbon::parse($availableUsersAttendance->check_in, config('app.timezone'));
                                $checkInTime->setTimezone(Config('settings.time_zone'));
                                $checkInTime = Carbon::parse($checkInTime)->toTimeString(); //user checkin time
                                // $checkInTime = date(Config('settings.time_format'), strtotime($checkInTime));
                            } else {
                                $checkInTime = null;
                            }
                            //late check in
                            if ($checkInTime > $timeWithBuffer) {
                                $lateCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                $lateCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                $lateCheckinUsers[$key]['time'] = date(Config('settings.time_format'), strtotime($checkInTime));
                            }
                            //user weekly
                            $dateForWeeklyOff = Carbon::parse($availableUsersAttendance->check_in)->setTimezone(config('settings.time_zone'))->toDateString();
                            $startDateForWeeklyOff = Carbon::parse($dateForWeeklyOff . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                            $endDateForWeeklyOff = Carbon::parse(Carbon::parse($availableUsersAttendance->check_in)->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                            $userWeeklyOff = UserWeeklyOff::where('user_id', $user->id)
                                ->whereBetween('created_at', [$startDateForWeeklyOff, $endDateForWeeklyOff])
                                ->where('weekly_off', 1)->first();
                            if (!empty($userWeeklyOff)) {
                                $usersOnWeekend[$key]['id'] = $user->userdetail->user_id;
                                $usersOnWeekend[$key]['name'] = $user->name . ' ' . $user->lastName;
                                $usersOnWeekend[$key]['team'] = $userInTeam;
                            }
                        }
                    }
                }
            }
        }
        //total users
        $this->totalEmployees = $totalEmployees;
        //no check in users
        $this->noCheckinUsers = $noCheckinUsers;
        $this->noCheckinUsersCount = count($noCheckinUsers);
        //available users
        $this->avialable_users = $available_users;
        $this->totalPresent = count($available_users);
        //late check in users
        $this->lateCheckinUsers = $lateCheckinUsers;
        $this->lateCheckinCount = count($lateCheckinUsers);
        //early check out users
        $this->earlyCheckoutUsers = $earlyCheckoutUsers;
        $this->earlyCheckoutCount = count($earlyCheckoutUsers);
        //user on weekend
        $this->usersOnWeekend = $usersOnWeekend;
        $this->usersOnWeekendCount = count($usersOnWeekend);
    }
    public function getAttendanceDetails(Request $request)
    {
        $users = User::all();
        $noCheckinUsers = [];
        $currentTime = Carbon::now('UTC')->toTimeString();
        $currentDate = Carbon::now('UTC')->toDateString();
        $startDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $currentTimeWithTimezone = Carbon::now(config('settings.time_zone'))->toTimeString();
        $currentDateWithTimezone = Carbon::now(config('settings.time_zone'))->toDateString();
        $holiday = Holiday::where('date', $currentDateWithTimezone)->first();
        $available_users = [];
        $lateCheckinUsers = [];
        $user_attendance = [1];
        $usersOnWeekend = [];
        $earlyCheckout = 0;
        $earlyCheckoutUsers = [];
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($request);
        $valUser = AttendanceHelper::getAttendanceUser($request);
        $attendanceValue = null;
        if ($valUser) {
            $attendanceValue = $valUser;
        } elseif ($valTeam) {
            $attendanceValue = $valTeam;
        } elseif ($val) {
            $attendanceValue = $val;
        } else {
            $attendanceValue = null;
        }
        foreach ($users as $key => $user) {
            if (!empty($user->userdetail)) {
                $userWeeklyOff = UserWeeklyOff::where('user_id', $user->id)
                    ->whereBetween('created_at', [$startDate, $endDate])
                    ->where('weekly_off', 1)->first();
                // dd($userWeeklyOff);
                //check user on leave
                $user_leave = ApplyLeave::where('user_id', $user->id)
                    ->where('from_date', '<=', $currentDateWithTimezone)
                    ->where('to_date', '>=', $currentDateWithTimezone)
                    ->where('status', 'Approve')
                    ->first();
                //get shift details
                $shift = GetShiftDetailHelper::getShiftDetail($user->id, $startDate, $endDate);
                if ($shift != null) {
                    $shiftStartTime = $shift['shiftStartTime'];
                    $shiftEndTime = $shift['shiftEndTime'];
                    //buffer time for shift check in
                    $bufferCheckinTime = $shift['bufferCheckinTime'];
                    //buffer time for shift checkout
                    $bufferCheckoutTime = $shift['bufferCheckoutTime'];
                    $bufferCheckinSecs = strtotime($bufferCheckinTime) - strtotime("00:00:00");
                    $bufferCheckoutSecs = strtotime($bufferCheckoutTime) - strtotime("00:00:00");
                    $timeWithBuffer = date("H:i:s", strtotime($shiftStartTime) + $bufferCheckinSecs);
                    $shiftEndTimeWithBuffer = date("H:i:s", strtotime($shiftEndTime) + $bufferCheckoutSecs);
                    //time for early checkout
                    $timeWithBuffer_earlyCheckout = date("H:i:s", strtotime($shiftEndTime));
                    //offset start time is 2 hours before shift  start time
                    $offsetStartTime = Carbon::parse($shiftStartTime, config('settings.time_zone'));
                    $offsetStartTime = $offsetStartTime->subHours(2)->toTimeString();
                    //offset end time is 2 hours after shift end time
                    $offsetEndTime = Carbon::parse($shiftEndTimeWithBuffer, config('settings.time_zone'));
                    $offsetEndTime = $offsetEndTime->addHours(2)->toTimeString();
                    $time = Carbon::now(config('settings.time_zone'));
                    $day = $time->day + 1;
                    //set time to shift start time
                    $setShiftStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $time->year . '-' . $time->month . '-' . $time->day . ' ' . $shiftStartTime, config('settings.time_zone'));
                    //set time to next day 12am
                    $set12am = Carbon::createFromFormat('Y-m-d H:i:s', $time->year . '-' . $time->month . '-' . $day . ' 00:00:00', config('settings.time_zone'));
                    if ($shiftStartTime > $shiftEndTime) // to check if the shift ends the next day
                    {
                        //$subday_date_time = Carbon::now('UTC')->toDateString();
                        //sub day start and end time for timezone
                        $subdayStartDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->subDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                        $subdayEndDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                        $subdayWithTimezone = Carbon::now(config('settings.time_zone'))->subday()->toDateString();
                        //if user is on leave
                        $userOnLeaveSubday = ApplyLeave::where('from_date', '<=', $subdayWithTimezone)
                            ->where('to_date', '>=', $subdayWithTimezone)
                            ->where('status', 'Approve')
                            ->where('user_id', $user->id)
                            ->first();
                        //check holiday
                        $holidayIds = HolidayHelper::getholidayList($user->id);
                        $holidaySubday = Holiday::where('date', $subdayWithTimezone)->whereIn('id', $holidayIds)->first();
                        //no checkin
                        $userWeeklyOffSubday = UserWeeklyOff::where('user_id', $user->id)
                            ->whereBetween('created_at', [$subdayStartDate, $subdayEndDate])
                            ->where('weekly_off', 1)->first();
                        //no checkin
                        // check user is on leave yesterday and check current time is not between shift start time and morning 00:00 && before shift time
                        if (!$time->between($setShiftStartTime, $set12am, true) && $currentTimeWithTimezone < $shiftEndTimeWithBuffer) {
                            if (empty($userWeeklyOffSubday) && empty($userOnLeaveSubday) && empty($holidaySubday)) {
                                $user_attendance = AttendanceDetail::where('user_id', '=', $user->id)
                                    ->whereBetween('check_in', [$subdayStartDate, $subdayEndDate])
                                    ->first();
                            } else {
                                $user_attendance = [1];
                            }
                        } else {
                            if (empty($userWeeklyOff) && empty($user_leave) && empty($holiday)) {
                                if ($currentTimeWithTimezone > $timeWithBuffer) {
                                    $user_attendance = AttendanceDetail::where('user_id', $user->id)
                                        ->whereBetween('check_in', [$startDate, $endDate])
                                        ->first();
                                } else {
                                    $user_attendance = [1];
                                }
                            } else {
                                $user_attendance = [1];
                            }
                        }
                        //avialble user
                        if (!$time->between($offsetStartTime, $set12am, true) && $currentTimeWithTimezone < $offsetEndTime) {
                            //check if user is available
                            $availableUsersAttendance = AttendanceDetail::where('user_id', $user->id)
                                ->whereBetween('check_in', [$subdayStartDate, $subdayEndDate])
                                ->where('check_out', '=', NULL)->first();
                        } else {
                            //check if user is available
                            $availableUsersAttendance = AttendanceDetail::where('user_id', $user->id)
                                ->whereBetween('check_in', [$startDate, $endDate])
                                ->where('check_out', '=', NULL)->first();
                        }
                        //early checkout
                        // check current time is not between shift start time and morning 00:00 && before end time + 2 hours
                        if (!$time->between($offsetStartTime, $set12am, true) && $currentTimeWithTimezone < $offsetEndTime) {
                            $earlyCheckouAtttendanceDetail = AttendanceDetail::where('user_id', $user->id)
                                ->whereBetween('check_in', [$subdayStartDate, $subdayEndDate])
                                ->first();
                            if (isset($earlyCheckouAtttendanceDetail->check_out)) {
                                $checkOutTime = Carbon::parse($earlyCheckouAtttendanceDetail->check_out, config('app.timezone'));
                                $checkOutTime->setTimezone(Config('settings.time_zone'));
                                $checkOutTime = Carbon::parse($checkOutTime)->toTimeString(); //user checkout time
                                //$checkOutTime = date(Config('settings.time_format'), strtotime($checkOutTime));
                            } else {
                                $checkOutTime = null;
                            }
                            if ($checkOutTime != null && ($checkOutTime < $timeWithBuffer_earlyCheckout || Carbon::parse($checkOutTime)->between($offsetStartTime, $set12am, true))) {
                                $earlyCheckout = 1;
                            } else {
                                $earlyCheckout = 0;
                            }
                        } else {
                            //dd($attendance);
                            $earlyCheckouAtttendanceDetail = AttendanceDetail::where('user_id', $user->id)
                                ->whereBetween('check_in', [$startDate, $endDate])
                                ->first();
                            if (isset($earlyCheckouAtttendanceDetail->check_out)) {
                                $checkOutTime = Carbon::parse($earlyCheckouAtttendanceDetail->check_out, config('app.timezone'));
                                $checkOutTime->setTimezone(Config('settings.time_zone'));
                                $checkOutTime = Carbon::parse($checkOutTime)->toTimeString(); //user checkout time
                                //$checkOutTime = date(Config('settings.time_format'), strtotime($checkOutTime));
                            } else {
                                $checkOutTime = null;
                            }
                            if ($checkOutTime != NULL && Carbon::parse($checkOutTime)->between($offsetStartTime, $set12am, true)) {
                                $earlyCheckout = 1;
                            } else {
                                $earlyCheckout = 0;
                            }
                        }
                    } else {
                        if (empty($userWeeklyOff) && empty($user_leave) && empty($holiday)) {
                            if ($currentTimeWithTimezone > $timeWithBuffer) {
                                $user_attendance = AttendanceDetail::where('user_id', $user->id)
                                    ->whereBetween('check_in', [$startDate, $endDate])
                                    ->first();
                            } else {
                                $user_attendance = [1];
                            }
                        } else {
                            $user_attendance = [1];
                        }
                        //check if user is available
                        $availableUsersAttendance = AttendanceDetail::where('user_id', $user->id)
                            ->whereBetween('check_in', [$startDate, $endDate])
                            ->where('check_out', '=', NULL)->first();
                        $earlyCheckouAtttendanceDetail = AttendanceDetail::where('user_id', $user->id)
                            ->whereBetween('check_in', [$startDate, $endDate])
                            ->first();
                        if (isset($earlyCheckouAtttendanceDetail->check_out)) {
                            $checkOutTime = Carbon::parse($earlyCheckouAtttendanceDetail->check_out, config('app.timezone'));
                            $checkOutTime->setTimezone(Config('settings.time_zone'));
                            $checkOutTime = Carbon::parse($checkOutTime)->toTimeString(); //user checkout time
                            //$checkOutTime = date(Config('settings.time_format'), strtotime($checkOutTime));
                        } else {
                            $checkOutTime = null;
                        }
                        if ($checkOutTime != NULL && $checkOutTime < $timeWithBuffer_earlyCheckout) {
                            $earlyCheckout = 1;
                        } else {
                            $earlyCheckout = 0;
                        }
                    }
                    // $userAttendanceTeam = $user->userdetail->teams;
                    //     foreach ($userAttendanceTeam as $userTeam) {
                    //         $userInTeam = $userTeam->team;
                    //     }
                    //primary team name
                    $userInTeam = $user->userdetail->primaryTeamName->team;
                    //no checkin
                    // if (empty($user_attendance)) {
                    //     $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                    //     $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                    //     $noCheckinUsers[$key]['team'] = $userInTeam;
                    // }
                    if (empty($user_attendance)) {
                        if ($val == "1") {
                            $noCheckinUsers[$key]['profile_pic'] = '';
                            $noCheckinUsers[$key]['id'] = '';
                            $noCheckinUsers[$key]['name'] = '';
                            $noCheckinUsers[$key]['team'] = '';
                        } elseif ($val != "1") {
                            // if (empty($attendanceValues)) {
                            $userIds = User::pluck('id');
                            $attendanceUserValues = [];
                            foreach ($userIds as $userId) {
                                $attendanceMarkUser = userSetting::where('name', 'attendance')
                                    ->where('category', 'User')
                                    ->where('user_id', $userId)
                                    ->first();
                                if ($attendanceMarkUser) {
                                    $attendanceUserValues[] = $attendanceMarkUser->value;
                                    if ($attendanceMarkUser->value == "1") {
                                        // Exclude this user from $noCheckinUsers
                                        $noCheckinUsers = array_filter($noCheckinUsers, function ($user) use ($userId) {
                                            return $user['id'] != $userId;
                                        });
                                    } else {
                                        $noCheckinUsers[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                                        $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                        $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                        $noCheckinUsers[$key]['team'] = $userInTeam;
                                    }
                                } else {
                                    $noCheckinUsers[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                                    $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                    $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                    $noCheckinUsers[$key]['team'] = $userInTeam;
                                }
                            }
                            // }
                            $teamIds = Team::pluck('id');
                            $attendanceValues = [];
                            foreach ($teamIds as $teamId) {
                                $attendanceMarkTeam = TeamSetting::where('name', 'attendance')
                                    ->where('category', 'Team')
                                    ->where('team_id', $teamId)
                                    ->first();
                                if ($attendanceMarkTeam) {
                                    $attendanceValues[] = $attendanceMarkTeam->value;
                                    if ($attendanceMarkTeam->value == "1") {
                                        // Exclude all members of this team from $noCheckinUsers
                                        $noCheckinUsers = array_filter($noCheckinUsers, function ($user) use ($teamId) {
                                            return $user['team'] != $teamId;
                                        });
                                    } else {
                                        $noCheckinUsers[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                                        $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                        $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                        $noCheckinUsers[$key]['team'] = $userInTeam;
                                    }
                                } else {
                                    $noCheckinUsers[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                                    $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                                    $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                                    $noCheckinUsers[$key]['team'] = $userInTeam;
                                }
                            }
                        } else {
                            $noCheckinUsers[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                            $noCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                            $noCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                            $noCheckinUsers[$key]['team'] = $userInTeam;
                        }
                    }
                    //early checkout
                    if ($earlyCheckout == 1) {
                        $earlyCheckoutUsers[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                        $earlyCheckoutUsers[$key]['id'] = $user->userdetail->user_id;
                        $earlyCheckoutUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                        $earlyCheckoutUsers[$key]['time'] = date(Config('settings.time_format'), strtotime($checkOutTime));
                    }
                    if (!empty($availableUsersAttendance)) {
                        $userId = $user->userdetail->user_id;
                        $userDetails = AttendanceDetail::where('user_id',$userId)
                                                        ->latest('created_at')
                                                        ->first();
                        $userCheckin = $userDetails->check_in;
                        $userCheckin = Carbon::parse($userCheckin, config('app.timezone'));
                        $userCheckin->setTimezone(Config('settings.time_zone'));
                        $userCheckin = Carbon::parse($userCheckin)->toTimeString();
                        $userCheckout = $userDetails->check_out;
                        if($userCheckout != null){
                        $userCheckout = Carbon::parse($userCheckout, config('app.timezone'));
                        $userCheckout->setTimezone(Config('settings.time_zone'));
                        $userCheckout = Carbon::parse($userCheckout)->toTimeString();
                        }
                        $available_users[$key]['profilePic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                        $available_users[$key]['id'] = $user->userdetail->user_id;
                        $available_users[$key]['name'] = $user->name . ' ' . $user->lastName;
                        $available_users[$key]['team'] = $userInTeam;
                        $available_users[$key]['checkin'] = $userCheckin;
                        $available_users[$key]['checkout'] = $userCheckout;
                        if (isset($availableUsersAttendance->check_in)) {
                            $checkInTime = Carbon::parse($availableUsersAttendance->check_in, config('app.timezone'));
                            $checkInTime->setTimezone(Config('settings.time_zone'));
                            $checkInTime = Carbon::parse($checkInTime)->toTimeString(); //user checkin time
                            // $checkInTime = date(Config('settings.time_format'), strtotime($checkInTime));
                        } else {
                            $checkInTime = null;
                        }
                        //late check in
                        if ($checkInTime > $timeWithBuffer) {
                            $lateCheckinUsers[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                            $lateCheckinUsers[$key]['id'] = $user->userdetail->user_id;
                            $lateCheckinUsers[$key]['name'] = $user->name . ' ' . $user->lastName;
                            $lateCheckinUsers[$key]['time'] = date(Config('settings.time_format'), strtotime($checkInTime));
                        }
                        //user weekly
                        $dateForWeeklyOff = Carbon::parse($availableUsersAttendance->check_in)->setTimezone(config('settings.time_zone'))->toDateString();
                        $startDateForWeeklyOff = Carbon::parse($dateForWeeklyOff . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                        $endDateForWeeklyOff = Carbon::parse(Carbon::parse($availableUsersAttendance->check_in)->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
                        $userWeeklyOff = UserWeeklyOff::where('user_id', $user->id)
                            ->whereBetween('created_at', [$startDateForWeeklyOff, $endDateForWeeklyOff])
                            ->where('weekly_off', 1)->first();
                        if (!empty($userWeeklyOff)) {
                            $usersOnWeekend[$key]['profile_pic'] = $this->getProfilePicturePath($user->userdetail->user_id);
                            $usersOnWeekend[$key]['id'] = $user->userdetail->user_id;
                            $usersOnWeekend[$key]['name'] = $user->name . ' ' . $user->lastName;
                            $usersOnWeekend[$key]['team'] = $userInTeam;
                        }
                    }
                }
            }
        }
        //total users
        $this->totalEmployees = count($users);
        //no check in users
        $this->noCheckinUsers = $noCheckinUsers;
        $this->noCheckinUsersCount = count($noCheckinUsers);
        //available users
        $this->avialable_users = $available_users;
        $this->totalPresent = count($available_users);
        //late check in users
        $this->lateCheckinUsers = $lateCheckinUsers;
        $this->lateCheckinCount = count($lateCheckinUsers);
        //early check out users
        $this->earlyCheckoutUsers = $earlyCheckoutUsers;
        $this->earlyCheckoutCount = count($earlyCheckoutUsers);
        //user on weekend
        $this->usersOnWeekend = $usersOnWeekend;
        $this->usersOnWeekendCount = count($usersOnWeekend);
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function createRole($roleName)
    {
        $role = Role::create(['name' => $roleName]);
        $permissions = Permission::get();
        $teams = Team::all();
        return view('administrationForms.dashboard.layout', compact('permissions', 'role', 'teams'));
    }
    public function getProfilePicturePath($userId)
    {
        $userProfilePic = "global_assets/images/favicon_io/default-avatar-boy.png";
        $userProfilePicDetail = User::where('id',"=",$userId)
                                                ->get();
        if(count($userProfilePicDetail) && !empty($userProfilePicDetail[0]->profile_pic)){                    
            $userProfilePic = $userProfilePicDetail[0]->profile_pic;
        }else{
            $avatarPic = UserDetail::where('user_id',$userId)->value('gender');
            if($avatarPic == 'Male'){
                $userProfilePic = "global_assets/images/favicon_io/default-avatar-boy.png";
            }else{
                $userProfilePic = "global_assets/images/favicon_io/default-avatar-girl.png";
            }
        }
        return $userProfilePic;
    }
    public function usersOnLeave()
    {
        $today = Carbon::today(config('settings.time_zone'))->toDateString();
        $user_leaves = User::select('users.*', 'apply_leaves.leave_type as leave_type', 'apply_leaves.half_day_type as half_day_type')
            ->join('apply_leaves', 'users.id', 'apply_leaves.user_id')
            ->where('from_date', '<=', $today)
            ->where('to_date', '>=', $today)
            ->where('status', 'Approve')
            ->get();
        $this->usersOnLeave = $user_leaves;
        $this->usersOnLeaveCount = count($user_leaves);
    }
    //user on leave based on team
    public function teamUsersOnLeave($teamId)
    {
        $today = Carbon::today(config('settings.time_zone'))->toDateString();
        $user_leaves = User::select('users.*', 'apply_leaves.leave_type as leave_type', 'apply_leaves.half_day_type as half_day_type')
            ->join('apply_leaves', 'users.id', 'apply_leaves.user_id')
            ->join('user_details', 'users.id', 'user_details.user_id')
            // ->join('team_user_detail', 'user_details.id', 'team_user_detail.user_detail_id')
            // ->where('team_user_detail.team_id',$teamId)
            ->where('user_details.primary_team_id', $teamId)
            ->where('from_date', '<=', $today)
            ->where('to_date', '>=', $today)
            ->where('status', 'Approve')
            ->get();
        foreach($user_leaves as $user_leave){
            $user_leave["profile_pic"] = "storage/".$user_leave["profile_pic"];
        }    
        $this->usersOnLeave = $user_leaves;
        $this->usersOnLeaveCount = count($user_leaves);
    }
    // load more leave request on dashboard
    public function getLeaveRequest(Request $request,$opcode="web")
    {
          //code is left untouched for web version and the web keyword specifies if the request is for web or api
          $offset = $request->input('offset') ? $request->input('offset') : 0;
          if(strcmp($opcode,"web")==0) {
              $limit = $request->input('limit') ? $request->input('limit') : 5;
          }else{
              $limit = $request->input('limit') ? $request->input('limit') : 100;
          }
        //get leaves, if user is collaborator
        $getCollaboratorLeaves = GetShiftDetailHelper::getCollabratorLeaves('leave');
        // $leave_reports = ApplyLeave::where('status','pending')->with(['user', 'Leave'])->orderBy('created_at','DESC')->skip($offset * $limit)->take($limit)->get();
        //view permissions
        if (auth()->user()->can('View All leave requests')) {
            $leave_reports = ApplyLeave::where('status', 'pending')->with(['user', 'Leave'])->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (auth()->user()->can('View All leave requests of team')) {
            $userIds = GetShiftDetailHelper::getMyteamMembers();
            $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->with(['user', 'Leave'])->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (auth()->user()->can('View All leave requests of assigned employees')) {
            //View All leave requests of assigned employees
            $userIds = GetShiftDetailHelper::getMyReportingEmployees();
            $userIds[] = auth()->user()->id;
            $leave_reports = ApplyLeave::whereIn('user_id', $userIds)->where('status', 'pending')->with(['user', 'Leave'])->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (count($getCollaboratorLeaves) > 0) {
            $leave_reports = ApplyLeave::whereIn('id', $getCollaboratorLeaves)->where('status', 'pending')->with(['user', 'Leave'])->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (auth()->user()->can('View Self Leave Report')) {
            $leave_reports = ApplyLeave::where('status', 'pending')->where('user_id', auth()->user()->id)->with(['user', 'Leave'])->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else {
            $leave_reports = [];
        }
        $leave_data = array();
        $editPermission = false;
        foreach ($leave_reports as $leave_report) {   
            if ($leave_report->user) {
                $leaves = Leave::withTrashed()->where('id', $leave_report->leave_id)->first();
                if($leaves){
                    $from_date = Carbon::parse($leave_report->from_date)->format(config('settings.php_date_format'));
                    $to_date = Carbon::parse($leave_report->to_date)->format(config('settings.php_date_format'));
                    $requested_on = Carbon::parse($leave_report->created_at);
                    $requested_on->setTimezone(config('settings.time_zone'));
                    $requested_on = $requested_on->format(config('settings.php_date_format') . ' H:i:s');
                    $leave_obj['id'] = $leave_report->id;
                    $leave_obj['leave_length'] = $leave_report->leave_length;
                    $leave_obj['reason'] = $leave_report->reason;
                    $leave_obj['spoken_to'] = $leave_report->spoken_to;
                    $leave_obj['from_date'] = $from_date;
                    $leave_obj['to_date'] = $to_date;
                    $leave_obj['is_process'] = $leave_report->status;
                    $leave_obj['user_id'] = $leave_report->user_id;
                    $leave_obj['created_at'] = $leave_report->created_at;
                    $leave_obj['updated_at'] = $leave_report->updated_at;
                    $leave_obj['leave_id'] = $leave_report->leave_id;
                    $leave_obj['status'] = $leave_report->status;
                    $leave_obj['requested_on'] = $requested_on;
                    $leave_obj['leave_type'] = $leave_report->leave_type;
                    $leave_obj['half_day_type'] = $leave_report->half_day_type;
                    $leave_obj['approver_comments'] = $leave_report->approver_comments;
                    $leave_obj['user'] = $leave_report->user;
                    $leave_obj['leave'] = $leave_report->leave;
                    $chatCount = UserRequestDiscuss::where('context_id', '=', $leave_report->id)->get();
                    $leave_obj['chat_count'] = count($chatCount);
                    // $leaves = Leave::where('id', '=', $leave_report->leave_id)->first();
                    $leave_obj['manageleaveurl'] = route("manage-leave-request", $leave_report->id);
                    $leave_obj['leavename'] = $leaves->name;
                    $leave_obj['leaveabbr'] = $leaves->abbr;
                    $leave_obj['leavetype'] = $leaves->type;
                    $user = User::where('id', $leave_report->user->id)->first();
                    $leave_obj['user']['gender'] = $user->userdetail->gender;
                    //user leave discuss
                    $userLeaveDiscuss = UserRequestDiscuss::with(['user', 'user.userdetail'])
                        ->where('module', 'leave')
                        ->where('context_id', $leave_report->id)
                        ->orderBy('id', 'asc')
                        ->get()->toArray();
                    //added collaborators
                    $collaborators = userRequestCollaborator::where('module', 'leave')
                        ->where('context_id', $leave_report->id)
                        ->get();
                    $data = '';
                    $collaboratorsArray = [];
                    if (count($collaborators) > 0) {
                        foreach ($collaborators as $collaborator) {
                            $collaboratorsArray[] = $collaborator->user_id;
                            $user = User::where('id', $collaborator->user_id)->first();
                            if ($user->profile_pic) {
                                $user_image = url('storage/' . $user->profile_pic);
                            } else {
                                if (!empty($user->userdetail)) {
                                    if ($user->userdetail->gender == 'Male') {
                                        $user_image = url("global_assets/images/favicon_io/default-avatar-boy.png");
                                    } else {
                                        $user_image = url("global_assets/images/favicon_io/default-avatar-girl.jpg");
                                    }
                                } else {
                                    $user_image = url("global_assets/images/placeholders/placeholder.jpg");
                                }
                            }
                            $text = "'leave'";
                            $data .= '<div class="col-md-1 remove-collaborator-' . $collaborator->id . '"  style="cursor: pointer;">';
                            $data .= '<a class="boxclose" onclick="removeCollaborator(' . $collaborator->id . ',' . $leave_report->id . ',' . $text . ')"> <i class="icon-close2"></i></a>';
                            $data .= ' <img src="' . $user_image . '" title="' . $user->name . ' ' . $user->lastName . '" class="rounded-circle rounded-border" width="32" height="32" alt="">';
                            $data .= '</div>';
                        }
                    }
                    //Edit permissions
                    if (auth()->user()->can('Edit  All leave requests')) {
                        $editPermission = true;
                    } else if (auth()->user()->can('Edit All leave requests of team')) {
                        if (in_array($leave_report->user_id, GetShiftDetailHelper::getMyteamMembers()->toArray())) {
                            $editPermission = true;
                        } else {
                            $editPermission = false;
                        }
                    } else if (auth()->user()->can('Edit All leave requests of assigned employees')) {
                        if (GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) != 0 ? GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) == auth()->user()->id : GetShiftDetailHelper::checkReportingManagers($leave_report->user_id)) {
                            $editPermission = true;
                        } else {
                            $editPermission = false;
                        }
                    } else {
                        $editPermission = false;
                    }
                    //chat permission and add collaborator permission
                    //check first if user has primary reporting manager, if not then check for secondary managers
                    //if user has primary reporting manager, then add collaborator will show to primary manager only
                    if (GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) != 0 ? GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) == auth()->user()->id : GetShiftDetailHelper::checkReportingManagers($leave_report->user_id)) {
                        $chatPermission = true;
                        $addCollaboratorPermission = true;
                    } else if (auth()->user()->can('View Self Leave Report') && auth()->user()->id == $leave_report->user_id) {
                        //show chat to  applied leave user who has permission for 'View Self Leave Report'
                        $chatPermission = true;
                        $addCollaboratorPermission = false;
                    } else if (in_array(auth()->user()->id, $collaboratorsArray)) {
                        // if user is collaborator, then show chat
                        $chatPermission = true;
                        $addCollaboratorPermission = false;
                    } else {
                        $chatPermission = false;
                        $addCollaboratorPermission = false;
                    }
                    $leave_obj['editPermission'] = $editPermission;
                    $leave_obj['chatPermission'] = $chatPermission;
                    $leave_obj['addCollaboratorPermission'] = $addCollaboratorPermission;
                    $leave_obj['UserLeaveDiscuss'] = $userLeaveDiscuss;
                    $leave_obj['collaborators'] = $data;
                    array_push($leave_data, $leave_obj);
                }
            }
        }
        return array(
            'leave_reports' => $leave_data,
        );
    }
    // load more attendance request on dashboard
    public function getAttendanceRequest(Request $request,$opcode="web")
    {
         //code is left untouched for web version and the opcode specifes if the request is for web or for the flutter api
         $offset = $request->input('offset') ? $request->input('offset') : 0;
         if(strcmp($opcode,"web")==0) {
             $limit = $request->input('limit') ? $request->input('limit') : 4;
         }else{
             $limit = $request->input('limit') ? $request->input('limit') : 100;
         }
        //get leaves, if user is collaborator
        $getCollaboratorAttendance = GetShiftDetailHelper::getCollabratorLeaves('attendance');
        //$request_attendances = UserAttendanceRequests::where('status','pending')->with('user')->orderBy('created_at','DESC')->skip($offset * $limit)->take($limit)->get();
        ///  for Attendance requests 
        if (auth()->user()->can('View All Attendance request')) {
            $request_attendances = UserAttendanceRequests::where('status', 'pending')->with('user')->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (auth()->user()->can('View All Attendance requests of team')) {
            $userIds = GetShiftDetailHelper::getMyteamMembers();
            $request_attendances = UserAttendanceRequests::whereIn('user_id', $userIds)->where('status', 'pending')->with('user')->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (auth()->user()->can('View All Attendance requests of assigned employees')) {
            $userIds = GetShiftDetailHelper::getMyReportingEmployees();
            $userIds[] = auth()->user()->id;
            $request_attendances = UserAttendanceRequests::whereIn('user_id', $userIds)->where('status', 'pending')->with('user')->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (count($getCollaboratorAttendance) > 0) {
            $request_attendances = UserAttendanceRequests::whereIn('id', $getCollaboratorAttendance)->where('status', 'pending')->with('user')->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else if (auth()->user()->can('View Self Attendance Report')) {
            $request_attendances = UserAttendanceRequests::where('status', 'pending')->where('user_id', auth()->user()->id)->with('user')->orderBy('created_at', 'DESC')->skip($offset * $limit)->take($limit)->get();
        } else {
            $request_attendances = [];
        }
        $attendance_data = [];
        $editPermission = false;
        foreach ($request_attendances as $request_attendance) {
            if ($request_attendance->user) {
                $checkInDate = Carbon::parse($request_attendance->check_in);
                $checkInDate->setTimezone(config('settings.time_zone'));
                $checkInDate = $checkInDate->format(config('settings.php_date_format') . ' ' . Config('settings.time_format'));
                if ($request_attendance->check_out == null) {
                    $checkOutDate = '';
                } else {
                    $checkOutDate = Carbon::parse($request_attendance->check_out);
                    $checkOutDate->setTimezone(config('settings.time_zone'));
                    $checkOutDate = $checkOutDate->format(config('settings.php_date_format') . ' ' . Config('settings.time_format'));
                }
                $requested_on = Carbon::parse($request_attendance->created_at);
                $requested_on->setTimezone(config('settings.time_zone'));
                $requested_on = $requested_on->format(config('settings.php_date_format') . ' ' . Config('settings.time_format'));
                $attendance_obj['id'] = $request_attendance->id;
                $attendance_obj['comments'] = $request_attendance->comments;
                $attendance_obj['approver_comments'] = $request_attendance->approver_comments;
                $attendance_obj['status'] = $request_attendance->status;
                $attendance_obj['requested_on'] = $requested_on;
                $attendance_obj['user_id'] = $request_attendance->user_id;
                $attendance_obj['created_at'] = $request_attendance->created_at;
                $attendance_obj['updated_at'] = $request_attendance->updated_at;
                $attendance_obj['check_in'] = $checkInDate;
                $attendance_obj['check_out'] = $checkOutDate;
                $attendance_obj['user'] = $request_attendance->user;
                $chatCount = UserRequestDiscuss::where('context_id', $request_attendance->id)->get();
                $attendance_obj['chat_count'] = count($chatCount);;
                if (isset($request_attendance->user->id)) {
                    $user = User::where('id', $request_attendance->user->id)->first();
                }
                if (isset($user->userdetail)) {
                    $attendance_obj['user']['gender'] = $user->userdetail->gender;
                    $attendance_obj['requested_for'] = $request_attendance->requested_for;
                }
                //user attendance discuss
                $UserAttendanceDiscuss = UserRequestDiscuss::with(['user', 'user.userdetail'])
                    ->where('module', 'attendance')
                    ->where('context_id', $request_attendance->id)
                    ->orderBy('id', 'asc')
                    ->get()->toArray();
                //added collaborators
                $collaborators = userRequestCollaborator::where('module', 'attendance')
                    ->where('context_id', $request_attendance->id)
                    ->get();
                $data = '';
                $collaboratorsArray = [];
                if (count($collaborators) > 0) {
                    foreach ($collaborators as $collaborator) {
                        $collaboratorsArray[] = $collaborator->user_id;
                        $user = User::where('id', $collaborator->user_id)->first();
                        if ($user->profile_pic) {
                            $user_image = url('storage/' . $user->profile_pic);
                        } else {
                            if ($user->userdetail->gender == 'Male') {
                                $user_image = url("global_assets/images/favicon_io/default-avatar-boy.png");
                            } else {
                                $user_image = url("global_assets/images/favicon_io/default-avatar-girl.jpg");
                            }
                        }
                        $text = "'attendance'";
                        $data .= '<div class="col-md-1 remove-collaborator-' . $collaborator->id . '"  style="cursor: pointer;">';
                        $data .= '<a class="boxclose" onclick="removeCollaborator(' . $collaborator->id . ',' . $request_attendance->id . ',' . $text . ')"> <i class="icon-close2"></i></a>';
                        $data .= ' <img src="' . $user_image . '" title="' . $user->name . ' ' . $user->lastName . '" class="rounded-circle rounded-border" width="32" height="32" alt="">';
                        $data .= '</div>';
                    }
                }
                //edit permission
                if (auth()->user()->can('Edit All Attendance request')) {
                    $editPermission = true;
                } else if (auth()->user()->can('Edit All Attendance requests of team')) {
                    if (in_array($request_attendance->user_id, GetShiftDetailHelper::getMyteamMembers()->toArray())) {
                        $editPermission = true;
                    } else {
                        $editPermission = false;
                    }
                } elseif (auth()->user()->can('Edit All Attendance requests of assigned employees')) {
                    if (GetShiftDetailHelper::getPrimaryReportingManager($request_attendance->user_id) != 0 ? GetShiftDetailHelper::getPrimaryReportingManager($request_attendance->user_id) == auth()->user()->id : GetShiftDetailHelper::checkReportingManagers($request_attendance->user_id)) {
                        $editPermission = true;
                    } else {
                        $editPermission = false;
                    }
                } else {
                    $editPermission = false;
                }
                //chat permission
                //check first if user has primary reporting manager, if not then check for secondary managers
                //if user has primary reporting manager, then add collaborator will show to primary manager only
                if (GetShiftDetailHelper::getPrimaryReportingManager($request_attendance->user_id) != 0 ? GetShiftDetailHelper::getPrimaryReportingManager($request_attendance->user_id) == auth()->user()->id : GetShiftDetailHelper::checkReportingManagers($request_attendance->user_id)) {
                    $chatPermission = true;
                    $addCollaboratorPermission = true;
                } else if (auth()->user()->can('View Self Attendance Report') && auth()->user()->id == $request_attendance->user_id) {
                    //show chat to  applied leave user who has permission for 'View Self Leave Report'
                    $chatPermission = true;
                    $addCollaboratorPermission = false;
                } else if (in_array(auth()->user()->id, $collaboratorsArray)) {
                    // if user is collaborator, then show chat
                    $chatPermission = true;
                    $addCollaboratorPermission = false;
                } else {
                    $chatPermission = false;
                    $addCollaboratorPermission = false;
                }
                $attendance_obj['editPermission'] = $editPermission;
                $attendance_obj['chatPermission'] = $chatPermission;
                $attendance_obj['addCollaboratorPermission'] = $addCollaboratorPermission;
                $attendance_obj['UserAttendanceDiscuss'] = $UserAttendanceDiscuss;
                $attendance_obj['collaborators'] = $data;
                array_push($attendance_data, $attendance_obj);
            }    
        }
        return array(
            'request_attendances' => $attendance_data,
        );
    }
    public function lateCheckinEarlyCheckout(Request $request)
    {
        $platforms = PlatformHelper::getPlatformMarkValue($request);
        // dd($platforms);
        $agent = new Agent();
        $platformDetection = $agent->platform();
        if($platformDetection==""){
            $platformDetection = $request->platform;
        }
        if ($platforms == '[""]' ||  $platforms == null) {
            return $this->PlatformCheck($request);
        }
        if ($platformDetection=="Windows" || $platformDetection=="OS X" || $platformDetection=="Linux") {
            if ($platforms == '["Desktop"]') {
                return $this->PlatformCheck($request);
            } elseif ($platforms == '["Mobile"]') {
                return response()->json(
                    [
                        'platform_error' => 1,
                        'status' => 'Warning',
                        'message' => ($request->button == "checkin") ? 'Please check-in using mobile' : 'Please check-out using mobile',
                    ],
                    200
                );
    
            } elseif ($platforms == '["Mobile","Desktop"]')  {
               
                return $this->PlatformCheck($request);
            } 
            // else {
            //     return $this->PlatformCheck($request);
            // }
            // dd('asndkjsahdsahdch');
        } elseif ($platformDetection=="AndroidOS" || $platformDetection=="iOS" || $platformDetection=="extension") {
            if ($platforms == '[""]' ||  $platforms == null) {
                return $this->PlatformCheck($request);
            } elseif ($platforms == '["Mobile"]') {
               
                return $this->PlatformCheck($request);
            } elseif ($platforms == '["Desktop"]') {
               
                return response()->json(
                    [
                        'platform_error' => 1,
                        'status' => 'Warning',
                        'message' => ($request->button == "checkin") ? 'Please check-in using Desktop' : 'Please check-out using Desktop',
                    ],
                    200
                );
            } elseif ($platforms == '["Mobile","Desktop"]') {
              
                return $this->PlatformCheck($request);
            } 
        }
    }
    
    public function PlatformCheck(Request $request)
    {
        //show popup for late checkin based on shift timing
        $earlyCheckoutTime='';
        $currentTime = Carbon::now(config('settings.time_zone'))->toTimeString();
        $lateCheckin = null;
        $earlyCheckout = null;
        $afterShiftTime = null;
        $user = Auth::user();
        $user_id = $user->id;
        $currDate = Carbon::now(config('settings.time_zone'))->toDateString();
        $currDateTime = Carbon::now(config('settings.time_zone'));
        $startDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDate = Carbon::parse(Carbon::now(config('settings.time_zone'))->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $lateCheckinInfo = UserAttendanceRequests::where('user_id', Auth::user()->id)
            ->where('requested_for', 'Late Checkin')
            ->where('status', 'approved')
            ->latest()->first();
        $lateCheckinPendingInfo = UserAttendanceRequests::where('user_id', Auth::user()->id)
            ->where('requested_for', 'Late Checkin')
            ->where('status', 'pending')
            ->latest()->first();
        $checkInValue = AttendanceDetail::where('user_id', '=', Auth::user()->id)
            ->latest('check_in')->first();
        // $latestCheckin = $checkInValue->check_in;
        // $latestCheckinInTimeZone = Carbon::createFromFormat('Y-m-d H:i:s', $latestCheckin, 'UTC')
        //                             ->setTimezone(config('settings.time_zone'));
                if ($checkInValue) {
          $latestCheckin = $checkInValue->check_in;
          $latestCheckinInTimeZone = Carbon::createFromFormat('Y-m-d H:i:s', $latestCheckin, 'UTC')
            ->setTimezone(config('settings.time_zone'));
          $latestCheckinInTimeZoneDate = date("Y-m-d", strtotime($latestCheckinInTimeZone));
        
        } else {
          $latestCheckinInTimeZoneDate = "2023-01-01";
        }
        if (isset($lateCheckinInfo)) {
            $lateCheckinInfo = $lateCheckinInfo->check_in;
            $lateCheckinInfo = Carbon::parse($lateCheckinInfo)->toDateString();
        } else if (isset($lateCheckinPendingInfo)) {
            $lateCheckinPendingInfo = $lateCheckinPendingInfo->check_in;
            $lateCheckinPendingInfo = Carbon::parse($lateCheckinPendingInfo)->toDateString();
        } else {
            $lateCheckinInfo = 0 - 0 - 0;
        }
        if (!empty(Auth::user()->userdetail)) {
            //get shift details
            $shift = GetShiftDetailHelper::getShiftDetail($user->id, $startDate, $endDate);
            // dd();
            if ($shift != null) {
                $shiftStartTime = $shift['shiftStartTime'];
                $shiftEndTime = $shift['shiftEndTime'];
                $bufferCheckinTime = $shift['bufferCheckinTime'];
                $bufferCheckoutTime = $shift['bufferCheckoutTime'];
                $bufferCheckinSecs = strtotime($bufferCheckinTime) - strtotime("00:00:00");
                //buffer time for checkin
                $timeWithBuffer = date("H:i:s", strtotime($shiftStartTime) + $bufferCheckinSecs);
                //for checking early checkout, we use only shift end time
                $shiftEndTimeForEarlyCheckout = date("H:i:s", strtotime($shiftEndTime));
                $bufferCheckoutSecs = strtotime($bufferCheckoutTime) - strtotime("00:00:00");
                $shiftEndTimeWithBuffer = date("H:i:s", strtotime($shiftEndTime) + $bufferCheckoutSecs);
                //offset time for current time is before 2 hours to shift time
                $offsetStartTimeForCheckin = date("H:i:s", strtotime($shiftStartTime) - strtotime("02:00:00"));
                // $latestCheckinInTimeZoneDate = date("Y-m-d", strtotime($latestCheckinInTimeZone));
                //checking current time
                if ($currentTime > $timeWithBuffer) {
                    $earlyCheckoutTime = true;
                    $lateCheckin = true;
                    if ($lateCheckinInfo == $currDate) {
                        $lateCheckin = null;
                    } else if ($lateCheckinPendingInfo == $currDate) {
                        $lateCheckin = true;
                    } 
                } else if($currentTime < $timeWithBuffer){
                    if($currDate == $latestCheckinInTimeZoneDate){
                        if($latestCheckinInTimeZone){
                            $earlyCheckout = null;
                            $earlyCheckoutTime = false;
                        }
                     }
                }
                //if shift start time is greater than end time, that is two day shift
                if ($shiftStartTime > $shiftEndTime) // to check if the shift ends the next day
                {
                    $time = Carbon::now(config('settings.time_zone'));
                    $day = $time->day + 1;
                    //set time to shift start time
                    $setShiftStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $time->year . '-' . $time->month . '-' . $time->day . ' ' . $shiftStartTime, config('settings.time_zone'));
                    //set offset time 
                    $setOffsetStartTimeForCheckin = Carbon::createFromFormat('Y-m-d H:i:s', $time->year . '-' . $time->month . '-' . $time->day . ' ' . $offsetStartTimeForCheckin, config('settings.time_zone'));
                    //set time to next day 12am
                    $set12am = Carbon::createFromFormat('Y-m-d H:i:s', $time->year . '-' . $time->month . '-' . $day . ' 00:00:00', config('settings.time_zone'));
                    //current time is between shift start time and morning 00:00
                    if ($time->between($setShiftStartTime, $set12am, true)) {
                        $earlyCheckout = true;
                    } else if ($time->between($setOffsetStartTimeForCheckin, $setShiftStartTime, true)) {
                        //if current time is before 2 hours to shift time 
                        $afterShiftTime = false;
                    } else {
                        if ($currentTime < $shiftEndTimeForEarlyCheckout) { //current time is after 12am or before shift end time
                            $earlyCheckout = true;
                        } else if ($currentTime > $shiftEndTimeForEarlyCheckout) { //after shift end time
                            $afterShiftTime = true;
                            $lateCheckin = false;
                            $earlyCheckoutTime = true;
                        }
                    }
                } else {
                    /*echo $currentTime."<br>".$shiftEndTimeWithBuffer;
                    exit;*/
                    if ($currentTime > $shiftStartTime && $currentTime < $shiftEndTimeForEarlyCheckout) { //before shift end time
                        $earlyCheckout = true;
                    } else if ($currentTime > $shiftEndTimeForEarlyCheckout) { //after shift end time
                        $afterShiftTime = true;
                        $lateCheckin = false;
                    }
                }
                $time1 = Carbon::parse($shiftStartTime);
                $time2 = Carbon::parse($shiftEndTime);
                $difference = $time2->diff($time1);
                $hours = $difference->h;
                $minutes = $difference->i;
                $seconds = $difference->s;
                $totalDifference = $hours * 3600 + $minutes * 60 + $seconds;
                $halfDifference = $totalDifference / 2;
                $difference = CarbonInterval::seconds($halfDifference)->cascade();
                $halfTime = $time1->copy()->add($difference);
                $formattedHalfTime = $halfTime->format('H:i:s');
                $half_time_over = true;
                if ($currentTime > $formattedHalfTime) {
                    $half_time_over = false;
                }
            }
        }
        //check user is on leave today
        $checkUserOnLeave = LeaveHelper::checkUserOnLeave($user->id);
        // check if user late checkin is rejected
        $currentDate = Carbon::now(config('settings.time_zone'))->toDateString();
        $request = UserAttendanceRequests::where('user_id', '=', $user->id)
                                            ->whereDate('check_in','=', $currentDate)
                                            ->where('status', '=', 'rejected')
                                            ->first();
        if(!empty($request)){
            $lateCheckinRejected = true;
        }
        else{
            $lateCheckinRejected = false;
        }
        
          //to make the user not enter the reason for early checkout/ late checkin if he has applied for half day
        $getHalfDayInfo = ApplyLeave::where('user_id', Auth::user()->id)
            ->where('leave_type', 'half_day')
            ->where('from_date', $currDate)
            ->where('status', 'Approve')
            ->value('half_day_type');
        if (($getHalfDayInfo == 'second_half') && ($half_time_over != true)) {
            $earlyCheckout = null;
        }
        if (($getHalfDayInfo == 'first_half') && ($half_time_over != false)) {
            $lateCheckin = null;
        }
        //regerate sesssion
        session()->regenerate();
        $currentDateWithTimezone = Carbon::now(config('settings.time_zone'))->toDateString();
        $dobnow = Carbon::now('UTC')->format('Y-m-d');
        // $holiday = Holiday::where('date', $currentDateWithTimezone)->first();
        $holidayIds = HolidayHelper::getholidayList($user->id);
        $holiday = Holiday::where('date', '=', $dobnow)
                            ->whereIn('id', $holidayIds)
                            ->get();
        $isHoliday = false;
        $isHoliday1 = $holiday->isNotEmpty();
        if($isHoliday1) {
            $isHoliday = true;
        }
        // to get the weekly off date
        $dateForWeeklyOff = Carbon::now()->setTimezone(config('settings.time_zone'))->toDateString();
        $startDateForWeeklyOff = Carbon::parse($dateForWeeklyOff . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDateForWeeklyOff = Carbon::parse(Carbon::now()->addDay()->toDateString() . '00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $userWeeklyOff = UserWeeklyOff::where('user_id', $user->id)
        ->whereBetween('created_at', [$startDateForWeeklyOff, $endDateForWeeklyOff])
        ->where('weekly_off', 1)->first();
        $weekend = false;
        if(!empty($userWeeklyOff))
        {
            $weekend = true;
        }
        
        return response()->json(
            [
                'status'=>200,
                    'lateCheckin' => $lateCheckin,
                    'earlyCheckout' => $earlyCheckout,
                    'afterShiftTime' => $afterShiftTime,
                    'checkUserOnLeave' => $checkUserOnLeave,
                    'lateCheckinRejected' =>  $lateCheckinRejected,
                    'earlyCheckoutTime' =>  $earlyCheckoutTime,
                    'is_weekend' => $weekend,
                    'is_holiday' => $isHoliday,
                    "token" => csrf_token()
                ],
            200
        );
    }
    // load more compoff balance request on dashboard
    public function getCompOffBalanceRequest(Request $request)
    {
        $offset = $request->input('offset') ? $request->input('offset') : 0;
        $limit = $request->input('limit') ? $request->input('limit') : 5;
        
        //get leaves, if user is collaborator
        $getCollaboratorLeaves  = GetShiftDetailHelper::getCollabratorLeaves('leave');   
         
        // $leave_reports = ApplyLeave::where('status','pending')->with(['user', 'Leave'])->orderBy('created_at','DESC')->skip($offset * $limit)->take($limit)->get();
        //view permissions
        if (auth()->user()->can('View All CompOff requests')) {
            $compOffbalance_reports = CompOffLeave::where('status', 'pending')
             ->with(['user', 'Leave'])
             ->whereHas('user', function ($query) {
              $query->whereNull('deleted_at');
             })
             ->orderBy('created_at', 'DESC')
             ->skip($offset * $limit)
             ->take($limit)
             ->get();
           } elseif (auth()->user()->can('View All CompOff requests of team')) {
            $userIds = GetShiftDetailHelper::getMyteamMembers();
            $compOffbalance_reports = CompOffLeave::whereIn('user_id', $userIds)
             ->where('status', 'pending')
             ->with(['user', 'Leave'])
             ->whereHas('user', function ($query) {
              $query->whereNull('deleted_at');
             })
             ->orderBy('created_at', 'DESC')
             ->skip($offset * $limit)
             ->take($limit)
             ->get();
           } elseif (auth()->user()->can('View All CompOff requests of assigned employees')) {
            $userIds = GetShiftDetailHelper::getMyReportingEmployees();
            $userIds[] = auth()->user()->id;
            $compOffbalance_reports = CompOffLeave::whereIn('user_id', $userIds)
             ->where('status', 'pending')
             ->with(['user', 'Leave'])
             ->whereHas('user', function ($query) {
              $query->whereNull('deleted_at');
             })
             ->orderBy('created_at', 'DESC')
             ->skip($offset * $limit)
             ->take($limit)
             ->get();
           } elseif (count($getCollaboratorLeaves) > 0) {
            $compOffbalance_reports = CompOffLeave::whereIn('id', $getCollaboratorLeaves)
             ->where('status', 'pending')
             ->with(['user', 'Leave'])
             ->whereHas('user', function ($query) {
              $query->whereNull('deleted_at');
             })
             ->orderBy('created_at', 'DESC')
             ->skip($offset * $limit)
             ->take($limit)
             ->get();
           } else {
            $compOffbalance_reports = CompOffLeave::where('status', 'pending')
             ->where('user_id', auth()->user()->id)
             ->with(['user', 'Leave'])
             ->whereHas('user', function ($query) {
              $query->whereNull('deleted_at');
             })
             ->orderBy('created_at', 'DESC')
             ->skip($offset * $limit)
             ->take($limit)
             ->get();
           }
       
        $leave_data = array();
        $editPermission = false;
        foreach ($compOffbalance_reports as $leave_report) {
            if ($leave_report->user) {
                $leaves = Leave::where('id', '=', $leave_report->leave_id)->first();
                if($leaves){
                    $for_date =  Carbon::parse($leave_report->date)->format(config('settings.php_date_format'));
                    //to get the holidays dates
                    $holidays = Holiday::all('date');
                    $holidayDates = array();
                    for($i=0; $i<count($holidays); $i++){
                    $holidaydate[$i] = $holidays[$i]->getAttribute('date');
                    $holidayDates[$i] = Carbon::parse($holidaydate[$i])->format('d/m/Y');
                    $type = null;
                    }
                    if(in_array($for_date,$holidayDates))
                    {
                        $occasion = 'Holiday';
                    }
                    else
                    {
                        $occasion = 'Weekend';
                    }
                    $requested_on = Carbon::parse($leave_report->created_at);
                    $requested_on->setTimezone(config('settings.time_zone'));
                    $requested_on = $requested_on->format(config('settings.php_date_format') . ' h:i A');
                    $leave_obj['requested_on'] = $requested_on;
                    $leave_obj['id'] = $leave_report->id;
                    $leave_obj['reason'] = $leave_report->reason;
                    $leave_obj['for_date'] = $for_date;
                    $leave_obj['is_process'] = $leave_report->status;
                    $leave_obj['user_id'] = $leave_report->user_id;
                    $leave_obj['created_at'] = $leave_report->created_at;
                    $leave_obj['updated_at'] = $leave_report->updated_at;
                    $leave_obj['leave_id'] = $leave_report->leave_id;
                    $leave_obj['status'] = $leave_report->status;
                    $leave_obj['occasion'] = $occasion;
                    $leave_obj['approver_comments'] = $leave_report->approver_comments;
                    $leave_obj['user'] = $leave_report->user;
                    $leave_obj['leave'] = $leave_report->leave;
                    // $leaves = Leave::where('id', '=', $leave_report->leave_id)->first();
                    $leave_obj['manageleaveurl'] = route("manage-leave-request", $leave_report->id);
                    $leave_obj['leavename'] = $leaves->name;
                    $user = User::where('id', $leave_report->user->id)->first();
                    if ($user->userdetail !== null) {
                        $leave_obj['user']['gender'] = $user->userdetail->gender;
                    }
                    $chatCount = UserRequestDiscuss::where('context_id', $leave_report->id)->get();
                    $leave_obj['chat_count'] = count($chatCount);;
                    //user leave discuss
                    $userLeaveDiscuss = UserRequestDiscuss::with(['user', 'user.userdetail'])
                        ->where('module', 'leave')
                        ->where('context_id', $leave_report->id)
                        ->orderBy('id','asc')
                        ->get()->toArray();
                    //added collaborators
                    $collaborators = userRequestCollaborator::where('module', 'leave')
                        ->where('context_id', $leave_report->id)
                        ->get();
                    $data  = '';
                    $collaboratorsArray = [];
                    if (count($collaborators) > 0) {
                        foreach ($collaborators as $collaborator) {
                            $collaboratorsArray[] =  $collaborator->user_id;
                            $user = User::where('id', $collaborator->user_id)->first();
                            if ($user->profile_pic) {
                                $user_image = url('storage/' . $user->profile_pic);
                            } else {
                                if(!empty($user->userdetail)){
                                    if ($user->userdetail->gender == 'Male') {
                                        $user_image = url("global_assets/images/favicon_io/default-avatar-boy.png");
                                    } else {
                                        $user_image = url("global_assets/images/favicon_io/default-avatar-girl.jpg");
                                    }
                                }else{
                                    $user_image = url("global_assets/images/placeholders/placeholder.jpg");
                                }
                                
                            }
                            $text = "'leave'";
                            $data .= '<div class="col-md-1 remove-collaborator-' . $collaborator->id . '"  style="cursor: pointer;">';
                            $data .= '<a class="boxclose" onclick="removeCollaborator(' . $collaborator->id . ',' . $leave_report->id.','.$text.')"> <i class="icon-close2"></i></a>';
                            $data .= ' <img src="' . $user_image . '" title="' . $user->name . ' ' . $user->lastName . '" class="rounded-circle rounded-border" width="32" height="32" alt="">';
                            $data .= '</div>';
                        }
                    }
                    //Edit permissions
                    if (auth()->user()->can('Edit All CompOff requests')) {
                        $editPermission = true;
                    } else if (auth()->user()->can('Edit All CompOff requests of team')) {
                        if (in_array($leave_report->user_id, GetShiftDetailHelper::getMyteamMembers())) {
                            $editPermission = true;
                        } else {
                            $editPermission = false;
                        }
                    } else if (auth()->user()->can('Edit All CompOff requests of assigned employees')) {
                        if (GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) != 0 ? GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) == auth()->user()->id : GetShiftDetailHelper::checkReportingManagers($leave_report->user_id)) {
                            $editPermission = true;
                        } else {
                            $editPermission = false;
                        }
                    } else {
                        $editPermission = false;
                    }
                    
                    //chat permission and add collaborator permission
                    //check first if user has primary reporting manager, if not then check for secondary managers
                    //if user has primary reporting manager, then add collaborator will show to primary manager only
                    if (GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) != 0 ? GetShiftDetailHelper::getPrimaryReportingManager($leave_report->user_id) == auth()->user()->id : GetShiftDetailHelper::checkReportingManagers($leave_report->user_id)) {
                        $chatPermission = true;
                        $addCollaboratorPermission = true;
                    } else if (auth()->user()->can('View Self CompOff Report') && auth()->user()->id == $leave_report->user_id) {
                        //show chat to  applied leave user who has permission for 'View Self Leave Report'
                        $chatPermission = true;
                        $addCollaboratorPermission = false;
                    } else if (in_array(auth()->user()->id, $collaboratorsArray)) { 
                        // if user is collaborator, then show chat
                        $chatPermission = true;
                        $addCollaboratorPermission = false;
                    } else {
                        $chatPermission = false;
                        $addCollaboratorPermission = false;
                    }
                
                    $leave_obj['editPermission'] = $editPermission;
                    $leave_obj['chatPermission'] = $chatPermission;
                    $leave_obj['addCollaboratorPermission'] = $addCollaboratorPermission;
                    $leave_obj['UserLeaveDiscuss'] = $userLeaveDiscuss;
                    $leave_obj['collaborators'] = $data;
                    array_push($leave_data, $leave_obj);
                }    
            }
        }
        return array(
            'compoffBalance_reports' => $leave_data,
        );
    }
    public function updateMethod(Request $request)
    {
        $context_id=$request->attendanceRequestId;
        UserRequestDiscuss::where('context_id', $context_id)
                            ->update(['read' => 1]);
    }
    // // public function getChatCount(Request $request){
    // //     // $attendanceRequestId = $request->input('attendanceRequestId');
    // //     // dd($attendanceRequestId);
    // //     // $userContext_id = $id->attendanceRequestId;
    // //     dd($request);
    // //     $userContext_id = 119;
    // //     $count = UserRequestDiscuss::where('context_id', $userContext_id)
    //                                 ->get();
    // //     $chatCount = 0; 
    // //     $chatCount = count($count);
    // //     return $chatCount;                               
    // // }
}