<?php

namespace App\Api\Http\Resources\Leads;

use App\Api\Http\Resources\Budget\BudgetResource;
use App\Api\Http\Resources\LeadCategory\LeadCategoryResource;
use App\Api\Http\Resources\LeadStage\LeadStageResource;
use App\Api\Http\Resources\PreferredProject\PreferredProjectResource;
use App\Api\Http\Resources\PriceList\PriceListResource;
use App\Api\Http\Resources\Project\ProjectResource;
use App\Api\Http\Resources\ProjectType\ProjectTypeResource;
use App\Api\Http\Resources\Sources\SourceResource;
use App\Api\Http\Resources\User\UserResource;
use App\Lead;
use App\Source;
use App\Task;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class LeadResource extends JsonResource
{
    public function toArray($request): array
    {
        $check = false;
        $check_email = false;
        $check_mobile_task = false;
        $check_email_task = false;
        $authUser = auth()->user();
        $UserIds = $authUser->getAllReportingUsersIds();
        $mobile = $this->mobile;
        $phone_code = $this->phone_code;
        $email = $this->email;
        $fifteenDays = now()->subDays(15);
        $threeMonthBefore = now()->subMonths(3);
        $lastAttendedBy = "";



        if (!empty($mobile)) {

            $check = Lead::where('mobile', $mobile)
                ->orderBy('created_at', 'desc')
                ->skip(1)
                ->take(1)
                ->first();

            if (!$check) {
                $mbb = $phone_code . $mobile;
                $check = Lead::where('mobile', $mbb)
                    ->orderBy('created_at', 'desc')
                    ->skip(1)
                    ->take(1)
                    ->first();
                if (!$check) {
                    $check = Lead::where('phone_code', $phone_code)
                        ->where('mobile', $mobile)
                        ->orderBy('created_at', 'desc')
                        ->skip(1)
                        ->take(1)
                        ->first();

                    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 . '%')->orderBy('created_at', 'desc')->skip(1)->take(1)->first();
                        }
                    }
                }
            }
        }

        if (!empty($email)) {
            $check_email = Lead::where('email', $email)
                ->orderBy('created_at', 'desc')
                ->skip(1)
                ->take(1)
                ->first();
        }



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


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



        if ($check && $check->created_at >= $threeMonthBefore && $check->attended_by) {

            $attendedUser = User::where('id', $check->attended_by)
                ->where('status', 1)->first();
            $lastAttendedBy = $attendedUser ? $attendedUser->name : '';
        } elseif ($check_email && $check_email->created_at >= $threeMonthBefore && $check_email->attended_by) {

            $attendedUser = User::where('id', $check_email->attended_by)
                ->where('status', 1)->first();
            $lastAttendedBy = $attendedUser ? $attendedUser->name : '';
        } elseif ($check_mobile_task && $check_mobile_task->created_at >= $fifteenDays) {

            $attendedUser = User::where('id', $check_mobile_task->created_by)
                ->where('status', 1)
                ->first();
            $lastAttendedBy = $attendedUser ? $attendedUser->name : '';
        } elseif ($check_email_task && $check_email_task->created_at >= $fifteenDays) {

            $attendedUser = User::where('id', $check_email_task->created_by)
                ->where('status', 1)
                ->first();
            $lastAttendedBy = $attendedUser ? $attendedUser->name : '';
        }
        // $date = Carbon::parse(2023-06-05);
        // if (!empty($this->allocation_date)) {
        //     $allocationDate = Carbon::parse($this->allocation_date);
        
        //     if ($date->greaterThanOrEqualTo($allocationDate)) {
               
        //         $currentDateTime = Carbon::now(); // Get the current date and time
        //         $addedTime = $allocationDate->copy()->addHours(12);
            
        //         // Calculate the difference in minutes
        //         $diffInMinutes = $currentDateTime->diffInMinutes($addedTime);
        //     } else {
        //         $diffInMinutes = 0;
        //     }
        // } else {
        //     $diffInMinutes = 0;
        // }
        // if($this->allocation_date != ''){
        //     $currentDateTime = Carbon::now(); // Get the current date and time
        //     $allocatedTime = Carbon::parse($this->allocation_date); 
        //      $addedTime = $allocatedTime->copy()->addHours(12);
    
        //     // Calculate the difference in minutes
        //     $diffInMinutes = $currentDateTime->diffInMinutes($addedTime);
        // }else{
        //     $diffInMinutes = 0;
        // }

        if(!empty($this->getSource)){
            $id = $this->getSource->id;
            $source  = Source::find($id);
            if($source && $source->status ==0){
                $status = 0;
            }else{
                $status = 1;
            }

        }
        else{
            $status = 1;
        }
        
        if (!empty($this->allocation_date) && $status ==0) {
            $allocationDate12 = Carbon::parse($this->allocation_date)->startOfDay();
            $date = Carbon::parse('2023-06-05')->startOfDay();
            
            $allocationDate = Carbon::parse($this->allocation_date);
               
            if ($allocationDate12->greaterThanOrEqualTo($date)) {
                $currentDateTime = Carbon::now(); // Get the current date and time
                $addedTime = $allocationDate->copy()->addHours(12);
            
                // Calculate the difference in minutes
                $diffInMinutes = $currentDateTime->diffInMinutes($addedTime);
                $diffinSeconds = $currentDateTime->diffInSeconds($addedTime);
                if($diffInMinutes > 0 && $diffInMinutes<=180 ){
                $colorCode = '#FF0000';
                }
                elseif($diffInMinutes > 180 && $diffInMinutes<=360){
                    $colorCode = '#FF5733';
                }else{
                    $colorCode = '#008000';
                }
                
            } else {
                $diffInMinutes = 0;
                $diffinSeconds = 0;
                $colorCode = '';
            }
        } else {
            $diffInMinutes = 0;
            $diffinSeconds = 0;
            $colorCode = '';
        }

        $attended_by = $this->attended_by;

        $user = User::find($attended_by);
        if(auth()->user()->hasRole('sales-head') && $user->hasRole('team-leader')){
            $team_leader = $this->getAttendedBy->name ?? '';
        }elseif(auth()->user()->hasRole('sales-head') && !$user->hasRole('team-leader')){
            $team_leader = $this->getAttendedBy->getReportingTo->name ?? '';
        }else{
            $team_leader = "";
        }

        // $team_leader = $users;

        $call_log = $this->getCallLog()->latest()->first();
        $formattedDateTime = '';
        if (!empty($call_log)) {
            $timestamp = $call_log->created_at;
            $formattedDateTime = Carbon::parse($timestamp)->format('Y-m-d h:i A');
        }

        if($this->lead_bank_reallocate == 1){
            $re_attended_by = $this->getLeadBankAttendedBy ? $this->getLeadBankAttendedBy->name : "";
            $source = [
                'name' => "Re Allocated",
            ];
            $allocation = "";
            $lead_date = "";
            $sales_person = "";
        }else{
            $re_attended_by = $this->getReAttendedBy ? $this->getReAttendedBy->name : "";
            $source = $this->source ? new SourceResource($this->whenLoaded('getSource')) : (object)[];
            $allocation = (string)$this->allocation_date;
            $lead_date = $this->lead_date ?: $this->created_at->format('Y-m-d H:i:s');
            $sales_person = (string)$this->getAttendedBy ? $this->getAttendedBy->name : "";
        }

        return [
            'id' => $this->id,
            'enquirer_name' => (string)$this->enquirer_name,
            'phone_code' => (string)$this->phone_code,
            'mobile' => (string)$this->mobile,
            'alt_mobile' => (string)$this->alt_mobile,
            'email' => (string)$this->email,
            'source' => $source,
            'chat' => (string)$this->chat,
            // 'preferred_project' => $this->preferred_project ? new ProjectResource($this->whenLoaded('getPreferredProject')) : (object)[],
            'preferred_project' => $this->getPreferredProject ? new ProjectResource($this->getPreferredProject) : (object)[],
            'created_at ' => (string)$this->created_at->format('Y-m-d H:i:s'),
            'pref_name' => (string)$this->pref_name,
            // 'email' => (string)$this->email,
            // 'duplicate_entry' => $this->duplicate_entry,
            // 'sales_head_approval' => (bool)$this->sales_head_approval,
            // 'lost_lead_approval' => (bool)$this->lost_lead_approval,
            // 'pan_no' => (string)$this->pan_no,
            // 'whatsapp_no' => (string)$this->whatsapp_no,
            'project_type' => $this->getProjectType ? new ProjectTypeResource($this->whenLoaded('getProjectType')) : (object)[],
            'preferred_project_id' => (string) $this->preferred_project,
            'project_type_id' => (string) $this->project_type,
            'enquirer_date' =>  $lead_date,
            'budget' => new BudgetResource($this->whenLoaded('getBudget')),
            'lead_category' => new LeadCategoryResource($this->whenLoaded('getLeadCategory')),
            'lead_category_id' => (string)$this->lead_category,
            'country' => (string)$this->country,
            // 'lead_percentage' => (int)$this->lead_percentage,
            'allocation_date' => $allocation,
            'allocation_time' =>   (string)$this->allocation_date ? Carbon::createFromFormat('Y-m-d H:i:s', $this->allocation_date)->format('H:i:s'):'00:00:00',
            "allocation_time_12" =>(string)$this->allocation_date ? Carbon::createFromFormat('Y-m-d H:i:s', $this->allocation_date)->addHours(12)->format('H:i:s'):'00:00:00',
            "lead_allocation_time"=>$diffInMinutes,
            "lead_allocation_time_seconds"=> $diffinSeconds,
            'color_code' =>$colorCode,
            'remarks' => (string)$this->remarks,
            'residential_status' => (string)$this->residential_status,
            // 'gender' => (string)$this->gender,
            // 'dob' => (string)$this->dob,
            // 'age' => (string)$this->age,
            // 'home_loan_assistance' => (string)$this->home_loan_assistance,
            // 'self_occupancy' => (string)$this->self_occupancy,
            // 'profession' => (string)$this->profession,
            // 'phone_office' => (string)$this->phone_office,
            // 'address' => (string)$this->address,
            // 'country' => (string)$this->country,
            // 'state' => (string)$this->state,
            'location' => (string)$this->location,
            'location_id' => (string)$this->location_id,
            // 'desom' => (string)$this->desom,
            // 'post' => (string)$this->post,
            // 'taluk' => (string)$this->taluk,
            // 'pin' => (string)$this->pin,
            // 'no_of_bedrooms' => (string)$this->no_of_bedrooms,
            // 'saleable_area' => (string)$this->saleable_area,
            // 'preferred_floor' => (string)$this->preferred_floor,
            // 'preferred_city' => (string)$this->preferred_city,
            // 'preferred_location' => (string)$this->preferred_location,
            // 'organization' => (string)$this->organization,
            // 'designation' => (string)$this->designation,
            // 'department' => (string)$this->department,
            // 'lead_date' => (string)$this->lead_date,
            // 'unique_id' => (string)$this->unique_id,
            // 'status' => (string)$this->status,
            // 'is_ceo_verified' => (string)$this->is_ceo_verified,
            'lead_stage_id' => new LeadStageResource($this->whenLoaded('getLeadStage')),
            // 'sale_status' => (string)$this->sale_status,
            // 'fb_form_name' => (string)$this->fb_form_name,
            // 'show_in_salesperson_actions' => (string)$this->show_in_salesperson_actions,
            // 'updated_at' => (string)$this->updated_at,
            // 'unit_id' => new PriceListResource($this->whenLoaded('getUnit')),
            // 'nationality' => (string)$this->nationality,
            // 'building_no' => (string)$this->building_no,
            // 'bank_account_no' => (string)$this->bank_account_no,
            // 'invoice_no' => (string)$this->invoice_no,
            // 'booking_form_received' => (string)$this->booking_form_received,
            // 'oc_details' => (string)$this->oc_details,
            // 'possession_remarks' => (string)$this->possession_remarks,
            // 'is_verified' => (string)$this->is_verified,
            // 'verification_remarks' => (string)$this->verification_remarks,
            // 'leads_maker_status' => (string)$this->leads_maker_status,
            // 'campaign_name' => (string)$this->campaign_name,
            // 'adset_name' => (string)$this->adset_name,
            // 'ad_name' => (string)$this->ad_name,
            // 'chat' => (string)$this->chat,
            // 'attended_by' => new UserResource($this->whenLoaded('getAttendedBy')),
            'team_leader' => $team_leader,
            'longitude' => $this->longitude ?? '',
            'latitude' => $this->latitude ?? '',
            'call_id' => $formattedDateTime,
            'last_attended' => (string)$lastAttendedBy,
            'last_attended_name'=>$sales_person,
            'lead_time' => (string)$this->created_at->format('H:i:s'),
            're_attended_by' => (string)$re_attended_by,
        ];
    }
}
