<?php

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

use App\Api\Http\Requests\ReferalAllocation\ReferalAllocationRequest;
use App\CustomerReferral;
use App\Http\Controllers\Controller;
use App\Lead;
use App\PreferredProject;
use App\Source;
use App\Task;
use App\User;
use Carbon\Carbon;

class CustomerReferalController extends Controller
{
    public function index()
    {
        $referrals = [];
        $customerReferrals = CustomerReferral::select('id', 'project_id', 'customer_id', 'lead_id', 'name', 'email', 'phone', 'remarks', 'status', 'created_at')
            ->groupBy('project_id', 'customer_id')
            ->get();
        foreach ($customerReferrals as $key => $customerReferral) {
            $preferredProject = PreferredProject::find($customerReferral->project_id);
            $projectType = $preferredProject ? $preferredProject->getProjectType : null;
            $referrals[] = [
                'customer_referral_id' => $customerReferral->id,
                'project_name' => $preferredProject ? $preferredProject->project_name : null,
                'project_type' => $projectType ? $projectType->name : null,
                'name' => $customerReferral->name,
                'email' => $customerReferral->email,
                'phone_no' => $customerReferral->phone,
                'remarks' => $customerReferral->remarks,
                'status' => $customerReferral->status,
                'date' => Carbon::parse($customerReferral->created_at)->format('Y-m-d H:i:s'),
                'allocated_person' => $customerReferral->getLead->enquirer_name ?? null,
                'allocated_date' => $customerReferral->getLead ? Carbon::parse($customerReferral->getLead->created_at)->format('Y-m-d') : null,
                'allocated_time' => $customerReferral->getLead ? Carbon::parse($customerReferral->getLead->created_at)->format('H:i:s') : null,
            ];
        }

        return $this->success(
            'Customer Referrals!',
            $referrals
        );
    }

    public function referalAllocation(ReferalAllocationRequest $request)
    {
        try {
            $referralId = $request->referal_id;
            $salePersonId = $request->allocate_to; //saleperson_id
            $customerReferralId = $request->customer_referral_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_referral_id = $customerReferralId;

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

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