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

class UpdatesPerfexCRMInvoice
{

    /**
     * @param $invoice
     * @param string $projectId
     * @return null|object
     * @throws MalformedRequestException
     */
    public function execute($invoice, string $projectId) {
        try{
            // <p>The Invoice number field is required.<\/p>
            // <p>The Invoice date field is required.<\/p>
            // <p>The Currency field is required.<\/p>
            // <p>The Items field is required.<\/p>
            // <p>The Allow Payment Mode field is required.<\/p>
            // <p>The Billing Street field is required.<\/p>
            // <p>The Sub Total field is required.<\/p>
            // <p>The Total field is required.<\/p>

            $newInvoiceItems = [];
            foreach ($invoice->items as $item) {
                $item['itemid'] = $item['id'];
                unset($item['id']);
                $item['order'] = $item['item_order'];
                unset($item['item_order']);
                array_push($newInvoiceItems,$item);
            }

            $allowedPaymentModes = [];
            array_push($allowedPaymentModes, 1, 2);

            $data = [
                'number' => $invoice->number,
                'date' => $invoice->date,
                'duedate' => $invoice->duedate,
                'currency' => $invoice->currency,
                'subtotal' => $invoice->subtotal,
                'total' => $invoice->total,
                'billing_street' => $invoice->billing_street,
                'shipping_street' => $invoice->billing_street,
                'project_id' => $projectId,
                'items' => $newInvoiceItems,
                'allowed_payment_modes' => $allowedPaymentModes,
            ];

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