<?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;

class UpdatesPerfexCRMTask
{

    /**
     * @param string $taskName
     * @param string $milestoneId
     * @param string $projectId
     * @param string $status, default: 1
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(string $taskId, string $taskName, string $milestoneId, string $projectId, string $status = "1") {
        try{
            $data = [
                'name' => $taskName,
                'milestone' => $milestoneId,
                'startdate' => date('Y-m-d'),
                'duedate' => date('Y-m-d'),
                'rel_type' => 'project',
                'rel_id' => $projectId,
                'status' => $status,
                'repeat_every' => '',
            ];

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

            if($response->successful()){
                $data = $response->json();
                return (object) $data;
            }else{
                Log::error('UpdatesPerfexCRMTask: '.$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());
        }
    }
}
