<?php

namespace App\Http\Controllers\Admin\Api;

use App\Events\UserLogEvent;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use App\Models\Lead;
use App\libs\Response\GlobalApiResponse;
use App\libs\Response\GlobalApiResponseCodeBook;
use App\Services\Admin\LeadService;
use Carbon\Carbon;
use Illuminate\Http\Request;

class LeadsController extends Controller
{
    private $leadService;

    public function __construct(LeadService $leadService)
    {
        $this->leadService = $leadService;
    }

    public function leadsList(Request $request)
    {
        $data = $this->leadService->leadsList($request);
        return (new GlobalApiResponse())->success('Leads list', 1, $data);
    }

    public function leadListingsList(Request $request)
    {
        $data = $this->leadService->leadListingsList($request);
        return (new GlobalApiResponse())->success('Lead Listings list', 1, $data);
    }

    public function getLeadDetail($id)
    {
        $data = $this->leadService->getLeadDetail($id);
        return (new GlobalApiResponse())->success('Leads Details', 1, $data);
    }

    public function createLead(Request $request)
    {
        $this->leadService->createLead($request->all());
        if ($this->leadService->hasError()) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, $this->leadService->getErrors()[0]['message'], $this->leadService->getErrors());
        }
        return (new GlobalApiResponse())->success('Successfully created');
    }

    public function updateLead(Request $request, $id)
    {
        $this->leadService->updateLead($request->all(), $id);
        if ($this->leadService->hasError()) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, $this->leadService->getErrors()[0]['message'], $this->leadService->getErrors());
        }
        return (new GlobalApiResponse())->success('Successfully updated');
    }

    public function deleteLead(Request $request)
    {
        if (empty($request->lead_ids)) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, "IDs not found!");
        }
        auth()->user()->leads()->whereIn('id', $request->lead_ids)->delete();
        return (new GlobalApiResponse())->success("Successfully deleted");
    }

    public function updateLeadStatus(Request $request)
    {
        if (empty($request->lead_ids)) {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::INVALID_FORM_INPUTS, "IDs not found!");
        }
        $mods = auth()->user()->leads()->whereIn('id', $request->lead_ids)->get();
        if (!empty($mods)) {
            foreach ($mods as $mod) {
                if ($request->type == 'Contacts') {
                    $mod->update(['converted_to' => $request->type]);
                    $contact = new Contact();
                    $contact->name = $mod->name;
                    $contact->email = $mod->email;
                    $contact->phone = $mod->phone;
                    $contact->assign_to = $mod->assign_to;
                    $contact->type = 1;
                    $contact->added_by = auth()->id();
                    $contact->reference_number = generateReferenceNumber(auth()->id(), 'contacts');
                    $contact->save();
                    event(new UserLogEvent($mod->id, 'leads', 'Lead Moved To Contacts'));
                } else {
                    $mod->update([$request->column => $request->status]);
                    event(new UserLogEvent($mod->id, 'leads', 'Lead ' . $request->type . ' Updated'));
                }
            }
            return (new GlobalApiResponse())->success("Successfully updated");
        } else {
            return (new GlobalApiResponse())->error(GlobalApiResponseCodeBook::RECORD_NOT_EXIST, "Lead not found!");
        }
    }

    public function leadsBulkAction()
    {
        $ids = request()->input('bulkIds');
        if ($ids) {
            $ids = explode(',', $ids);
            $assign_id = request()->input('bulk_assign_to');
            $status_id = request()->input('bulk_status');
            $ps_id = request()->input('bulk_ps');
            $ss_id = request()->input('bulk_ss');
            if ($assign_id) {
                auth()->user()->leads()->whereIn('id', $ids)->each(function ($item) use ($assign_id) {
                    $item->update(['assign_to' => $assign_id]);
                });
            }
            if ($ps_id) {
                auth()->user()->leads()->whereIn('id', $ids)->each(function ($item) use ($ps_id) {
                    $item->update(['lead_primary_source_id' => $ps_id]);
                });
            }
            if ($ss_id) {
                auth()->user()->leads()->whereIn('id', $ids)->each(function ($item) use ($ss_id) {
                    $item->update(['lead_secondary_source_id' => $ss_id]);
                });
            }
            if ($status_id) {
                auth()->user()->leads()->whereIn('id', $ids)->each(function ($item) use ($status_id) {
                    $item->update(['lead_status_id' => $status_id]);
                });
            }
        }
        return redirect(url()->previous())->with('bsuccess', "Updated successfully.");
    }

    public function saveLeadNote()
    {
        $lead_id = request()->input('lead_id');
        $note = request()->input('note');
        if (!empty($lead_id) && !empty($note)) {
            $lead = auth()->user()->leads()->find($lead_id);
            if ($lead) {
                $lead->notes()->create(['note' => $note]);
            }
        }
        event(new UserLogEvent($lead_id, 'leads', 'Lead Note Added'));
        return redirect(url()->previous())->with('nsuccess', "Updated successfully.");
    }
}
