<?php

namespace App\Classes\Modules\PerfexCRM\Services;

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

class UpdatesPerfexCRMCustomer
{

    /**
     * @param string $customerId
     * @param string $companyReference
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(string $customerId, string $companyName, string $companyReference) {
        try{
            $custom_fields = [
                "customers" => [
                    PerfexCRMCustomFields::CUSTOMERS_SHIPPING_PORTAL_REFERENCE => $companyReference
                ]
            ];

            $data = [
                'company' => $companyName,
                'custom_fields' => $custom_fields
            ];

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

            if($response->successful()){
                $data = $response->json();
                return (object) $data;
            }else{
                // Helper::debugLogger($response);
                return null;
            }
        }
        catch(\Illuminate\Http\Client\ConnectionException $exception){
            $error = 'Failed to connect to CRM';
            throw new ConnectionErrorException($error, $exception->getMessage(), "", $exception->getTraceAsString());
        }
        catch(\Exception $exception){
            throw new MalformedRequestException('Unable to get correct response from Perfex CRM server: ' . $exception->getMessage());
        }
    }
}
