<?php

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

use App\Api\Http\Requests\ProjectAllocation\ProjectAllocationRequest;
use App\Customer;
use App\CustomerEnquiry;
use App\Http\Controllers\Controller;
use App\Lead;
use App\PreferredProject;
use App\Source;
use App\Task;
use App\User;
use Carbon\Carbon;

class CustomerEnquiryController extends Controller
{
    public function index()
    {
        $enquiries = [];
        $customerEnquiries = CustomerEnquiry::select('id', 'project_id', 'customer_id', 'lead_id', 'type', 'status', 'created_at')
            ->groupBy('project_id', 'customer_id')
            ->where('type', 'project')
            ->get();
        foreach ($customerEnquiries as $key => $customerEnquiry) {
            $preferredProject = PreferredProject::find($customerEnquiry->project_id);
            $customer = Customer::find($customerEnquiry->customer_id);
            $enquiries[] = [
                'id' => $customerEnquiry->id,
                'project_name' => $preferredProject ? $preferredProject->project_name : null,
                'customer_name' => $customer ? $customer->getFullNameAttribute() : null,
                'phone_no' => $customer ? $customer->mobile : null,
                'status' => $customerEnquiry->status,
                'created_at' => Carbon::parse($customerEnquiry->created_at)->format('Y-m-d H:i:s'),
                'allocated_person' => $customerEnquiry->getLead->enquirer_name ?? null,
                'allocated_date' => $customerEnquiry->getLead ? Carbon::parse($customerEnquiry->getLead->created_at)->format('Y-m-d') : null,
                'allocated_time' => $customerEnquiry->getLead ? Carbon::parse($customerEnquiry->getLead->created_at)->format('H:i:s') : null,
            ];
        }

        return $this->success(
            'Customer Enquiry Projects!',
            $enquiries
        );
    }

    public function getInteriors()
    {
        $enquiries = [];
        $customerEnquiries = CustomerEnquiry::select('id', 'project_id', 'customer_id', 'lead_id', 'type', 'status', 'created_at')
            ->groupBy('project_id', 'customer_id')
            ->where('type', 'interior')
            ->get();
        foreach ($customerEnquiries as $key => $customerEnquiry) {
            $preferredProject = PreferredProject::find($customerEnquiry->project_id);
            $customer = Customer::find($customerEnquiry->customer_id);
            $enquiries[] = [
                'id' => $customerEnquiry->id,
                'project_name' => $preferredProject ? $preferredProject->project_name : null,
                'customer_name' => $customer ? $customer->getFullNameAttribute() : null,
                'phone_no' => $customer ? $customer->mobile : null,
                'location' => $customer ? $customer->location : null,
                'status' => $customerEnquiry->status,
                'created_at' => Carbon::parse($customerEnquiry->created_at)->format('Y-m-d H:i:s'),
                'allocated_person' => $customerEnquiry->getLead->enquirer_name ?? null,
                'allocated_date' => $customerEnquiry->getLead ? Carbon::parse($customerEnquiry->getLead->created_at)->format('Y-m-d') : null,
                'allocated_time' => $customerEnquiry->getLead ? Carbon::parse($customerEnquiry->getLead->created_at)->format('H:i:s') : null,
            ];
        }

        return $this->success(
            'Customer Enquiry Interiors!',
            $enquiries
        );
    }

    public function getProjectAllocateUsers()
    {
        $users = User::where('status', 1)->whereHas('roles', function ($q) {
            $q->whereIn('id', [3, 7, 8]);
        })->get();

        return $this->success(
            'Project Allocate Users!',
            $users
        );
    }

    public function projectAllocation(ProjectAllocationRequest $request)
    {
        try {
            $projectId = $request->project_id;
            $salePersonId = $request->allocate_to; //saleperson_id
            $customerEnquiryId = $request->customer_enquiry_id;

            $salePerson = User::find($salePersonId);

            $source = Source::where('name', 'My HiLITE')->first();
            if ($source == null) {
                $source = new Source();
                $source->name = 'My HiLITE';
                $source->save();
            }

            $lead = new Lead();
            $lead->enquirer_name = $salePerson->name;
            $lead->mobile = $salePerson->mobile;
            $lead->phone_code = $salePerson->phone_code;
            $lead->source = $source->id;
            $lead->lead_date = date('Y-m-d');
            $lead->attended_by = $salePersonId;
            $lead->created_by = $salePersonId;
            $lead->updated_by = $salePersonId;
            $lead->is_attended = 1;
            $lead->customer_enquiry_id = $customerEnquiryId;

            $check = false;
            $check_mobile_task = false;
            $fifteenDays = now()->subDays(15);
            $threeMonthBefore = now()->subMonths(3);

            $mobile =  $salePerson->mobile;

            if (!empty($mobile)) {

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

                if (!$check) {
                    $mbb =  $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();

            if (!empty($lead->id)) {
                $leadId = $lead->id;
                $uId = 'HiLEAD/' . date('Y') . '/' . $leadId;
                $lead->unique_id = $uId;
                $lead->save();

                $customerEnquiry = CustomerEnquiry::find($customerEnquiryId);
                $customerEnquiry->lead_id = $leadId;
                $customerEnquiry->status = 'Attended'; // default value Pending
                if ($customerEnquiry->save()) {
                    return $this->success(
                        'Project Allocation Added Successfully',
                    );
                }
            }
        } catch (\Throwable $th) {
            return $this->error(
                'Something went wrong!'
            );
        }
    }
}
