<?php

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

use App\Api\Http\Requests\Lead\CallLeadListRequest;
use App\Api\Http\Requests\Lead\LeadAllocationRequest;
use App\Api\Http\Resources\Leads\LeadCollection;
use App\Api\Http\Resources\User\UserCollection;
use App\Http\Controllers\Controller;
use App\Http\Requests\Dashboard\DailyActivity\DailyActivityStoreRequest;
use App\Lead;
use App\Helpers\ActivityLog;
use App\Location;
use App\Notification;
use App\Notifications\AllocationNotification;
use App\PreferredProject;
use App\Task;
use App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
use Illuminate\Http\Request;

class CallLeadListController extends Controller
{
    public function store(CallLeadListRequest $request)
    {
        $leadIds = $request->lead_id;
        foreach ($leadIds as $id) {
            $lead = Lead::find($id);
            $lead->call_lead_list = 1;
            $lead->call_lead_list_date = now();
            $lead->save();
        }

        return $this->success(
            'Lead Added To Call List Successfully!',
        );
    }

    public function index(Request $request): LeadCollection
    {
        $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', 'head-sales')) { //Except superadmin and admin
            $all_reporting_users_id_array = $authUser->getAllReportingUsersIds();
            array_push($all_reporting_users_id_array, $authUser->id);
        }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)
            ->pluck('id')
            ->toArray();
        }
        // $userRoles = auth()
        //     ->user()
        //     ->userRoles();

        // $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);
        // }
        $leads = QueryBuilder::for(Lead::class)
            ->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')
            ->where('call_lead_list', 1)
            ->defaultSort('-created_at')

            ->allowedFilters([
                AllowedFilter::callback('is_today', function (Builder $query, $value) {
                    $query->whereDate('created_at', today());
                }),
                AllowedFilter::callback('project_type', function (Builder $query, $value) {
                    if ($value == 0) {
                        $query->whereNull('project_type');
                    } else {
                        $query->where('project_type', $value);
                    }
                }),

                AllowedFilter::exact('id'),
                // AllowedFilter::exact('project_type', 'getProjectType.id'),
                AllowedFilter::exact('source', 'getSource.id'),
                AllowedFilter::exact('project', 'getPreferredProject.id'),
                AllowedFilter::scope('starts_between'),

            ])
            ->jsonPaginate()
            ->appends(request()->query());

        return (new LeadCollection($leads))->additional(['message' => 'Leads list!']);
    }
    public function storeTasks(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->call_lead_list = 2;
                $lead->call_lead_task_date = now();
                $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.',
            );
        }
    }

}
