<?php

namespace App\Classes\Modules\PerfexCRM\Services;

use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\MalformedRequestException;
use Illuminate\Support\Facades\Log;
use App\Classes\ValueObjects\Constants\PerfexCRMCustomFields;

class UpdatesPerfexCRMLead
{
    /**
     * @param $lead
     * @param string $companyReference
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute($lead, string $companyReference) {
        try{
            $custom_fields = [
                "leads" => [
                    PerfexCRMCustomFields::LEADS_EXCHANGE_REFERENCE => $companyReference
                ]
            ];

            $data = [
                'name' => $lead->name,
                'email' => $lead->email,
                'phonenumber' => $lead->phonenumber,
                'company' => $lead->company,
                'custom_fields' => $custom_fields,
                'source' => $lead->source,
                'status' => $lead->status,
            ];

            $response = Http::asJson()->withHeaders([
                'authtoken' => config('perfexcrm.api_key')])
            ->put(config('perfexcrm.base_url').'/api/leads/'.$lead->id, $data);

            if($response->successful()){
                $data = $response->json();
                return (object) $data;
            }else{
                Log::channel('perfex_crm')->info($response);
                return null;
            }
        }catch(\Exception $exception){
            throw new MalformedRequestException('Unable to get correct response from Perfex CRM server: ' . $exception->getMessage());
        }
    }
}
