<?php

namespace App\Classes\Modules\PerfexCRM\Services;

use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Exceptions\ConnectionErrorException;
use App\Classes\General\LogHelper;
use Illuminate\Support\Facades\Log;

class UpdatesPerfexCRMProject
{
    /**
     * @param $project
     * @param int $status
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute($project, int $status) {
        try{
            $data = [
                'name' => $project['name'],
                'clientid' => $project['clientid'],
                // 'rel_type' => 'customer',
                'billing_type' => 1,
                'start_date' => $project['start_date'],
                'status' => $status
            ];

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

            if($response->successful()){
                $data = $response->json();
                return (object) $data;
            }else{
                LogHelper::channel('perfex_crm')->info($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());
        }
    }
}
