<?php

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

use App\Lead;
use App\User;
use App\DailySaleReport;
use App\DailyWorkPlan;
use App\DsrBooking;
use App\DsrSplit;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use App\Http\Controllers\Controller;
use App\Notification;
use App\Quarter;
use App\Task;
use Carbon\Carbon;

class HomeController extends Controller
{
    // protected function calculateIndividualTotals($user, $quarterlyTarget)
    // {
    //     $individualDsrBooking = DsrBooking::where('split', 1)
    //         ->where('sales_person_id', $user->id)
    //         ->when($quarterlyTarget, function ($query, $quarterlyTarget) {
    //             return $query->where('quarter', $quarterlyTarget->name);
    //         })
    //         ->get();
    //     $individualDsrSplit = DsrSplit::where('user_id', $user->id)
    //         ->when($quarterlyTarget, function ($query, $quarterlyTarget) {
    //             return $query->where('quarter', $quarterlyTarget->name);
    //         })

    //         ->get();

    //     $individualTotal = [
    //         'individual_agreement_total_amount' => 0,
    //         'individual_agreement_total_units' => 0,
    //         'individual_booking_total_amount' => 0,
    //         'individual_booking_total_units' => 0,
    //         'individual_pending_total_amount' => 0,
    //         'individual_pending_total_units' => 0,
    //     ];

    //     foreach ($individualDsrBooking as $booking) {
    //         if ($booking->status === 'AGREEMENTED') {
    //             $sumAmount = $booking->sale_value;
    //             $individualTotal['individual_agreement_total_amount'] += $sumAmount;

    //             $sumUnit = 1;

    //             $individualTotal['individual_agreement_total_units'] += $sumUnit;
    //         } elseif ($booking->status === 'BOOKING') {
    //             $sumAmount = $booking->sale_value;
    //             $individualTotal['individual_booking_total_amount'] += $sumAmount;
    //             $sumUnit = 1;
    //             $individualTotal['individual_booking_total_units'] += $sumUnit;
    //         }

    //         if ($booking->status === 'PENDING' || $booking->status === 'BOOKING') {
    //             $sumAmount = $booking->sale_value;
    //             $individualTotal['individual_pending_total_amount'] += $sumAmount;
    //             $sumUnit = 1;
    //             $individualTotal['individual_pending_total_units'] += $sumUnit;
    //         }
    //         if ($booking->status === 'AGREEMENTED' && $booking->transferred_quarter === null) {
    //             $sumAmount = $booking->sale_value;
    //             $individualTotal['individual_booking_total_amount'] += $sumAmount;
    //             $sumUnit = 1;
    //             $individualTotal['individual_booking_total_units'] += $sumUnit;
    //         }
    //     }
    //     foreach ($individualDsrSplit as $split) {
    //         if ($split->status === 'AGREEMENTED') {
    //             $sumAmount = $split->amount;
    //             $individualTotal['individual_agreement_total_amount'] += $sumAmount;

    //             $sumUnit = 1 / $split->split;

    //             $individualTotal['individual_agreement_total_units'] += $sumUnit;
    //         } elseif ($split->status === 'BOOKING') {
    //             $sumAmount = $split->amount;
    //             $individualTotal['individual_booking_total_amount'] += $sumAmount;
    //             $sumUnit = 1 / $split->split;
    //             $individualTotal['individual_booking_total_units'] += $sumUnit;
    //         }

    //         if ($split->status === 'PENDING' || $split->status === 'BOOKING') {
    //             $sumAmount = $split->amount;
    //             $individualTotal['individual_pending_total_amount'] += $sumAmount;
    //             $sumUnit = 1 / $split->split;
    //             $individualTotal['individual_pending_total_units'] += $sumUnit;
    //         }
    //         if ($split->status === 'AGREEMENTED' && $split->transferred_quarter === null) {
    //             $sumAmount = $split->amount;
    //             $individualTotal['individual_booking_total_amount'] += $sumAmount;
    //             $sumUnit = 1 / $split->split;
    //             $individualTotal['individual_booking_total_units'] += $sumUnit;
    //         }
    //     }

    //     return $individualTotal;
    // }
    public function index(Request $request)
    {
        /** @var User $user */
        $user = auth()->user();
        $olduser = User::find($user->id);
        if ($olduser) {
            $olduser->device_type = $request->device;
            $olduser->app_version = $request->app_version;
            $olduser->device_name = $request->device_name;
            $olduser->save();
        }


        $date = date('Y-m-d');
        $userName = $user->name;
        $subTitle = "Make Today Count !";
        $userRoles = auth()
            ->user()
            ->userRoles();

        $all_reporting_users_id_array = [];
        $authUser = auth()->user();

        if (!$userRoles->contains('slug', 'ceo') && !$userRoles->contains('slug', 'super-admin') && !$userRoles->contains('slug', 'admin') && !$userRoles->contains('slug', 'sales-head')) { //Except superadmin and admin
            $all_reporting_users_id_array = $authUser->getAllReportingUsersIds();
            array_push($all_reporting_users_id_array, $authUser->id);
        }

        $tasks = Task::with([
            'getTaskType',
            'getFollowupBy',
            'getProject',
            'getLeadCategory',
            'getLeadStage',
            'getFollowupStatus',
            'getSiteVisitStatus',
            'getBudget',
            'getCreatedBy',
            'getLead'
        ])
            ->where(function ($query) use ($all_reporting_users_id_array) {
                $query->whereIn('followup_by', $all_reporting_users_id_array)
                    ->orWhereIn('created_by', $all_reporting_users_id_array);
            })
            ->where(function ($query) use ($date) {
                $query->whereDate('reminder', now()->format('Y-m-d'))
                    ->orWhereDate('schedule_date', now()->format('Y-m-d'));
            })
            ->get()
            ->count();




        $authUser = auth()->user();
        if ($authUser->hasRole('admin') || $authUser->hasRole('super-admin') || $authUser->hasRole('ceo') || $authUser->hasRole('sales-head')) {
            $all_reporting_users = User::with('roles')->whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })->where('status', 1)->get()->pluck('id');
        } elseif ($authUser->hasRole('executive')) {
            $all_reporting_users = auth()->user()->id;
        } else {
            $all_reporting_users = $authUser->getAllReportingUsersIds();
        }
        $unnattended = Lead::with('getLeadCategory', 'getPreferredProject')
            ->where('is_ceo_verified', '1')
            ->where('runo', 0)
            ->when(is_array($all_reporting_users), function ($query) use ($all_reporting_users) {
                return $query->whereIn('attended_by', $all_reporting_users);
            }, function ($query) use ($all_reporting_users) {
                return $query->where('attended_by', $all_reporting_users);
            })
            ->where('is_attended', 0)->get()->count();

        $allocationLeadsCount = Lead::where('is_ceo_verified', 1)
            ->where('attended_by', $user->id)
            ->where('sale_status', '!=', 'yes')
            ->where('show_in_salesperson_actions', 1)->get()->count();


        $leads = Lead::with([
            'getLeadStage',
            'getUnit',
            'getAttendedBy',
            'getSource',
            'getProjectType',
            'getPreferredProject',
            'getPreferredProject.getProjectType',
            'getBudget',
            'getLeadCategory',
        ])

            ->where(function ($query) {
                $query->whereNotIn('lead_stage_id', [6, 7, 8])->orWhereNull('lead_stage_id');
            })
            ->when($userRoles->contains('slug', 'executive'), function ($q) {
                $q->where('is_attended', 1);
            })
            ->when(!$userRoles->contains('slug', 'super-admin') && !$userRoles->contains('slug', 'admin') && !$userRoles->contains('slug', 'ceo') && !$userRoles->contains('slug', 'sales-head'), function ($q) use ($all_reporting_users_id_array) {
                $q->whereIn('attended_by', $all_reporting_users_id_array);
            })

            ->where('sale_status', 'no')->get();


        $residentialCount = $leads->where('project_type', 1)->count();

        $residential = [
            "id" => 1,
            "count" => $residentialCount,
            "colorCode" => "#BB922E"
        ];

        $commercialCount = $leads->where('project_type', 2)->count();

        $commercial = [
            "id" => 2,
            "count" => $commercialCount,
            "colorCode" => "#4669A9"
        ];

        $retailCount = $leads->where('project_type', 3)->count();

        $retail = [
            "id" => 3,
            "count" => $retailCount,
            "colorCode" => "#002A53"
        ];

        $othersCount = Lead::where('attended_by', $user->id)->where('project_type', null)->count();
        $others = [
            "id" => 0,
            "count" => $othersCount,
            "colorCode" => "#B1A075"
        ];
        $leadsCount = $leads->count();

        $leadsDetails = [
            "total" => $leadsCount,
            "residential" => $residential,
            "commercial" => $commercial,
            "retail" => $retail,
            "others" => $others
        ];
        $currentDate = date('Y-m-d');
        $quarterlyTarget = Quarter::whereRaw('? between date_from and date_to', $currentDate)
            ->first();
            $executivesList= User::with(['roles'])
            ->whereHas('roles', function ($q) {
                $q->where('role_id', 8);
            })
            ->where('status', 1)
            ->where('reporting_to', '!=', 282)
            ->where('branch_id', auth()->user()->branch_id)

            ->get();

            $teamLeadersList = User::with('roles', 'getDailySaleReport')
            ->whereHas('roles', function ($query) {
                $query->where('id', 7);
            })
            ->where('status', 1)
            ->where('id', '!=', 282)
            ->where('branch_id', auth()->user()->branch_id)
            ->get();
            $teamLeadersRankList = $teamLeadersList->map(function ($item, $key) use ($quarterlyTarget) {
                $teamMembers = User::where('reporting_to', $item->id)->where('status', 1)->get();

                $teamMembers->each(function ($member) use ($quarterlyTarget) {
                    $member->individual_totals = $this->calculateIndividualTotals($member, $quarterlyTarget);
                });

                $item->individual_totals = $this->calculateIndividualTotals($item, $quarterlyTarget);

                $teamMembersWithLeaderIds = $teamMembers->pluck('id')->push($item->id)->toArray();
                $teamTotals = $teamMembers->pluck('individual_totals')->push($item->individual_totals);

                $teamAgreementTotalAmount = $teamTotals->sum('individual_agreement_total_amount');
                $teamAgreementTotalUnits = $teamTotals->sum('individual_agreement_total_units');

                $teamBookingTotalAmount = $teamTotals->sum('individual_booking_total_amount');
                $teamBookingTotalUnits = $teamTotals->sum('individual_booking_total_units');

                $teamPendingTotalAmount = $teamTotals->sum('individual_pending_total_amount');
                $teamPendingTotalUnits = $teamTotals->sum('individual_pending_total_units');

                return [
                    // 'team_leader' => $item,
                    'id' => $item->id,
                    'name' => $item->name,
                    // 'short_name' => $item->short_name,
                    // 'team_members' => $teamMembers,
                    'amount' => $teamAgreementTotalAmount,
                    'units' => $teamAgreementTotalUnits,
                    'image' => $item->image ? url("uploads/$item->image") : '',
                    // 'team_booking_total_amount' => $teamBookingTotalAmount,
                    // 'team_booking_total_units' => $teamBookingTotalUnits,
                    // 'team_pending_total_amount' => $teamPendingTotalAmount,
                    // 'team_pending_total_units' => $teamPendingTotalUnits,
                ];
            });
            $teamLeadersListByRank = $teamLeadersRankList->sortByDesc('amount')->values();

            $teamLeadersListByRank->transform(function ($item, $key) {
            $item['rank'] = $key + 1;

            $val = $item['amount'] / 100000;
           $val = ceil($val);
           $finalVal = $val . ' lakh';

           $item['amount'] = $finalVal;

             return $item;
         });

         $teamLeadersRanksList =  $teamLeadersListByRank->take(10);

            $executivesRankList = $executivesList->map(function ($item, $key) use ($quarterlyTarget) {
            $individual_totals = $this->calculateIndividualTotals($item, $quarterlyTarget);
            $userAgreementTotalAmount = $individual_totals['individual_agreement_total_amount'];
            $userAgreementTotalUnits = $individual_totals['individual_agreement_total_units'];

            return [
                'id' => $item->id,
                'name' => $item->name,
                'units' => $userAgreementTotalUnits,
                'amount' => $userAgreementTotalAmount,
                'image' => $item->image ? url("uploads/$item->image") : '',
            ];
        });

        $executivesListByRank = $executivesRankList->sortByDesc('amount')->values();
        $executivesListByRank->transform(function ($item, $key) {
            $item['rank'] = $key + 1;

            $val = $item['amount'] / 100000;
            $val = ceil($val);
            $finalVal = $val . ' lakh';

            $item['amount'] = $finalVal;

            return $item;
        });

        $executivesRanksList =  $executivesListByRank->take(10);
        if (auth()->user()->hasRole('executive')) {
            $myrankingList = $executivesListByRank;
        } else {
             $myrankingList = $teamLeadersListByRank;
        }

        $myRanking = [
            'id' => $user->id,
            'name' => $user->name,
            "rank" => $myrankingList->where('id', $user->id)->first()['rank'] ?? 0,
            "amount" => $myrankingList->where('id', $user->id)->first()['amount'] ?? '0',
            'image' => $user->image ? url("uploads/{$user->image}") : '',
        ];

        // //teamleaders
        // $teamLeadersList = User::with('roles', 'getDsr')
        //     ->whereHas('roles', function ($query) {
        //         $query->where('id', 7);
        //     })
        //     ->where('branch_id', auth()->user()->branch_id)
        //     ->where('status', 1)
        //     ->get();

        // //executives
        // $executivesList = User::with('roles', 'getDsr')
        //     ->whereHas('roles', function ($query) {
        //         $query->where('id', 8);
        //     })
        //     ->where('branch_id', auth()->user()->branch_id)
        //     ->where('status', 1)
        //     ->get();

        // //teamleaders
        // $teamLeadersRankList = $teamLeadersList->map(function ($item, $key) {
        //     return [
        //         'id' => $item->id,
        //         'name' => $item->name,
        //         'amount' => DailySaleReport::where('user_id', $item->id)->sum('agreement_sale_value'),
        //         'image' => $item->image ? url("uploads/$item->image") : '',
        //     ];
        // });

        // //executives
        // $executivesRankList = $executivesList->map(function ($item, $key) {
        //     return [
        //         'id' => $item->id,
        //         'name' => $item->name,
        //         'amount' => DailySaleReport::where('user_id', $item->id)->sum('agreement_sale_value'),
        //         'image' => $item->image ? url("uploads/$item->image") : '',
        //     ];
        // });

        // $teamLeadersListByRank = $teamLeadersRankList->sortByDesc('amount')->values();
        // $executivesListByRank = $executivesRankList->sortByDesc('amount')->values();


        // $teamLeadersListByRank->transform(function ($item, $key) {
        //     $item['rank'] = $key + 1;

        //     $val = $item['amount'] / 100000;
        //     $val = ceil($val);
        //     $finalVal = $val . ' lakh';

        //     $item['amount'] = $finalVal;

        //     return $item;
        // });




        // $teamLeadersRanksList =  $teamLeadersListByRank->take(10);
        // $executivesRanksList =  $executivesListByRank->take(10);


        // if (auth()->user()->hasRole('executive')) {
        //     $myrankingList = $executivesListByRank;
        // } else {
        //     $myrankingList = $teamLeadersListByRank;
        // }

        // $val = DailySaleReport::where('user_id', $user->id)->sum('agreement_sale_value') / 100000;
        // $val = ceil($val);
        // $totalAmount = $val . ' lakh';


        // $myRanking = [
        //     'id' => $user->id,
        //     'name' => $user->name,
        //     "rank" => $myrankingList->where('id', $user->id)->first()['rank'] ?? 0,
        //     "amount" => $totalAmount,
        //     'image' => $user->image ? url("uploads/{$user->image}") : '',
        // ];


        $notificationCount = Notification::where('user_id', $user->id)->where('status', 0)->count();

        $taskStatusCount = Task::where(function ($query) use ($user) {
            $query->where('followup_by', $user->id)
                ->orWhere('created_by', $user->id);
        })
            ->where('task_completed_status', 0)
            ->count();

        if ($taskStatusCount > 0) {
            $addLead = 1;
        } else {
            $addLead = 0;
        }
        // $work_plan_status = 0;
        // $workPlan = DailyWorkPlan::where('user_id', Auth::user()->id)->where('date', now()->format('Y-m-d'))->first();
        // if ($workPlan) {
        //     $work_plan_status = 1;
        // }



        return response()->json([
            "message" => "Success",
            "data" => [
                "userName" => $userName,
                "subTitle" => $subTitle,
                "leadsDetails" => $leadsDetails,
                "myRanking" => $myRanking,
                "executivesRanksList" => $executivesRanksList,
                "teamLeadersRanksList" => $teamLeadersRanksList,

                "today_tasks" => $tasks ?? '',
                "unnattended" => $unnattended ?? '',
                'allocation_leads_count' => $allocationLeadsCount,
                "user_status" =>  $user->status,
                "Notification" => $notificationCount ?? 0,
                "task_create_status" => $addLead,
                'daily_work_plan_status' => '0'
                // 'work_plan_status' => strval($work_plan_status)
            ]
        ]);
    }
}
