<?php

namespace App\Classes\Modules\PerfexCRM\Services;

use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\MalformedRequestException;
use Illuminate\Support\Facades\Log;
use App\Classes\Modules\PerfexCRM\DataTransferObjects\InvoicePerfexCRMObject;

class CreatesPerfexCRMInvoice
{
    /**
     * @param InvoicePerfexCRMObject $invoicePerfexCRMObject
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute(InvoicePerfexCRMObject $invoicePerfexCRMObject) {
        try{
            $subtotal = floor($invoicePerfexCRMObject->getSubTotal() * 100) / 100;
            $total = floor($invoicePerfexCRMObject->getTotal() * 100) / 100;

            $data = [
                'clientid' => $invoicePerfexCRMObject->getClientId(),
                'number' => $invoicePerfexCRMObject->getNumber(),
                'date' => $invoicePerfexCRMObject->getDate(),
                'duedate' => $invoicePerfexCRMObject->getDueDate(),
                'currency' => $invoicePerfexCRMObject->getCurrency(),
                'subtotal' => number_format($subtotal, 2, '.', ''),
                'total' => number_format($total, 2, '.', ''),
                'billing_street' => $invoicePerfexCRMObject->getBillingStreet(),
                'project_id' => $invoicePerfexCRMObject->getProjectId(),
                'allowed_payment_modes[0]' => 1,
                'allowed_payment_modes[1]' => 2,
            ];

            for($count=0; $count < count($invoicePerfexCRMObject->getInvoiceItems()); $count++) {
                $oneItem = [
                    "newitems[".$count."][description]" => $invoicePerfexCRMObject->getInvoiceItems()[$count]->description,
                    "newitems[".$count."][long_description]" => $invoicePerfexCRMObject->getInvoiceItems()[$count]->longDescription,
                    "newitems[".$count."][qty]" => $invoicePerfexCRMObject->getInvoiceItems()[$count]->qty,
                    "newitems[".$count."][rate]" => $invoicePerfexCRMObject->getInvoiceItems()[$count]->rate,
                    "newitems[".$count."][order]" => $invoicePerfexCRMObject->getInvoiceItems()[$count]->order,
                    "newitems[".$count."][unit]" => $invoicePerfexCRMObject->getInvoiceItems()[$count]->unit,
                ];
                $data = array_merge($data, $oneItem);
            }

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