<?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\General\Helper;

class FetchesPerfexCRMTask
{
    /**
     * @param string $taskName
     * @param string $milestoneId
     * @param string $relType
     * @param string $relId
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(string $taskName, string $milestoneId, string $relType, string $relId, string $invoiceId) {
        try{
            $data = [
                'name' => $taskName,
                'rel_type' => $relType,
                'rel_id' => $relId,
            ];

            if($milestoneId != '') {
                $newItem = ['milestone' =>  $milestoneId ];
                $data = array_merge($data, $newItem);
            }

            if($invoiceId != 0) {
                $newItem = ['invoice_id' =>  $invoiceId ];
                $data = array_merge($data, $newItem);
            }

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