<?php

namespace App\Classes\Modules\PerfexCRM\Services;

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

class UpdatesPerfexCRMTask
{

    /**
     * @param string $taskName
     * @param string $milestoneId
     * @param string $projectId
     * @param string $status, default: 1
     * @param string $startDate
     * @param string $dueDate
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(string $taskId, string $taskName, string $milestoneId, string $projectId, string $status, string $startDate, string $dueDate) {
        try{
            $data = [
                'name' => $taskName,
                'milestone' => $milestoneId,
                'startdate' => $startDate,
                'duedate' => $dueDate,
                '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::channel('perfex_crm')->info($response);
                return null;
            }
        }catch(\Exception $exception){
            throw new MalformedRequestException('Unable to get correct response from Perfex CRM server' . $exception->getMessage());
        }
    }
}
