<?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\Modules\PerfexCRM\DataTransferObjects\CreateLeadPerfexCRMObject;

class CreatesPerfexCRMLead
{
    /**
     * @param CreateLeadPerfexCRMObject $createLeadPerfexCRMObject
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(CreateLeadPerfexCRMObject $createLeadPerfexCRMObject) {
        try{
            $custom_fields = [
                "leads" => [
                    3 => $createLeadPerfexCRMObject->getCompanyReference()
                ]
            ];

            $data = [
                'name' => $createLeadPerfexCRMObject->getName(),
                'email' => $createLeadPerfexCRMObject->getEmail(),
                'phonenumber' => $createLeadPerfexCRMObject->getPhone(),
                'company' => $createLeadPerfexCRMObject->getCompanyName(),
                'source' => 1, //1: Exchange, 2: Shipping Portal
                'status' => 2, //2: Lead, 1: Customer,
                'custom_fields' => $custom_fields
            ];

            $response = Http::asForm()->withHeaders([
                'authtoken' => config('perfexcrm.api_key')])
            ->post(config('perfexcrm.base_url').'/api/leads/byemail',$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());
        }
    }
}
