<?php

namespace App\Api\Http\Controllers\Api\V2\Home;

use App\DailyActivityCalculation;
use App\DailyWorkEfficiency;
use App\DsrBooking;
use App\DsrSplit;
use App\Http\Controllers\Controller;
use App\Lead;
use App\Leave;
use App\Quarter;
use App\Task;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SalesHeadController extends Controller
{
    public function WorkPlans(Request $request)
    {
        $authUser = auth()->user();
        $currentDate = date('Y-m-d');
        $userRoles = $authUser->userRoles();
        $all_reporting_users_id_array = [];
        if ($userRoles->contains('slug', 'ceo') || $userRoles->contains('slug', 'super-admin') || $userRoles->contains('slug', 'admin') || $userRoles->contains('slug', 'head-sales')) {
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })
            ->where('status', 1)
            ->when($request->has('branch_id'), function ($query) use ($request) {
                return $query->where('branch_id', $request->branch_id);
            })
            ->when($request->has('user_id'), function ($query) use ($request) {
                return $query->where('reporting_to', $request->user_id);
            })
            ->get()
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])
            ->pluck('id')
            ->toArray();
        } elseif ($userRoles->contains('slug', 'sales-head')) {
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->where('branch_id', auth()->user()->branch_id)
            ->when($request->has('user_id'), function ($query) use ($request) {
                return $query->where('reporting_to', $request->user_id);
            })
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])
            ->where('status', 1)
            ->get()
            ->pluck('id')
            ->toArray();
        } elseif ($userRoles->contains('slug', 'head-sales-2')) {
            $userIds = $authUser->getAllReportingUsersIds();
            $users = User::whereIn('id', $userIds)->get();

            foreach ($users as $user) {
                $branchId[] = $user->branch_id;
            }
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->whereIn('branch_id', $branchId)
            ->when($request->has('user_id'), function ($query) use ($request) {
                return $query->where('reporting_to', $request->user_id);
            })
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])
            ->where('status', 1)
            ->get()
            ->pluck('id')
            ->toArray();
        }

        $lists = $request->list;
        $week = Carbon::today()->subDays(15);
        $month = Carbon::now()->subMonth();
        $yesterday = Carbon::yesterday()->toDateString();
        $seven = Carbon::today()->subDays(7);
        $quarter = Quarter::whereRaw('? between date_from and date_to', $currentDate)
        ->first();

        if ($quarter) {
            $from_date = $quarter->date_from;
            $to_date = $quarter->date_to;
        }
        $usersData = DailyWorkEfficiency::whereIn('user_id', $all_reporting_users_id_array)
        ->when($lists == 1, function ($query) {
            $query->whereDate('date', today());
        })
        ->when($lists == 2, function ($query) use ($week) {
            $query->whereDate('date', '>=', $week);
        })
        ->when($lists == 3, function ($query) use ($month) {
            $query->whereDate('date', '>=', $month);
        })
        ->when($lists == 4, function ($query) use ($request) {
            $from = $request->from_date;
            $to = $request->to_date;
            $query->whereBetween('date', [$from, $to]);
        })
        ->when($lists == 5, function ($query) use ($yesterday) {
            $query->whereDate('date', '=', $yesterday);
        })
        ->when($lists == 6, function ($query) {
            $query->whereBetween('date', ['2023-11-20', '2023-12-31']);
        })
        ->when($lists == 7, function ($query) use ($seven) {
            $query->whereDate('date', '>=', $seven);
        })
        ->when($lists == 8, function ($query) use ($from_date, $to_date) {
            $query->whereBetween('date', [$from_date, $to_date]);
        })
        ->orderByDesc('work_efficiency') // Order by work efficiency in descending order
        ->get();
        // ->map(function ($user) {
        //     $work_plan_point = ($user->work_plan === null) ? 'Not Submitted' : $user->work_plan;
        //     $pdfUrl = route('showpdfnew', $user->id);

        //     return [
        //         'id' => $user->id,
        //         'name' => $user->user_name,
        //         'work_plan' => strval($work_plan_point),
        //         'efficiency' => $user->work_efficiency,
        //         'report' => $pdfUrl,
        //     ];
        // });

        $groupedData = $usersData->groupBy('user_id');
        $usersData = $groupedData->map(function ($userWorks, $userId) use ($lists, $request, $from_date, $seven ,$all_reporting_users_id_array) {
            $totalEfficiency = $userWorks->sum('work_efficiency');
            $totalWorkPlanPointEff = $userWorks->sum('work_efficiency');
            $totalWorkPlanPoint = $userWorks->sum('work_plan');

            $userIds = $all_reporting_users_id_array;
            foreach ($userIds as $user_id) {
            }

            $userJoiningDate = User::whereIn('id', $userIds)->get(['id', 'created_at']);
            $userJoiningDates = [];
            foreach ($userJoiningDate as $user) {
                $userJoiningDates[$user->id] = Carbon::parse($user->created_at)->format('Y-m-d');
            }
            $joiningDate = $userJoiningDates[$userId];
            $currentDate = date('Y-m-d');
            $quarter = Quarter::whereRaw('? between date_from and date_to', $currentDate)
                ->first();
            $quaterDate = $quarter->date_from;
            $quaterEndDate = $quarter->date_to;
            foreach ($userJoiningDates as  $userJoiningDate) {
                if ($lists == 2) {
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {                
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($currentDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {
                        $before_15_days = date('Y-m-d', strtotime('-15 days', strtotime($currentDate)));                 
                        $daysDifference = Carbon::parse($currentDate)->diffInDays(Carbon::parse($before_15_days))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [ $before_15_days ,$currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;

                } elseif ($lists == 3) {
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {
                        // $before_24_days = date('Y-m-d', strtotime('-24 days', strtotime($currentDate)));
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($currentDate)) + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                       
                    } else {
                        $currentDates = Carbon::today();
                        $thirtyDaysAgo = $currentDates->subDays(31);
                        $currentDate = Carbon::today();
                        $daysDifference = Carbon::parse($thirtyDaysAgo)->diffInDays(Carbon::parse($currentDate)) +1;
                        $leaves = Leave::whereBetween('leave_dates', [ $thirtyDaysAgo ,$currentDate ])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 4) {
                    $from = $request->from_date;
                    $to = $request->to_date;
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($to)) + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $to])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {
                        $daysDifference = Carbon::parse($from)->diffInDays(Carbon::parse($to)) + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$from, $to])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 6) {
                    $startDate = Carbon::parse('2023-11-20');
                    $currentDate = now()->format('Y-m-d');
                    $daysDifference = Carbon::parse($startDate)->diffInDays(Carbon::parse($currentDate)) + 1;
                    $leaves = Leave::whereBetween('leave_dates', [$startDate, $currentDate])->count();
                    $totalDaysDifference =  $daysDifference - $leaves;
                    $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 7) {
                    $startDate = $seven;
                    $currentDate = now()->format('Y-m-d');
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($currentDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {
                        $daysDifference = Carbon::parse($startDate)->diffInDays(Carbon::parse($currentDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$startDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 8) {
                    $startDate = Carbon::createFromFormat('Y-m-d', $from_date)->format('Y-m-d');
                    $currentDate = now()->format('Y-m-d');
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {

                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($quaterEndDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $quaterEndDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {
                        $daysDifference = Carbon::parse($startDate)->diffInDays(Carbon::parse($quaterEndDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$startDate, $quaterEndDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                }  else {
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = ($userWorks->first()->work_plan === null) ? 'Not Submitted' : $totalWorkPlanPoint;
                }
                $totalEfficiency = round($totalEfficiency, 3);
                $pdfUrl = route('showpdfnew', $userWorks->first()->user_id);                
                    
                return [
                    'id' => $userId,
                    'name' => $userWorks->first()->user_name,
                    'work_plan' => strval($workPlanPoint),
                    'efficiency' => strval($totalEfficiency),
                    'report' => $pdfUrl,
                ];
            }
           

        })->values()->toArray();
        usort($usersData, function ($a, $b) {
            return $b['efficiency'] <=> $a['efficiency'];
        });

        return [
            'status' => 'true',
            'message' => 'Work Plans',
            'data' => $usersData,
        ];
    }

    public function lastSaleDate(Request $request)
    {
        $authUser = auth()->user();
        $currentDate = date('Y-m-d');
        $userRoles = $authUser->userRoles();
        $all_reporting_users_id_array = [];

        if ($userRoles->contains('slug', 'ceo') || $userRoles->contains('slug', 'super-admin') || $userRoles->contains('slug', 'admin') || $userRoles->contains('slug', 'head-sales')) {
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })
            ->where('status', 1)
            ->when(request()->has('branch_id'), function ($query) {
                return $query->where('branch_id', request()->branch_id);
            })
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])
            ->get()
            ->pluck('id')
            ->toArray();
        } elseif ($userRoles->contains('slug', 'sales-head')) {
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->where('branch_id', auth()->user()->branch_id)->
            where('status', 1)
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])->get()
            ->pluck('id')
            ->toArray();
        } elseif ($userRoles->contains('slug', 'head-sales-2')) {
            $userIds = $authUser->getAllReportingUsersIds();
            $users = User::whereIn('id', $userIds)->get();

            foreach ($users as $user) {
                $branchId[] = $user->branch_id;
            }
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->whereIn('branch_id', $branchId)
            ->when($request->has('user_id'), function ($query) use ($request) {
                return $query->where('reporting_to', $request->user_id);
            })
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])
            ->where('status', 1)
            ->get()
            ->pluck('id')
            ->toArray();
        }

        $dsrUsers = User::whereIn('id', $all_reporting_users_id_array)->pluck('id')->toArray();

        $last_sales = [];

        foreach ($dsrUsers as $userId) {
            $dsrBooking = DsrBooking::where('sales_person_id', $userId)
            ->where('status', 'AGREEMENTED')
            ->orderByDesc('agreement_date')
            ->first();
            $dsrSplit = DsrSplit::with(['getDsrBooking' => function ($query) {
                $query->orderBy('created_at', 'desc');
            }])
                ->where('user_id', $userId)
                ->where('status', 'AGREEMENTED')
                ->orderByDesc('created_at')
                ->first();
            if ($dsrBooking && $dsrSplit) {
                $dsr_booking_date = $dsrBooking->agreement_date;
                
                $dsr_split_date = $dsrSplit->getDsrBooking->agreement_date;

                $carbonDsrBookingDate = Carbon::parse($dsr_booking_date);
                
                $carbonDsrSplitDate = Carbon::parse($dsr_split_date);

                if ($carbonDsrBookingDate->greaterThan($carbonDsrSplitDate)) {
                    $latestBooking = $dsrBooking;
                } else {
                    $latestBooking = $dsrSplit;
                }
            }
            elseif($dsrBooking && !$dsrSplit){
                $latestBooking = $dsrBooking;
            }
            else{
                $latestBooking = $dsrSplit;
            }
          

            if ($latestBooking) {
                $dateField = $latestBooking instanceof DsrBooking
                    ? $latestBooking->agreement_date
                    : ($latestBooking->getDsrBooking ? $latestBooking->getDsrBooking->agreement_date : '');

                if ($dateField) {
                    $dateCount = Carbon::now()->diffInDays($dateField);

                    $last_sales[] = [
                        'user_id' => $userId,
                        'user' => User::find($userId)->name,
                        'last_sale_date_count' => $dateCount,
                        'latest_booking' => $dateField,
                    ];
                } else {
                    $last_sales[] = [
                        'user_id' => $userId,
                        'user' => User::find($userId)->name,
                        'last_sale_date_count' => 0,
                        'latest_booking' => '',
                    ];
                }
            } else {
                $last_sales[] = [
                    'user_id' => $userId,
                    'user' => User::find($userId)->name,
                    'last_sale_date_count' => 0,
                    'latest_booking' => '',
                ];
            }
        }

        usort($last_sales, function ($a, $b) {
            return $b['last_sale_date_count'] - $a['last_sale_date_count'];
        });

        return [
            'status' => 'true',
            'message' => 'Last sales',
            'data' => $last_sales,
        ];
    }

    public function index(Request $request)
    {
        $authUser = auth()->user();
        $userRoles = $authUser->userRoles();
        $currentDate = date('Y-m-d');

        $all_reporting_users_id_array = [];
        if ($userRoles->contains('slug', 'ceo') || $userRoles->contains('slug', 'super-admin') || $userRoles->contains('slug', 'admin') || $userRoles->contains('slug', 'head-sales')) {
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })
            ->where('status', 1)

            ->when($request->has('branch_id'), function ($query) use ($request) {
                return $query->where('branch_id', $request->branch_id);
            })
            ->when($request->has('user_id'), function ($query) use ($request) {
                return $query->where('reporting_to', $request->user_id);
            })
            ->get()
            ->pluck('id')
            ->toArray();
        } elseif ($userRoles->contains('slug', 'sales-head')) {
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->where('branch_id', auth()->user()->branch_id)
            ->when($request->has('user_id'), function ($query) use ($request) {
                return $query->where('reporting_to', $request->user_id);
            })
            ->where('status', 1)->get()
            ->pluck('id')
            ->toArray();
        } elseif ($userRoles->contains('slug', 'head-sales-2')) {
            $usersID = $authUser->getAllReportingUsersIds();
            $users = User::whereIn('id', $usersID)->get();
            foreach ($users as $user) {
                $branchId[] = $user->branch_id;
            }
            $all_reporting_users_id_array = User::whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->whereIn('branch_id', $branchId)
            ->when($request->has('user_id'), function ($query) use ($request) {
                return $query->where('reporting_to', $request->user_id);
            })
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])
            ->where('status', 1)
            ->get()
            ->pluck('id')
            ->toArray();
        }

        $lists = $request->list;
        $week = Carbon::today()->subDays(15);
        $seven = Carbon::today()->subDays(7);
        $month = Carbon::now()->subMonth();
        $yesterday = Carbon::yesterday()->toDateString();
        $currentDate = date('Y-m-d');
        $quarter = Quarter::whereRaw('? between date_from and date_to', $currentDate)
            ->first();

        if ($quarter) {
            $from_date = $quarter->date_from;
            $to_date = $quarter->date_to;
          
        }

        if ($quarter) {
            $previousQuarter = Quarter::where('orders', '<', $quarter->orders)
                ->orderBy('orders', 'desc')
                ->first();

                $previousQuarterDateFrom = $previousQuarter->date_from;
                $previousQuarterDateTo = $previousQuarter->date_to;
        }

        $tasks = Task::whereIn('created_by', $all_reporting_users_id_array)
            ->where('task_completed_status', 1)
            ->when($lists == 1, function ($query) {
                $query->whereDate('schedule_date', today());
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('schedule_date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('schedule_date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('schedule_date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('schedule_date', '=', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('schedule_date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('schedule_date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('schedule_date', [$from_date, $to_date]);
            })
            ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo) {
                $query->whereBetween('schedule_date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
            })
            ->whereIn('create_task_id', [2, 3, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
            ->where(function ($query) {
                $query->whereIn('create_task_id', [2, 3, 13, 14, 12, 19])
                    ->where('team_leader_approved', 1);
            })
            ->orWhere(function ($query) use ($all_reporting_users_id_array, $lists, $week, $month, $request, $yesterday, $seven, $from_date, $to_date, $previousQuarterDateFrom, $previousQuarterDateTo) {
                $query->whereIn('created_by', $all_reporting_users_id_array)
                    ->whereIn('create_task_id', [10, 11, 15, 16, 17, 18])
                    ->when($lists == 1, function ($query) {
                        $query->whereDate('schedule_date', today());
                    })
                    ->when($lists == 2, function ($query) use ($week) {
                        $query->whereDate('schedule_date', '>=', $week);
                    })
                    ->when($lists == 3, function ($query) use ($month) {
                        $query->whereDate('schedule_date', '>=', $month);
                    })
                    ->when($lists == 4, function ($query) use ($request) {
                        $from = $request->from_date;
                        $to = $request->to_date;
                        $query->whereBetween('schedule_date', [$from, $to]);
                    })
                    ->when($lists == 5, function ($query) use ($yesterday) {
                        $query->whereDate('schedule_date', '=', $yesterday);
                    })
                    ->when($lists == 6, function ($query) {
                        $query->whereBetween('schedule_date', ['2023-11-20', '2023-12-31']);
                    })
                    ->when($lists == 7, function ($query) use ($seven) {
                        $query->whereDate('schedule_date', '>=', $seven);
                    })
                    ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                        $query->whereBetween('schedule_date', [$from_date, $to_date]);
                    })
                    ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo) {
                        $query->whereBetween('schedule_date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
                    });
            })
            ->select('tasks.*', DB::raw('(SELECT MAX(point) FROM daily_activity_calculations WHERE create_task_id = tasks.create_task_id) as max_point'))
            ->get()
            ->groupBy('lead_id');

        $calculations = DailyActivityCalculation::get();
        $leadPoint = DailyActivityCalculation::find(1)->point ?? 0;

        $tasks->transform(function ($leadTasks) {
            return $leadTasks->sortByDesc('max_point')->first();
        });

        // $leadsToSkip = $tasks->pluck('lead_id')->toArray();

        // $newLeadCount = Lead::
        //     where('lead_date', $currentDate)
        //     ->where('duplicate_entry', 'no')
        //     ->whereNotIn('id', $leadsToSkip)
        //     ->count();

        // DB::statement('CREATE TEMPORARY TABLE temp_leads_to_skip (id INT)');

        // $chunkedIds = array_chunk($leadsToSkip, 3000);

        // foreach ($chunkedIds as $chunk) {
        //     DB::table('temp_leads_to_skip')->insert(array_map(function ($id) {
        //         return ['id' => $id];
        //     }, $chunk));
        // }

        // $newLeadCount = Lead::where(function($query) use ($all_reporting_users_id_array) {
        //     $query->whereIn('created_by', $all_reporting_users_id_array)
        //           ->orWhereIn('attended_by', $all_reporting_users_id_array);
        // })
        // ->when($lists == 1, function ($query) {
        //     $query->whereDate('lead_date', today());
        // })
        // ->when($lists == 2, function ($query) use ($week) {
        //     $query->whereDate('lead_date', '>=', $week);
        // })
        // ->when($lists == 3, function ($query) use ($month) {
        //     $query->whereDate('lead_date', '>=', $month);
        // })
        // ->when($lists == 4, function ($query) use ($request) {
        //     $from = $request->from_date;
        //     $to = $request->to_date;
        //     $query->whereBetween('lead_date', [$from, $to]);
        // })
        // ->when($lists == 5, function ($query) use ($yesterday) {
        //     $query->whereDate('lead_date', '=', $yesterday);
        // })
        // ->when($lists == 6, function ($query) {
        //     $query->whereBetween('lead_date', ['2023-11-20', '2023-12-31']);
        // })
        // ->where('duplicate_entry', 'no')
        // ->whereNotExists(function ($query) {
        //     $query->select(DB::raw(1))
        //           ->from('temp_leads_to_skip')
        //           ->whereRaw('leads.id = temp_leads_to_skip.id');
        // })
        // ->count();

        // $leadCalculation = number_format($newLeadCount * $leadPoint, 3);
        $siteVist = $tasks->where('create_task_id', 2)->count();
        $sitePoint = $calculations->where('create_task_id', 2)->first()->point;
        $totalSitepoint = number_format($siteVist * $sitePoint, 3);

        $officeVist = $tasks->where('create_task_id', 13)->count();
        $OfficePoint = $calculations->where('create_task_id', 13)->first()->point;
        $totalOfficePoint = number_format($officeVist * $OfficePoint, 3);
        $directMarketing = $tasks->where('create_task_id', 11)->count();

        $directMarketingPoint = $calculations->where('create_task_id', 11)->first()->point;
        $totalDirectMarketingPoint = number_format($directMarketing * $directMarketingPoint, 3);
        $mallCounter = $tasks->where('create_task_id', 10)->count();
        $mallCounterPoint = $calculations->where('create_task_id', 10)->first()->point;
        $totalMallCounterPoint = number_format($mallCounter * $mallCounterPoint, 3);

        $appointments = $tasks->where('create_task_id', 3)->count();
        $appointmentPoint = $calculations->where('create_task_id', 3)->first()->point;
        $totalAppointmentPoint = number_format($appointments * $appointmentPoint, 3);

        $virtual = $tasks->where('create_task_id', 12)->count();
        $virtualPoint = $calculations->where('create_task_id', 12)->first()->point;
        $totalVirtualPoint = number_format($virtual * $virtualPoint, 3);

        $followuptasks = $tasks->where('create_task_id', 19);
        $countWithNullImageAndDuration = $followuptasks->filter(function ($task) {
            return $task->image == null && $task->duration >= 120;
        })->count();

        $countWithNotNullImageAndTeamLeaderApprove = $followuptasks->filter(function ($task) {
            return $task->image != null && $task->team_leader_approved == 1;
        })->count();
        $followup = $countWithNullImageAndDuration + $countWithNotNullImageAndTeamLeaderApprove;
        $followupCount = $calculations->where('create_task_id', 19)->first()->point;
        $followupPoint = number_format($followup * $followupCount, 3);

        $fresh = $tasks->where('create_task_id', 15)->count();
        $freshRuno = $tasks->where('create_task_id', 17)->where('duration', '>', 30)->count();
        $freshCall = $fresh + $freshRuno;
        $freshCallPoint = $calculations->where('create_task_id', 15)->first()->point;
        $totalFreshCallPoint = number_format($freshCall * $freshCallPoint, 3);

        $freshNri = $tasks->where('create_task_id', 16)->count();
        $freshNriRuno = $tasks->where('create_task_id', 18)->where('duration', '>', 30)->count();
        $freshCallNriPoint = $calculations->where('create_task_id', 16)->first()->point;
        $freshCallNri = $freshNri + $freshNriRuno;
        $totalFreshCallNriPoint = number_format($freshCallNri * $freshCallNriPoint, 3);

        $connectHeads = $tasks->where('create_task_id', 14)->count();
        $connectHeadsPoint = $calculations->where('create_task_id', 14)->first()->point;
        $totalconnectHeadsPoint = number_format($connectHeads * $connectHeadsPoint, 3);

        if((auth()->user()->hasRole('head-sales') || auth()->user()->hasRole('super-admin') || auth()->user()->hasRole('ceo')) && ($request->branch_id == NULL) && ($request->user_id == NULL)){
            
            $dsrSales = DsrBooking::where('status', 'AGREEMENTED')
            ->when($lists == 1, function ($query) {
                $query->whereDate('agreement_date', today());
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('agreement_date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('agreement_date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('agreement_date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('agreement_date', '=', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('agreement_date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('agreement_date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('agreement_date', [$from_date, $to_date]);
            })
            ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo, $previousQuarter) {
                $query->whereBetween('agreement_date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
            })
            ->where('quarter', $lists == 9 ? $previousQuarter->name : $quarter->name)
            ->get();
            $dsrSalesSum = $dsrSales->sum('sale_value');
            $dsrSalesCount = $dsrSales->count();
    
            $salevalue = $dsrSalesSum ;
            if($salevalue > 0){
                $saleAmount = $salevalue/100000;
                $saleUnits  =  $dsrSalesCount;
            }
            else{
                $saleAmount = '0.0';
                $saleUnits = '0';
            }
              
        }elseif(($request->user_id != NULL)){
            $dsrSales = DsrBooking::where('team_leader_id', $request->user_id)
            ->where('split', 1)
            ->where('status', 'AGREEMENTED')

            ->when($lists == 1, function ($query) {
                $query->whereDate('agreement_date', today());
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('agreement_date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('agreement_date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('agreement_date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('agreement_date', '=', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('agreement_date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('agreement_date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('agreement_date', [$from_date, $to_date]);
            })
            ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo) {
                $query->whereBetween('agreement_date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
            })
            
            ->where('quarter', $quarter->name)
            ->get();
            $dsrSalesSum = $dsrSales->sum('sale_value');
            $dsrSalesCount = $dsrSales->count();

            $splitSales = DsrSplit::join('dsr_bookings', 'dsr_bookings.id', '=', 'dsr_split.dsr_booking_id')
            ->when($lists == 1, function ($query) use ($currentDate) {
                $query->whereDate('dsr_bookings.agreement_date', $currentDate);
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('dsr_bookings.agreement_date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('dsr_bookings.agreement_date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('dsr_bookings.agreement_date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('dsr_bookings.agreement_date', '=', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('dsr_bookings.agreement_date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('dsr_bookings.agreement_date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('dsr_bookings.agreement_date', [$from_date, $to_date]);
            })
            ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo) {
                $query->whereBetween('dsr_bookings.agreement_date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
            })
            ->select('dsr_split.*')
            ->where('dsr_split.team_leader_id', $request->user_id)
            ->where('dsr_split.status', 'AGREEMENTED')
            ->where('dsr_split.quarter', $quarter->name)
            ->get();
              $splitSalesCount = $splitSales->count();
              $splitSalesSum = $splitSales->sum('amount');
              $splitSum = $splitSales->sum('split');

            if($splitSalesCount != 0 || $splitSum != 0){
                $splitValue = $splitSalesCount / $splitSum;
                $splitTotal = $splitSalesCount * $splitValue;
    
                $salevalue = $dsrSalesSum + $splitSalesSum;
                if($salevalue > 0){
                    $saleAmount = $salevalue/100000;
                    $saleUnits  = $splitTotal +  $dsrSalesCount;
                }
                else{
                    $saleAmount = '0.0';
                    $saleUnits = '0';
                }
            }
            elseif($dsrSalesCount){
                $saleAmount = $dsrSalesSum /100000;
                $saleUnits  =  $dsrSalesCount;
            }
            else{
                $saleAmount = '0.0';
                $saleUnits = '0';
            }

        }else{
            $dsrSales = DsrBooking::where('branch_id', $request->branch_id)
            ->where('split', 1)
            ->where('status', 'AGREEMENTED')

            ->when($lists == 1, function ($query) {
                $query->whereDate('agreement_date', today());
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('agreement_date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('agreement_date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('agreement_date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('agreement_date', '=', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('agreement_date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('agreement_date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('agreement_date', [$from_date, $to_date]);
            })
            ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo) {
                $query->whereBetween('agreement_date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
            })
            
            ->where('quarter', $quarter->name)
            ->get();
            $dsrSalesSum = $dsrSales->sum('sale_value');
            $dsrSalesCount = $dsrSales->count();

            $splitSales = DsrSplit::join('dsr_bookings', 'dsr_bookings.id', '=', 'dsr_split.dsr_booking_id')
            ->when($lists == 1, function ($query) use ($currentDate) {
                $query->whereDate('dsr_bookings.agreement_date', $currentDate);
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('dsr_bookings.agreement_date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('dsr_bookings.agreement_date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('dsr_bookings.agreement_date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('dsr_bookings.agreement_date', '=', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('dsr_bookings.agreement_date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('dsr_bookings.agreement_date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('dsr_bookings.agreement_date', [$from_date, $to_date]);
            })
            ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo) {
                $query->whereBetween('dsr_bookings.agreement_date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
            })
            ->select('dsr_split.*')
            ->where('dsr_split.branch_id', $request->branch_id)
            ->where('dsr_split.status', 'AGREEMENTED')
            ->where('dsr_split.quarter', $quarter->name)
            ->get();
              $splitSalesCount = $splitSales->count();
              $splitSalesSum = $splitSales->sum('amount');
              $splitSum = $splitSales->sum('split');

            if($splitSalesCount != 0 || $splitSum != 0){
                $splitValue = $splitSalesCount / $splitSum;
                $splitTotal = $splitSalesCount * $splitValue;
    
                $salevalue = $dsrSalesSum + $splitSalesSum;
                if($salevalue > 0){
                    $saleAmount = $salevalue/100000;
                    $saleUnits  = $splitTotal +  $dsrSalesCount;
                }
                else{
                    $saleAmount = '0.0';
                    $saleUnits = '0';
                }
            }elseif($dsrSalesCount){
                $saleAmount = $dsrSalesSum /100000;
                $saleUnits  =  $dsrSalesCount;
            }
            else{
                $saleAmount = '0.0';
                $saleUnits = '0';
            }

          
        }
       
        $data = [
            [
                'activity_type' => 'Appointment',
                'id' => 3,
                'point' => $totalAppointmentPoint ?? '0.0',
                'count' => strval($appointments),
                'colorCode' => '#4285F4',
            ],
            [
                'activity_type' => 'Site Visit',
                'id' => 2,
                'point' => $totalSitepoint ?? '0.0',
                'count' => strval($siteVist),
                'colorCode' => '#EA4335',
            ],

            [
                'activity_type' => 'Office Visit',
                'id' => 13,
                'point' => $totalOfficePoint ?? '0.0',
                'count' => strval($officeVist),
                'colorCode' => '#FBBC05',
            ],
            [
                'activity_type' => 'Virtual Meeting',
                'id' => 12,
                'point' => $totalVirtualPoint ?? '0.0',
                'count' => strval($virtual),
                'colorCode' => '#34A853',
            ],
            [
                'activity_type' => 'Call Connected to Heads',
                'id' => 14,
                'point' => $totalconnectHeadsPoint ?? '0.0',
                'count' => strval($connectHeads),
                'colorCode' => '#A311A6',
            ],
            [
                'activity_type' => 'Direct Marketing',
                'id' => 11,
                'point' => $totalDirectMarketingPoint ?? '0.0',
                'count' => strval($directMarketing),
                'colorCode' => '#375559',
            ],
            [
                'activity_type' => 'Mall Counter',
                'id' => 10,
                'point' => $totalMallCounterPoint ?? '0.0',
                'count' => strval($mallCounter),
                'colorCode' => '#C29B2A',
            ],
            [
                'activity_type' => 'Follow Up Call',
                'id' => 19,
                'point' => $followupPoint ?? '0.0',
                'count' => strval($followup),
                'colorCode' => '#279548',
            ],
            [
                'activity_type' => 'Fresh Call (NRI)',
                'id' => 16,
                'point' => $totalFreshCallNriPoint ?? '0.0',
                'count' => strval($freshCallNri),
                'colorCode' => '#C254C5',
            ],
            [
                'activity_type' => 'Fresh Call (Resident)',
                'id' => 15,
                'point' => $totalFreshCallPoint ?? '0.0',
                'count' => strval($freshCall),
                'colorCode' => '#4A34BE',
            ],

            // [
            //     'activity_type' => 'New lead',
            //     'id' => 50,
            //     'point' => $leadCalculation,
            //     'count' => strval($newLeadCount),
            //     'colorCode' => '#23DAE5'
            // ],
            [
                'activity_type' => 'Sale',
                'id' => 0,
                'point' => strval($saleAmount),
                'count' => strval($saleUnits),
                'colorCode' => '#4A34BE',
            ],
        ];

        $totalPoints = 0.0;

        foreach ($data as $item) {
            if (is_numeric($item['point'])) {
                $totalPoints += $item['point'];
            }
        }

        $task = [
            'current_date' => $currentDate,
            'total_points' => number_format($totalPoints, 3),
            'data' => $data,
        ];

        $allocationLeadsCount = Lead::where('is_ceo_verified', 1)
            ->where('attended_by', $authUser->id)
            ->where('sale_status', '!=', 'yes')
            ->where('is_attended', 0)
            ->where('show_in_salesperson_actions', 1)
            ->whereHas('getSource', function ($query){
                $query->where('status', 0);
            })
            ->count();

        $unattended = Lead::with('getLeadCategory', 'getPreferredProject')
        ->where('is_ceo_verified', '1')
        ->where('is_attended', 0)
        ->where('runo', 0)
        ->when(is_array($all_reporting_users_id_array), function ($query) use ($all_reporting_users_id_array) {
            return $query->whereIn('attended_by', $all_reporting_users_id_array);
        }, function ($query) use ($all_reporting_users_id_array) {
            return $query->where('attended_by', $all_reporting_users_id_array);
        })
        ->whereHas('getSource', function ($query){
            $query->where('status', 0);
        })
        ->count();

        $tasks_count = Task::whereIn('followup_by', $all_reporting_users_id_array)
            ->whereDate('schedule_date', today());

        $todays_tasks = $tasks_count
            ->count();

        $dsrUsers = User::whereIn('id', $all_reporting_users_id_array)
            ->whereNotIn('id', [257, 271, 283, 251, 252, 285, 314])
            ->pluck('id')
            ->toArray();
        foreach ($dsrUsers as $userId) {
            $dsrBooking = DsrBooking::where('sales_person_id', $userId)
            ->where('status', 'AGREEMENTED')
            ->orderByDesc('agreement_date')
            ->first();

            $dsrSplit = DsrSplit::with(['getDsrBooking' => function ($query) {
                $query->orderBy('created_at', 'desc');
            }])
                ->where('user_id', $userId)
                ->where('status', 'AGREEMENTED')
                ->orderByDesc('created_at')
                ->first();
            if ($dsrBooking && $dsrSplit) {
                $dsr_booking_date = $dsrBooking->agreement_date;
                
                $dsr_split_date = $dsrSplit->getDsrBooking->agreement_date;

                $carbonDsrBookingDate = Carbon::parse($dsr_booking_date);
                
                $carbonDsrSplitDate = Carbon::parse($dsr_split_date);

                if ($carbonDsrBookingDate->greaterThan($carbonDsrSplitDate)) {
                    $latestBooking = $dsrBooking;
                } else {
                    $latestBooking = $dsrSplit;
                }
            }
            elseif($dsrBooking && !$dsrSplit){
                $latestBooking = $dsrBooking;
            }
            else{
                $latestBooking = $dsrSplit;
            }
            if ($latestBooking) {
                $dateField = $latestBooking instanceof DsrBooking
                    ? $latestBooking->agreement_date
                    : ($latestBooking->getDsrBooking ? $latestBooking->getDsrBooking->agreement_date : null);

                if ($dateField) {
                    $dateCount = Carbon::now()->diffInDays($dateField);

                    $last_sales[] = [
                        'user_id' => $userId,
                        'user' => User::find($userId)->name,
                        'last_sale_date_count' => $dateCount,
                        'latest_booking' => $dateField,
                    ];
                } else {
                    $last_sales[] = [
                        'user_id' => $userId,
                        'user' => User::find($userId)->name,
                        'last_sale_date_count' => 0,
                        'latest_booking' => '',
                    ];
                }
            } else {
                $last_sales[] = [
                    'user_id' => $userId,
                    'user' => User::find($userId)->name,
                    'last_sale_date_count' => 0,
                    'latest_booking' => '',
                ];
            }
        }

        if (isset($last_sales) && is_array($last_sales) && !empty($last_sales)) {
            usort($last_sales, function ($a, $b) {
                return $b['last_sale_date_count'] - $a['last_sale_date_count'];
            });

            $last_sales = array_slice($last_sales, 0, 10);
        } else {
            $last_sales = [];
        }

        $last_sales = array_slice($last_sales, 0, 10);

        $usersData = DailyWorkEfficiency::whereIn('user_id', $all_reporting_users_id_array)
        ->whereNotIn('user_id', [257, 271, 283, 251, 252, 285, 314])

            ->when($lists == 1, function ($query) {
                $query->whereDate('date', today());
            })
            ->when($lists == 2, function ($query) use ($week) {
                $query->whereDate('date', '>=', $week);
            })
            ->when($lists == 3, function ($query) use ($month) {
                $query->whereDate('date', '>=', $month);
            })
            ->when($lists == 4, function ($query) use ($request) {
                $from = $request->from_date;
                $to = $request->to_date;
                $query->whereBetween('date', [$from, $to]);
            })
            ->when($lists == 5, function ($query) use ($yesterday) {
                $query->whereDate('date', '=', $yesterday);
            })
            ->when($lists == 6, function ($query) {
                $query->whereBetween('date', ['2023-11-20', '2023-12-31']);
            })
            ->when($lists == 7, function ($query) use ($seven) {
                $query->whereDate('date', '>=', $seven);
            })
            ->when($lists == 8, function ($query) use ($from_date, $to_date) {
                $query->whereBetween('date', [$from_date, $to_date]);
            })
            ->when($lists == 9, function ($query) use ($previousQuarterDateFrom, $previousQuarterDateTo) {
                $query->whereBetween('date', [$previousQuarterDateFrom, $previousQuarterDateTo]);
            })
            ->orderByDesc('work_efficiency') // Order by work efficiency in descending order
            // Limit the results to the top 10 users
            ->get();
        // ->map(function ($user) {
        //     $work_plan_point = ($user->work_plan === null) ? 'Not Submitted' : $user->work_plan;
        //     $pdfUrl = route('showpdfnew', $user->user_id);

        //     return [
        //         'id' => $user->user_id,
        //         'name' => $user->user_name,
        //         'work_plan' => strval($work_plan_point),
        //         'efficiency' => $user->work_efficiency,
        //         'report' => $pdfUrl,
        //     ];
        // });
        $groupedData = $usersData->groupBy('user_id');
        $usersData = $groupedData->map(function ($userWorks, $userId) use ($lists, $request, $from_date, $seven ,$all_reporting_users_id_array) {
            $totalEfficiency = $userWorks->sum('work_efficiency');
            $totalWorkPlanPointEff = $userWorks->sum('work_efficiency');
            $totalWorkPlanPoint = $userWorks->sum('work_plan');

            $userIds = $all_reporting_users_id_array;
            foreach ($userIds as $user_id) {
            }

            $userJoiningDate = User::whereIn('id', $userIds)->get(['id', 'created_at']);
            $userJoiningDates = [];
            foreach ($userJoiningDate as $user) {
                $userJoiningDates[$user->id] = Carbon::parse($user->created_at)->format('Y-m-d');
            }
            $joiningDate = $userJoiningDates[$userId];
            $currentDate = date('Y-m-d');
            $quarter = Quarter::whereRaw('? between date_from and date_to', $currentDate)
                ->first();
            $quaterDate = $quarter->date_from;
            $quaterEndDate = $quarter->date_to;
            foreach ($userJoiningDates as  $userJoiningDate) {
                if ($lists == 2) {
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {                
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($currentDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {
                        $before_15_days = date('Y-m-d', strtotime('-15 days', strtotime($currentDate)));                 
                        $daysDifference = Carbon::parse($currentDate)->diffInDays(Carbon::parse($before_15_days))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [ $before_15_days ,$currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;

                } elseif ($lists == 3) {
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($currentDate)) + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                       
                    } else {
                        $currentDates = Carbon::today();
                        $thirtyDaysAgo = $currentDates->subDays(31);
                        $currentDate = Carbon::today();
                        $daysDifference = Carbon::parse($thirtyDaysAgo)->diffInDays(Carbon::parse($currentDate)) +1;
                        $leaves = Leave::whereBetween('leave_dates', [ $thirtyDaysAgo ,$currentDate ])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 4) {
                    $from = $request->from_date;
                    $to = $request->to_date;
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($to)) + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $to])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {
                        $daysDifference = Carbon::parse($from)->diffInDays(Carbon::parse($to)) + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$from, $to])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 6) {
                    $startDate = Carbon::parse('2023-11-20');
                    $currentDate = now()->format('Y-m-d');
                    $daysDifference = Carbon::parse($startDate)->diffInDays(Carbon::parse($currentDate)) + 1;
                    $leaves = Leave::whereBetween('leave_dates', [$startDate, $currentDate])->count();
                    $totalDaysDifference =  $daysDifference - $leaves;
                    $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 7) {
                    $startDate = $seven;
                    $currentDate = now()->format('Y-m-d');
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {
                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($currentDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {
                        $daysDifference = Carbon::parse($startDate)->diffInDays(Carbon::parse($currentDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$startDate, $currentDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } elseif ($lists == 8) {
                    $startDate = Carbon::createFromFormat('Y-m-d', $from_date)->format('Y-m-d');
                    $currentDate = now()->format('Y-m-d');
                    if (Carbon::parse($joiningDate)->between($quaterDate, $quaterEndDate)) {

                        $daysDifference = Carbon::parse($joiningDate)->diffInDays(Carbon::parse($quaterEndDate))  + 1;
                        $leaves = Leave::whereBetween('leave_dates', [$joiningDate, $quaterEndDate])->count();
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                    } else {

                        $daysDifference = Carbon::parse($startDate)->diffInDays(Carbon::parse($quaterEndDate))  + 1;
                        // dd($daysDifference);
                        $leaves = Leave::whereBetween('leave_dates', [$startDate, $quaterEndDate])->count();
                        // dd($leaves);
                        $totalDaysDifference =  $daysDifference - $leaves;
                        $totalEfficiency = $daysDifference > 0 ? ($totalEfficiency / $totalDaysDifference) : 0;
                        // dd($totalEfficiency);
                    }
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = $totalWorkPlanPointEff;
                } else {
                    $totalEfficiency = $totalEfficiency;
                    $workPlanPoint = ($userWorks->first()->work_plan === null) ? 'Not Submitted' : $totalWorkPlanPoint;
                }
                $totalEfficiency = round($totalEfficiency, 3);
                $pdfUrl = route('showpdfnew', $userWorks->first()->user_id);                
                    
                return [
                    'id' => $userId,
                    'name' => $userWorks->first()->user_name,
                    'work_plan' => strval($workPlanPoint),
                    'efficiency' => strval($totalEfficiency),
                    'report' => $pdfUrl,
                ];
            }
           

        })->values()->toArray();
        usort($usersData, function ($a, $b) {
            return $b['efficiency'] <=> $a['efficiency'];
        });

        $usersData = array_slice($usersData, 0, 10);

        return response()->json([
            'status' => true,
            'message' => 'Success',
            'data' => [
                'team_leader' => $authUser->name,
                'designation' => $authUser->designation ?? '',
                'status' => $authUser->status,
                'users' => $usersData,
                'unallocated' => $allocationLeadsCount,
                'unattended' => $unattended,
                'todays_tasks' => $todays_tasks,
                'tasks' => $task,
                'last_sales' => $last_sales,
            ],
        ]);
    }
}
