<?php

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

use App\Api\Http\Requests\Rono\RonoRequest;
use App\CallLog;
use App\Http\Controllers\Controller;
use App\Lead;
use App\LeadBank;
use App\Location;
use App\PreferredProject;
use App\Residence;
use App\Runo;
use App\SalesActivity;
use App\Source;
use App\Task;
use App\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RonoController extends Controller
{
    public function store(RonoRequest $request)
    {
        $callLog = CallLog::where('call_id', $request->callId)->exists();

        if (($request->phoneNumber) && (!$callLog)) {

            $user = User::where('callerId', $request->callerId)->first();

            if ($user->hasRole('team-leader') || $user->hasRole('executive') || $user->hasRole('sales-head')) {

                $phone_number = $request->phoneNumber;
                $phone_code = substr($phone_number, 0, 3);
                $phone = substr($phone_number, 3);
                if ($phone_code == '+91' && strlen($phone_number) == 13) {
                    $taskcreateId = 17;
                } else {
                    $taskcreateId = 18;
                }

                $phoneNumber = $request->phoneNumber;

                $lead = Lead::whereRaw("SUBSTRING(mobile, -10) = ?", substr($phoneNumber, -10))
                    ->where(function ($query) use ($user) {
                        $query->where('created_by', $user->id)
                            ->orWhere('attended_by', $user->id);
                    })
                    ->first();
                $new = 'no';
                if (!$lead) {

                    $lead = new Lead();
                    $lead->enquirer_name = $request->name;
                    $lead->mobile = $request->phoneNumber;
                    $lead->source = 77;
                    $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;
                    $lead->runo = 1; //runo default value 0
                    $check = false;
                    $check_mobile_task = false;
                    $fifteenDays = now()->subDays(15);
                    $threeMonthBefore = now()->subMonths(3);
                    $mobile =  $request->phoneNumber;


                    if (!empty($mobile)) {

                        $check = Lead::where('mobile', $mobile)
                            ->where(function ($query) use ($user) {
                                $query->where('created_by', $user->id)
                                    ->orWhere('attended_by', $user->id);
                            })->get()->last();

                        if (!$check) {
                            $mbb = $mobile;
                            $check = Lead::where('mobile', $mbb)
                                ->where(function ($query) use ($user) {
                                    $query->where('created_by', $user->id)
                                        ->orWhere('attended_by', $user->id);
                                })->get()->last();
                            if (!$check) {
                                $check = Lead::where('mobile', $mobile)
                                    ->where(function ($query) use ($user) {
                                        $query->where('created_by', $user->id)
                                            ->orWhere('attended_by', $user->id);
                                    })->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 . '%')
                                            ->where(function ($query) use ($user) {
                                                $query->where('created_by', $user->id)
                                                    ->orWhere('attended_by', $user->id);
                                            })->get()->last();
                                    }
                                }
                            }
                        }
                    }

                    if ($check) {
                        $check_mobile_task = Task::where('lead_id', $check->id)
                            ->where(function ($query) use ($user) {
                                $query->where('created_by', $user->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;
                }

                $taskCount = Task::where('lead_id', $leadId)->whereIn('create_task_id', [15, 17, 16, 18])->count();
                if ($taskCount == 0) {
                    $new = 'yes';
                }
                if ($request->duration > 30 && $new == 'yes') {
                    $taskData = [
                        'lead_id' =>  $leadId,
                        'create_task_id' => $taskcreateId,
                        'schedule_date' => date('Y-m-d'),
                        'created_by' => $user->id,
                        'task_completed_status' => 1,
                        'followup_by' => $user->id,
                        'runo_start_time' => $request->startTime ? $request->startTime : null,
                        'duration' => $request->duration ? $request->duration : null,
                        'runo_type' => $request->type ? $request->type : null,
                        'runo_status' => $request->status ? $request->status : null,
                        'tag' => $request->tag ? $request->tag : null,
                        'runo_created_at' => $request->createdAt ? $request->createdAt : null,
                        'runo_call_id' => $request->callId ? $request->callId : null,
                    ];

                    $task = Task::create($taskData);
                } elseif ($request->duration > 120 &&  $new == 'no') {
                    $taskData = [
                        'lead_id' =>  $leadId,
                        'create_task_id' => 19,
                        'schedule_date' => date('Y-m-d'),
                        'created_by' => $user->id,
                        'task_completed_status' => 1,
                        'followup_by' => $user->id,
                        'runo_start_time' => $request->startTime ? $request->startTime : null,
                        'duration' => $request->duration ? $request->duration : null,
                        'runo_type' => $request->type ? $request->type : null,
                        'runo_status' => $request->status ? $request->status : null,
                        'tag' => $request->tag ? $request->tag : null,
                        'runo_created_at' => $request->createdAt ? $request->createdAt : null,
                        'runo_call_id' => $request->callId ? $request->callId : null,
                    ];
                    $task = Task::create($taskData);
                } else {
                    $taskData = [
                        'lead_id' =>  $leadId,
                        'create_task_id' => 20, //runo interaction task id
                        'schedule_date' => date('Y-m-d'),
                        'created_by' => $user->id,
                        'task_completed_status' => 1,
                        'followup_by' => $user->id,
                        'runo_start_time' => $request->startTime ? $request->startTime : null,
                        'duration' => $request->duration ? $request->duration : null,
                        'runo_type' => $request->type ? $request->type : null,
                        'runo_status' => $request->status ? $request->status : null,
                        'tag' => $request->tag ? $request->tag : null,
                        'runo_created_at' => $request->createdAt ? $request->createdAt : null,
                        'runo_call_id' => $request->callId ? $request->callId : null,
                    ];

                    $task = Task::create($taskData);
                }
                $type = 'users';
            } else {
                $type = 'cr';
                $phoneNumber = $request->phoneNumber;

                $lead = Lead::whereRaw("SUBSTRING(mobile, -10) = ?", substr($phoneNumber, -10))->where('sale_status', 'yes')->first();
                if ($lead) {
                    $sale = SalesActivity::where('lead_id', $lead->id)->first();
                    
                    $sale_id = $sale->id;
                    $leadId = $sale->lead_id;
                }

            }

            $callLog = new CallLog();
            $callLog->lead_id = $leadId ?? null;
            $callLog->user_id = $user->id;
            $callLog->sale_id = $sale_id ?? null;
            $callLog->call_type =  $request->type ? $request->type : null;
            $callLog->call_status = $request->status ? $request->status : null;
            $callLog->call_tag = $request->tag ? $request->tag : null;
            $callLog->call_start_time = $request->startTime ? $request->startTime : null;
            $callLog->call_duration = $request->duration ? $request->duration : null;
            $callLog->call_created_at = $request->createdAt ? $request->createdAt : null;
            $callLog->call_id = $request->callId ? $request->callId : null;
            $callLog->type = $type;
            $callLog->phone = $phoneNumber;
            $callLog->save();

            $check = false;
            $mobile =  $request->phoneNumber;
            if (!$check) {
                $leadBankExists = LeadBank::where('mobile', $mobile)->exists();

                if (!$leadBankExists) {
                    $Lead_bank = new LeadBank();
                    $Lead_bank->lead_id = $lead->id;
                    $Lead_bank->enquirer_name = $request->name;
                    $Lead_bank->mobile = $request->phoneNumber;
                    $Lead_bank->source = 77;
                    $Lead_bank->lead_date = date('Y-m-d');
                    $Lead_bank->created_by = $user->id;
                    $Lead_bank->updated_by = $user->id;
                    $Lead_bank->attended_by = $user->id;

                    if (
                        $user->hasRole('super-admin') ||
                        $user->hasRole('admin')
                    ) {
                        $Lead_bank->attended_by = null;
                        if (!empty($attendedBy)) {
                            $Lead_bank->attended_by = $attendedBy;
                        }
                    } elseif (empty($user->reporting_to)) {
                        $Lead_bank->attended_by = null;
                    }
                    $Lead_bank->save();
                }
            }

            return $this->success(
                'Runo Lead Added Successfully',
            );
        }
        return $this->error(
            'Runo Lead not added',
        );
    }

    public function storeInteraction(Request $request)
    {
        $task = Task::where('runo_call_id', $request->callId)->first();

        if ($task) {
            $leadid = $task->lead_id;

            $lead = Lead::find($leadid);
            $lead_bank = LeadBank::find($leadid);



            if ($lead) {


                if ($lead->enquirer_name == 'Unknown' && isset($request->customer['name'])) {
                    $lead->enquirer_name = $request->customer['name'];
                    $lead_bank->enquirer_name = $request->customer['name'];

                }

                // if (isset($request->userFields[0]['value'])) {
                //     $source = Source::where('name', 'LIKE', $request->userFields[0]['value'])->first();

                //     if ($source) {
                //         $lead->source = $source->id;
                //     }
                // }
                if (isset($request->userFields[0]['value']) && $lead->source == 77) {
                    $source = Source::where('name', 'LIKE', $request->userFields[0]['value'])->first();
            
                    if ($source) {
                        $lead->source = $source->id;
                        $lead_bank->source = $source->id;
                    }
                }

                if (isset($request->userFields[2]['value'])) {
                    $project = PreferredProject::where('project_name', 'LIKE', $request->userFields[2]['value'])->first();

                    if ($project) {
                        $lead->preferred_project = $project->id;
                        $lead_bank->preferred_project = $project->id;
                        $lead->project_type = $project->project_type;
                        $lead_bank->project_type = $project->project_type;
                    }
                }

                $lead->save();
                $lead_bank->save();

                return $this->success('Runo Lead Updated Successfully');
            }
        }


        return $this->error('Task or Lead not found');
    }
}
