<?php

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

use app\Api\Http\Requests\DailyActivity\DailyActivityRequest;
use App\Api\Http\Resources\TaskType\TaskTypeCollection;
use App\Api\Http\Resources\User\UserCollection;
use App\Api\Http\Resources\User\UserResource;
use App\CreateTask;
use App\Customer;
use App\DailyActivityCalculation;
use App\DailyWorkPlan;
use App\DsrBooking;
use App\DsrSplit;
use App\Helpers\ActivityLog;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Requests\DailyActivity\DailyActivityStoreRequest;
use App\Lead;
use App\Location;
use App\PreferredProject;
use App\Task;
use App\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class DailyActivityController extends Controller
{
    public function DailyActivitylist()
    {
        $taskTypes = CreateTask::where('status', 1)->get();
        return response()->json([
            'status' => true,
            'task_types' => $taskTypes,
        ]);

        // return $this->success(
        //     'Task Types!',
        //     new TaskTypeCollection($taskTypes)
        // );
    }

    public function store(DailyActivityStoreRequest $request): JsonResponse
    {
        // try {
        //     $user = auth()->user();

        //     if ($request->lead_id == null) {

        //         if ($request->mobile) {
        //             $lead = Lead::where('mobile', 'LIKE', $request->mobile)
        //                 ->where(function ($query) use ($user) {
        //                     $query->where('created_by', $user->id)
        //                         ->orWhere('attended_by', $user->id);
        //                 })
        //                 ->first();

        //             if (!$lead) {
        //                 $lead = new Lead();
        //                 $lead->enquirer_name = $request->name;
        //                 $lead->mobile = $request->mobile;
        //                 $lead->phone_code = $request->phone_code;
        //                 $lead->source = $request->source;
        //                 $lead->lead_date = date('Y-m-d');
        //                 $lead->attended_by = $user->id;
        //                 $lead->created_by = $user->id;
        //                 $lead->updated_by = $user->id;
        //                 $lead->is_attended = 1;
        //                 $check = false;
        //                 $check_mobile_task = false;
        //                 $fifteenDays = now()->subDays(15);
        //                 $threeMonthBefore = now()->subMonths(3);

        //                 $mobile = $request->mobile;
        //                 $phoneCode = $request->phone_code;

        //                 if (!empty($mobile)) {

        //                     $check = Lead::where('mobile', $mobile)->get()->last();

        //                     if (!$check) {
        //                         $mbb = $phoneCode . $mobile;
        //                         $check = Lead::where('mobile', $mbb)->get()->last();
        //                         if (!$check) {
        //                             $check = Lead::where('mobile', $mobile)->get()->last();

        //                             if (!$check) {

        //                                 $n = 10;

        //                                 if (strlen($mobile) == 9) {

        //                                     $n = 9;
        //                                 }

        //                                 if (strlen($mobile) == 8) {

        //                                     $n = 8;
        //                                 }

        //                                 $start = strlen($mobile) - $n;
        //                                 $last_str = substr($mobile, $start);
        //                                 if ($start >= 0) {
        //                                     $check = Lead::where('mobile', 'LIKE', '%' . $last_str . '%')->get()->last();
        //                                 }
        //                             }
        //                         }
        //                     }
        //                 }


        //                 if ($check) {
        //                     $check_mobile_task = Task::where('lead_id', $check->id)->get()->last();
        //                 }

        //                 if ($check && $check->created_at >= $threeMonthBefore) {
        //                     $lead->duplicate_entry = 'yes';
        //                     $lead->sales_head_approval = 0;
        //                 } elseif ($check_mobile_task && $check_mobile_task->created_at >= $fifteenDays) {

        //                     $lead->duplicate_entry = 'yes';
        //                     $lead->sales_head_approval = 0;
        //                 }
        //                 $lead->save();
        //                 $leadId = $lead->id;
        //             } else {
        //                 $leadId = $lead->id;
        //             }
        //         }
        //     } else {
        //         $leadId = $request->lead_id;
        //     }

        //     if (auth()->user()->hasRole('team-leader')) {
        //         $user_id = $request->user_id;
        //     } else {
        //         $user_id = $user->id;
        //     }


        //     $taskData = [
        //         'lead_id' => $leadId,
        //         'create_task_id' => $request->create_task_id,
        //         'lead_category' => $request->lead_category,
        //         'schedule_date' => date('Y-m-d'),
        //         'project' => $request->project,
        //         'lead_stage' => $request->lead_stage,
        //         'created_by' => $user_id,
        //         'task_completed_status' => 1,
        //         'latitude' => $request->latitude,
        //         'longitude' => $request->longitude,
        //         'remarks' => $request->remarks,
        //         'followup_by' => $user_id,
        //         'place_address' => $request->place_address,

        //     ];

        //     if ($request->has('image')) {
        //         $taskData['image'] = $request->file('image')->store('Task', 'uploads');
        //     }

        //     $task = Task::create($taskData);
        //     if ($task) {
        //         $project = PreferredProject::find($request->project);
        //         $type = Null;
        //         if ($project) {
        //             $type = $project->project_type;
        //         }
        //         if ($request->location_id != 15 && $request->location_id != 16 && $request->location_id != null) {
        //             $locat = Location::find($request->location_id);
        //             $location = $locat->name;
        //         } else {
        //             $location = $request->location_name ?? '';
        //         }
        //         $lead = Lead::find($task->lead_id);
        //         $lead->lead_stage_id = $request->lead_stage ? $request->lead_stage : NULL;
        //         $lead->lead_category = $request->lead_category ? $request->lead_category : NULL;
        //         $lead->preferred_project = $request->project ? $request->project : NULL;
        //         $lead->latitude = $request->latitude ? $request->latitude : NULL;
        //         $lead->longitude = $request->longitude ? $request->longitude : NULL;
        //         $lead->city = $request->city ? $request->city : NULL;
        //         $lead->country = $request->country ? $request->country : NULL;
        //         $lead->residential_status = $request->residential_status ? $request->residential_status : NULL;
        //         $lead->project_type = $type;
        //         $lead->location = $location;
        //         $lead->place_address = $request->place_address ? $request->place_address : NULL;
        //         $lead->location_id = $request->location_id;
        //         $lead->is_attended = 1;
        //         $lead->phone_code = $request->phone_code;
        //         $lead->save();
        //         //add-coins-for-referred-customer
        //         if ($task->create_task_id == 2 && filled($lead->referred_customer_id)) {
        //             addCustomerCoins($lead->referred_customer_id, 250'0', 'Site Visits', $lead->id);
        //         }

        //         $activitySubject = $user->name . ' added a new daily task with ID : ' . $task->id;
        //         ActivityLog::addToLog($activitySubject, 'leads');

        //         return $this->success(
        //             'Daily Task has been added successfully.',
        //         );
        //     }
        // } catch (\Throwable $th) {
        //     info($th);
        //     return $this->error(
        //         'Something went wrong,Please try again.',
        //     );
        // }

        try {
            $user = auth()->user();

            if ($request->lead_id == null) {

                if ($request->mobile) {
                    $lead = Lead::where('mobile', 'LIKE', $request->mobile)
                        ->where(function ($query) use ($user) {
                            $query->where('created_by', $user->id)
                                ->orWhere('attended_by', $user->id);
                        })
                        ->first();

                    if (!$lead) {
                        $lead = new Lead();
                        $lead->enquirer_name = $request->name;
                        $lead->phone_code = $request->phone_code;
                        $lead->mobile = $request->mobile;
                        $lead->project_type = $request->project_type;
                        $lead->preferred_project = $request->preferred_project;
                        $lead->attended_by = $user->id;
                        $lead->created_by = $user->id;
                        $lead->updated_by = $user->id;
                        $lead->is_attended = 1;
                        $lead->lead_category = $request->lead_status;
                        $lead->source = $request->source;
                        $lead->remarks = $request->remarks;
                        $lead->save();

                    }
                }
            } else {
                $leadId = $request->lead_id;
            }

            $taskData = [
                'lead_id' => $leadId,
                'create_task_id' => $request->create_task_id,
                'lead_category' => $request->lead_category,
                'schedule_date' => date('Y-m-d'),
                'project' => $request->project,
                'lead_stage' => $request->lead_stage,
                'created_by' => $user->id,
                'task_completed_status' => 1,
                'latitude' => $request->latitude,
                'longitude' => $request->longitude,
                'remarks' => $request->remarks,
                'followup_by' => $user,
                'place_address' => $request->place_address,

            ];

            if ($request->has('image')) {
                $taskData['image'] = $request->file('image')->store('Task', 'uploads');
            }

            $task = Task::create($taskData);
            if ($task) {
                $project = PreferredProject::find($request->project);
                $type = Null;
                if ($project) {
                    $type = $project->project_type;
                }
                // if ($request->location_id != 15 && $request->location_id != 16 && $request->location_id != null) {
                //     $locat = Location::find($request->location_id);
                //     $location = $locat->name;
                // } else {
                //     $location = $request->location_name ?? '';
                // }
                $lead = Lead::find($task->lead_id);
                $lead->lead_stage_id = $request->lead_stage ? $request->lead_stage : NULL;
                $lead->lead_category = $request->lead_category ? $request->lead_category : NULL;
                $lead->preferred_project = $request->project ? $request->project : NULL;
                $lead->latitude = $request->latitude ? $request->latitude : NULL;
                $lead->longitude = $request->longitude ? $request->longitude : NULL;
                $lead->city = $request->city ? $request->city : NULL;
                $lead->country = $request->country ? $request->country : NULL;
                $lead->residential_status = $request->residential_status ? $request->residential_status : NULL;
                $lead->project_type = $type;
                // $lead->location = $location;
                $lead->place_address = $request->place_address ? $request->place_address : NULL;
                $lead->location_id = $request->location_id;
                $lead->is_attended = 1;
                $lead->phone_code = $request->phone_code;
                $lead->save();
                return $this->success(
                    'Daily Task has been added successfully.',
                );
            }

        } catch (\Throwable $th) {
            info($th);
            return $this->error(
                'Something went wrong,Please try again.',
            );
        }
    }

    public function Report()
    {
        $user = auth()->user();
        $currentDate = date('Y-m-d');
        $id = $user->id;

        $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);

        $data = [
            [
                '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 ($data as $item) {
            $totalPoints += ($item['point'] * $item['count']);
        }

        $colorCode = '#37D086';

        return [
            'status' => true,
            'message' => 'Report Summary',
            'current_date' => $currentDate,
            'total_points' => number_format($totalPoints, 3),
            'color_code' => $colorCode,
            'total_tasks' => $count,
            'data' => $data,
        ];
    }




    public function usersList()
    {
        $authUser = auth()->user();

        $users = User::where('reporting_to', $authUser->id)
            ->where('status', 1)
            ->get();
        $users->prepend($authUser);

        $usersData = $users->map(function ($user) {
            return [
                'id' => $user->id,
                'name' => $user->name,
            ];
        });

        return [
            'status' => true,
            'message' => "Users List",
            'data' => $usersData,

        ];
    }

    public function storeUnattended(DailyActivityStoreRequest $request): JsonResponse
    {
        try {
            $user = auth()->user();

            if ($request->lead_id == null) {

                if ($request->mobile) {
                    $lead = Lead::where('mobile', 'LIKE', $request->mobile)
                        ->where(function ($query) use ($user) {
                            $query->where('created_by', $user->id)
                                ->orWhere('attended_by', $user->id);
                        })
                        ->first();

                    if (!$lead) {
                        $lead = new Lead();
                        $lead->enquirer_name = $request->name;
                        $lead->mobile = $request->mobile;
                        $lead->phone_code = $request->phone_code;
                        $lead->source = $request->source;
                        $lead->lead_date = date('Y-m-d');
                        $lead->attended_by = $user->id;
                        $lead->created_by = $user->id;
                        $lead->updated_by = $user->id;
                        $lead->is_attended = 1;
                        $check = false;
                        $check_mobile_task = false;
                        $fifteenDays = now()->subDays(15);
                        $threeMonthBefore = now()->subMonths(3);

                        $mobile = $request->mobile;
                        $phoneCode = $request->phone_code;

                        if (!empty($mobile)) {

                            $check = Lead::where('mobile', $mobile)->get()->last();

                            if (!$check) {
                                $mbb = $phoneCode . $mobile;
                                $check = Lead::where('mobile', $mbb)->get()->last();
                                if (!$check) {
                                    $check = Lead::where('mobile', $mobile)->get()->last();

                                    if (!$check) {

                                        $n = 10;

                                        if (strlen($mobile) == 9) {

                                            $n = 9;
                                        }

                                        if (strlen($mobile) == 8) {

                                            $n = 8;
                                        }

                                        $start = strlen($mobile) - $n;
                                        $last_str = substr($mobile, $start);
                                        if ($start >= 0) {
                                            $check = Lead::where('mobile', 'LIKE', '%' . $last_str . '%')->get()->last();
                                        }
                                    }
                                }
                            }
                        }


                        if ($check) {
                            $check_mobile_task = Task::where('lead_id', $check->id)->get()->last();
                        }

                        if ($check && $check->created_at >= $threeMonthBefore) {
                            $lead->duplicate_entry = 'yes';
                            $lead->sales_head_approval = 0;
                        } elseif ($check_mobile_task && $check_mobile_task->created_at >= $fifteenDays) {

                            $lead->duplicate_entry = 'yes';
                            $lead->sales_head_approval = 0;
                        }
                        $lead->save();
                        $leadId = $lead->id;
                    } else {
                        $leadId = $lead->id;
                    }
                }
            } else {
                $leadId = $request->lead_id;
            }

            $user_id = $user->id;


            $taskData = [
                'lead_id' => $leadId,
                'create_task_id' => $request->create_task_id,
                'lead_category' => $request->lead_category,
                'schedule_date' => date('Y-m-d'),
                'project' => $request->project,
                'lead_stage' => $request->lead_stage,
                'created_by' => $user_id,
                'task_completed_status' => 1,
                'latitude' => $request->latitude,
                'longitude' => $request->longitude,
                'remarks' => $request->remarks,
                'followup_by' => $user_id,
                'place_address' => $request->place_address,

            ];

            if ($request->has('image')) {
                $taskData['image'] = $request->file('image')->store('Task', 'uploads');
            }

            $task = Task::create($taskData);
            if ($task) {
                $project = PreferredProject::find($request->project);
                $type = Null;
                if ($project) {
                    $type = $project->project_type;
                }
                if ($request->location_id != 15 && $request->location_id != 16 && $request->location_id != null) {
                    $locat = Location::find($request->location_id);
                    $location = $locat->name;
                } else {
                    $location = $request->location_name ?? '';
                }
                $lead = Lead::find($task->lead_id);
                $lead->lead_stage_id = $request->lead_stage ? $request->lead_stage : NULL;
                $lead->lead_category = $request->lead_category ? $request->lead_category : NULL;
                $lead->preferred_project = $request->project ? $request->project : NULL;
                $lead->latitude = $request->latitude ? $request->latitude : NULL;
                $lead->longitude = $request->longitude ? $request->longitude : NULL;
                $lead->city = $request->city ? $request->city : NULL;
                $lead->country = $request->country ? $request->country : NULL;
                $lead->residential_status = $request->residential_status ? $request->residential_status : NULL;
                $lead->project_type = $type;
                $lead->location = $location;
                $lead->place_address = $request->place_address ? $request->place_address : NULL;
                $lead->location_id = $request->location_id;
                $lead->is_attended = 1;
                $lead->phone_code = $request->phone_code;
                $lead->save();
                $activitySubject = $user->name . ' added a new daily task with ID : ' . $task->id;
                ActivityLog::addToLog($activitySubject, 'leads');

                return $this->success(
                    'Daily Task has been added successfully.',
                );
            }
        } catch (\Throwable $th) {
            info($th);
            return $this->error(
                'Something went wrong,Please try again.',
            );
        }
    }
}
