<?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;
use App\Classes\ValueObjects\Constants\PerfexCRMCustomFields;
use App\Classes\Modules\PerfexCRM\DataTransferObjects\CreateTaskPerfexCRMObject;

class CreatesPerfexCRMTask
{
    /**
     * @param CreateTaskPerfexCRMObject $createTaskPerfexCRMObject
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(CreateTaskPerfexCRMObject $createTaskPerfexCRMObject) {
        try{
            $custom_fields = [];
            if($createTaskPerfexCRMObject->getDepartment() != ""){
                $custom_fields = [
                    "tasks" => [
                        PerfexCRMCustomFields::TASKS_DEPARTMENT => $createTaskPerfexCRMObject->getDepartment()
                    ]
                ];
            }

            $data = [
                'name' => $createTaskPerfexCRMObject->getName(),
                'description' => $createTaskPerfexCRMObject->getDescription(),
                'milestone' => $createTaskPerfexCRMObject->getMilestoneId(),
                'startdate' => date('Y-m-d'),
                'rel_type' => 'project',
                'rel_id' => $createTaskPerfexCRMObject->getProjectId(),
                'status' => $createTaskPerfexCRMObject->getStatus(),
                'is_system_created' => 1,
                'reference' => $createTaskPerfexCRMObject->getReference(),
                'on_task_completion' => $createTaskPerfexCRMObject->getOnTaskCompletion(),
                'custom_fields' => $custom_fields,
                'priority' => $createTaskPerfexCRMObject->getPriority(),
                'duedate' => date('Y-m-d', strtotime('+' . $createTaskPerfexCRMObject->getDuedate() . ' days')),
                'invoice_id' => $createTaskPerfexCRMObject->getInvoiceId(),
            ];

            if($createTaskPerfexCRMObject->getLeadId() != '') {
                $data['rel_type'] = 'lead';
                $data['rel_id'] = $createTaskPerfexCRMObject->getLeadId();
            }

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