<?php

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

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

class HomeNewController 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,
    //     ];

    //     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;
    //         }
    //     }
    //     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;
    //         }
    //     }

    //     return $individualTotal;
    // }

    public function index(Request $request)
    {
        /** @var User $user */
        $user = auth()->user();
        $id = $user->id;
        $currentDate = date('Y-m-d');
        $roles = \App\UserRole::with('getRoles')->where('user_id', $id)->get();

        $user->update([
            'device_type' => $request->device,
            'app_version' => $request->app_version,
            'device_name' => $request->device_name,
        ]);

        $userName = $user->name;
        $subTitle = 'Make Today Count!';
        $userRoles = $roles->pluck('getRoles.slug')->toArray();

        // Collect reporting users IDs based on roles
        $all_reporting_users_id_array = [];
        $authUser = auth()->user();

        $today_tasks_count = Task::where('created_by', $id)->whereNot('create_task_id', 1)->whereDate('created_at', today())->get()->count();

        $user = auth()->user();
        $id = $user->id;
        $leads = Lead::where('attended_by', $id)->get();
        $count = $leads->count();

        $projectTypeCounts = $leads->groupBy('project_type')->map->count();

        $leadsDetails = [
            'total' => $count,
            'Website' => [
                'id' => 1,
                'count' => Lead::where('attended_by', $id)->where('project_type', 1)->count() ?? 0,
                'colorCode' => '#6933CA',
            ],
            'Mobile_app' => [
                'id' => 2,
                'count' => Lead::where('attended_by', $id)->where('project_type', 2)->count() ?? 0,
                'colorCode' => '#FE795A',
            ],
            'Digital_marketing' => [
                'id' => 3,
                'count' => Lead::where('attended_by', $id)->where('project_type', 3)->count() ?? 0,
                'colorCode' => '#1CABE1',
            ],
            'Others' => [
                'id' => 4,
                'count' => Lead::where('attended_by', $id)->whereNotIn('project_type', [1, 2, 3])->count(),
                'colorCode' => '#00CF6B',
            ],
        ];

        $currentDate = date('Y-m-d');

        $id = $user->id;
        $lists = $request->list;
        $last_fifteenDays = Carbon::today()->subDays(15);
        $month = Carbon::now()->subMonth();
        $yesterday = Carbon::yesterday()->toDateString();
        $currentDate = date('Y-m-d');
        $data = '';

        $dateConditions = [
            1 => Carbon::today()->toDateString(),
            2 => $yesterday,
            3 => $last_fifteenDays,
            4 => $month,
        ];

        // Only fetch tasks if $lists has a valid condition
        if (isset($dateConditions[$lists])) {
            $tasks = Task::where('created_by', $id)
                ->where(function ($query) use ($lists, $dateConditions) {
                    if ($lists == 3) {
                        $query->whereDate('created_at', '>=', $dateConditions[$lists]);
                    } elseif ($lists == 4) {
                        $query->whereDate('created_at', '>=', $dateConditions[$lists]);
                    } else {
                        $query->whereDate('created_at', '=', $dateConditions[$lists]);
                    }
                })
                ->get();
        } else {
            $tasks = collect(); // Empty collection if no valid list option
        }

        // Predefine the counters for all activity types
        $activityCounts = [
            2 => 0, // Fresh Call
            3 => 0, // Follow Up Call
            4 => 0, // Virtual Meeting
            5 => 0, // Fresh Meeting
            6 => 0, // Follow Up Meeting
            7 => 0, // Office Visit
            8 => 0, // Direct Marketing
        ];

        // Calculate counts for each activity type
        foreach ($tasks as $task) {
            $activityCounts[$task->create_task_id] = ($activityCounts[$task->create_task_id] ?? 0) + 1;
        }

        // Prepare data response with all activity types
        $data = [
            ['activity_type' => 'Fresh Call', 'id' => 2, 'count' => strval($activityCounts[2]), 'colorCode' => '#4285F4'],
            ['activity_type' => 'Follow Up Call', 'id' => 3, 'count' => strval($activityCounts[3]), 'colorCode' => '#EA4335'],
            ['activity_type' => 'Virtual Meeting', 'id' => 4, 'count' => strval($activityCounts[4]), 'colorCode' => '#FBBC05'],
            ['activity_type' => 'Fresh Meeting', 'id' => 5, 'count' => strval($activityCounts[5]), 'colorCode' => '#34A853'],
            ['activity_type' => 'Follow Up Meeting', 'id' => 6, 'count' => strval($activityCounts[6]), 'colorCode' => '#A311A6'],
            ['activity_type' => 'Office Visit', 'id' => 7, 'count' => strval($activityCounts[7]), 'colorCode' => '#375559'],
            ['activity_type' => 'Direct Marketing', 'id' => 8, 'count' => strval($activityCounts[8]), 'colorCode' => '#C29B2A'],
        ];

        // WORK EFFICIENCY CALCULATION
        $task = Task::where('created_by', $id)->whereDate('created_at', $currentDate)->get();
        $count = $task->count();
        $calculations = DailyActivityCalculation::get();
        // $leadPoint = DailyActivityCalculation::find(1)->point ?? 0;

        // TASK COUNT,POINT AND CALCULATIONS
        $newLead = $task->where('create_task_id', 1)->count() ?? 0;
        $newLeadPoint = $calculations->where('create_task_id', 1)->first()->point;
        $totalNewLeadPoint = number_format($newLead * $newLeadPoint, 3);

        $freshCall = $task->where('create_task_id', 2)->count() ?? 0;
        $freshCallPoint = $calculations->where('create_task_id', 2)->first()->point;
        $totalFreshCallPoint = number_format($freshCall * $freshCallPoint, 3);

        $followUpCall = $task->where('create_task_id', 3)->count() ?? 0;
        $followUpCallPoint = $calculations->where('create_task_id', 3)->first()->point;
        $totalFollowUpCallPoint = number_format($followUpCall * $followUpCallPoint, 3);

        $virtualMeeting = $task->where('create_task_id', 4)->count() ?? 0;
        $virtualMeetingPoint = $calculations->where('create_task_id', 4)->first()->point;
        $totalVirtualMeetingPoint = number_format($virtualMeeting * $virtualMeetingPoint, 3);

        $freshMeeting = $task->where('create_task_id', 5)->count() ?? 0;
        $freshMeetingPoint = $calculations->where('create_task_id', 5)->first()->point;
        $totalFreshMeetingPoint = number_format($freshMeeting * $freshMeetingPoint, 3);

        $followUpMeeting = $task->where('create_task_id', 6)->count() ?? 0;
        $followUpMeetingPoint = $calculations->where('create_task_id', 6)->first()->point;
        $totalFollowUpMeetingPoint = number_format($followUpMeeting * $followUpMeetingPoint, 3);

        $officeVisit = $task->where('create_task_id', 7)->count() ?? 0;
        $officeVisitPoint = $calculations->where('create_task_id', 7)->first()->point;
        $totalOfficeVisitPoint = number_format($officeVisit * $officeVisitPoint, 3);

        $directMarketing = $task->where('create_task_id', 8)->count() ?? 0;
        $directMarketingPoint = $calculations->where('create_task_id', 8)->first()->point;
        $totalDirectMarketingPoint = number_format($directMarketing * $directMarketingPoint, 3);

        $d = [
            [
                'activity_type' => 'New Lead',
                'point' => strval($totalNewLeadPoint) ?? '0.0',
                'count' => strval($newLead) ?? '0',
            ],
            [
                'activity_type' => 'Fresh Call',
                'point' => strval($totalFreshCallPoint) ?? '0.0',
                'count' => strval($freshCall) ?? '0',
            ],
            [
                'activity_type' => 'Follow Up Call',
                'point' => strval($totalFollowUpCallPoint) ?? '0.0',
                'count' => strval($followUpCall) ?? '0',
            ],
            [
                'activity_type' => 'Virtual Meeting',
                'point' => strval($totalVirtualMeetingPoint) ?? '0.0',
                'count' => strval($virtualMeeting) ?? '0',
            ],
            [
                'activity_type' => 'Fresh Meeting',
                'point' => strval($totalFreshMeetingPoint) ?? '0.0',
                'count' => strval($freshMeeting) ?? '0',
            ],
            [
                'activity_type' => 'Follow up Meeting',
                'point' => strval($totalFollowUpMeetingPoint) ?? '0.0',
                'count' => strval($followUpMeeting) ?? '0',
            ],
            [
                'activity_type' => 'Office Visit',
                'point' => strval($totalOfficeVisitPoint) ?? '0.0',
                'count' => strval($officeVisit) ?? '0',
            ],
            [
                'activity_type' => 'Direct Marketing',
                'point' => strval($totalDirectMarketingPoint) ?? '0.0',
                'count' => strval($directMarketing) ?? '0',
            ],

        ];

        $totalPoints = 0.0;

        foreach ($d as $item) {
            $totalPoints += ($item['point'] * $item['count']);
        }

        $dailyWorkPlanPointDate = Carbon::parse($user->daily_work_plan_point_date)->format('Y-m-d');
        $today = Carbon::now()->format('Y-m-d');

        if ($dailyWorkPlanPointDate == $today) {
            $daily_work_plan_point = $user->daily_work_plan_point;
        } else {
            $daily_work_plan_point = 'Not Submitted';
        }

        // if ($task['total_points'] >= 8) {
        //     $color = '#008000';
        // } elseif ($task['total_points'] > 5 && $task['total_points'] < 8) {
        //     $color = '#FFA500';
        // } else {
        //     $color = '#FF0000';
        // }

        return response()->json([
            'status' => true,
            'message' => 'Success',
            'data' => [
                'userName' => $userName,
                'subTitle' => $subTitle,
                'leadsDetails' => $leadsDetails,
                'today_tasks' => $today_tasks_count ?? 0,
                'user_status' => $user->status,
                'Notification' => 31,
                'last_project' => 1,
                'daily_work_plan_status' => 0,
                'work_efficiency' => floor($totalPoints) ?? 0,
                'color' => '#494082',
                "total_project_value" => 0.0,
                "last_project_date" => "",
                "last_project_date_count" => 0,
                "daily_work_plan_point" => $daily_work_plan_point,
                // 'task_counts' => $tasks,
                'data' => $data,
                // 'task' => $task,
                // 'today_tasks' => $task_count ?? '0',
                // 'unnattended' => $unnattended ?? 0,
                // 'reallocated' => $reallocated ?? 0
                // 'allocation_leads_count' => $allocationLeadsCount,
                // 'Notification' => $notificationCount ?? 0,
                // 'task_create_status' => $addLead,
                // 'work_efficiency' => floor($task['total_points'] ?? 0.00),
                // 'last_sale_date' => $latestBooking,
                // 'last_sale_date_count' => strval($dateCount) ?? '',

            ],
        ]);
    }


    public function getLeadList()
    {
        $user = auth()->user();
        $id = $user->id;
        $leads = Lead::where('created_by', $id)->get();
        $count = $leads->count();
        $total_leads_data = [
            [
                'project_type' => 'Website',
                'id' => 1,
                'count' => Lead::where(['created_by' => $id, 'project_type' => 1])->count(),
                'colorCode' => '#FBBC05',
            ],
            [
                'project_type' => 'Mobile App',
                'id' => 2,
                'count' => Lead::where(['created_by' => $id, 'project_type' => 2])->count(),
                'colorCode' => '#34A853',
            ],
            [
                'project_type' => 'Digital Marketing',
                'id' => 3,
                'count' => Lead::where(['created_by' => $id, 'project_type' => 3])->count(),
                'colorCode' => '#279548',
            ],
            [
                'project_type' => 'Others',
                'id' => 4,
                'count' => Lead::where(['created_by' => $id])->whereNotIn('project_type', [1, 2, 3])->count(),
                'colorCode' => '#C254C5',
            ],
        ];

        return response()->json([
            'status' => true,
            'count' => $count,
            // 'data' => $leads,
            'total_leads_data' => $total_leads_data,
        ]);
    }


    public function rankList(Request $request)
    {
        $user = auth()->user();
        $id = auth()->id();
        $roles = \App\UserRole::with('getRoles')->where('user_id', $id)->get();
        $userRoles = $roles->pluck('getRoles.slug')->toArray();

        $authUser = auth()->user();

        $currentDate = date('Y-m-d');


        $myRank = SalesActivity::where('sales_owner', $id)->get();
        $myAmount = 0;
        foreach ($myRank as $val) {
            $myAmount = $myAmount + $val->project_value;
        }
        // dd($myRank);

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


        $otherUsersAmounts = SalesActivity::join('users as r', 'r.id', '=', 'sales_activities.sales_owner')
            ->where('sales_activities.sales_owner', '!=', $id)
            ->select('sales_activities.sales_owner', 'r.name', DB::raw('SUM(sales_activities.project_value) as total_amount'))
            ->groupBy('sales_activities.sales_owner', 'r.name')
            ->orderBY('total_amount')
            ->get();

        return response()->json([
            'message' => 'Success',
            'data' => [
                'my_ranking' => $myRanking,
                // 'executives_ranking' => $executivesRanksList,
                // 'team_leaders_ranking' => $teamLeadersRanksList,
                // 'sale_value' => $sale_value ?? '0',
                // 'sales_this_quarter' => strval($sales_this_quarter) ?? '0',
                'rank_list' => $otherUsersAmounts,
                // 'team_leaders_ranking' => 0,
                // 'sale_value' => '0',
                'sales_this_quarter' => SalesActivity::get()->count(),
            ],
        ]);
    }
}
