<?php

namespace App\Classes\Modules\PerfexCRM\Services;

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

class CreatesPerfexCRMMilestone
{
    /**
     * @param string $$milestoneName
     * @param string $projectId
     * @param string $milestoneOrder
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(string $milestoneName, string $projectId, string $milestoneOrder =  "") {
        try{
            $data = [
                'name' => $milestoneName,
                'project_id' => $projectId,
                'due_date' => date('Y-m-d'),
                'start_date' => date('Y-m-d')
            ];

            if($milestoneOrder != ""){
                $data['milestone_order'] = $milestoneOrder;
            }

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