<?php

namespace App\Classes\Jobs;

use App\Classes\Modules\PerfexCRM\Processors\CreatePerfexCRMLeadProcessor;
use App\Classes\Modules\PerfexCRM\Services\FetchesPerfexCRMLead;
use App\Classes\Modules\PerfexCRM\Services\UpdatesPerfexCRMLead;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Classes\Modules\PerfexCRM\DataTransferObjects\CreateLeadPerfexCRMObject;

class CreatePerfexCRMCustomer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** @var CreateLeadPerfexCRMObject */
    private $createLeadPerfexCRMObject;

    /**
     * CreatePerfexCRMCustomer constructor.
     * @param CreateLeadPerfexCRMObject $createLeadPerfexCRMObject
     */
    public function __construct(CreateLeadPerfexCRMObject $createLeadPerfexCRMObject)
    {
        $this->createLeadPerfexCRMObject = $createLeadPerfexCRMObject;
    }

    public function handle()
    {
        $lead = (App()->make(FetchesPerfexCRMLead::class))->execute($this->createLeadPerfexCRMObject->getEmail());
        if(!is_null($lead)){
            (App()->make(UpdatesPerfexCRMLead::class))->execute($lead, $this->createLeadPerfexCRMObject->getCompanyReference());
        }
        else{
            (App()->make(CreatePerfexCRMLeadProcessor::class))->execute($this->createLeadPerfexCRMObject);
        }
    }
}
