<?php

namespace App\Classes\Modules\PerfexCRM\Processors;


use App\Classes\Modules\PerfexCRM\Processors\CreatePerfexCRMInvoiceProcessor;
use App\Classes\Modules\PerfexCRM\Services\FetchesPerfexCRMCustomer;
use App\Classes\Modules\PerfexCRM\Services\FetchesPerfexCRMInvoice;
use App\Classes\Modules\PerfexCRM\DataTransferObjects\FetchPerfexCRMInvoiceObject;
use Illuminate\Support\Facades\Log;
use App\Classes\General\Helper;

class FetchPerfexCRMInvoiceProcessor
{
    private $fetchesPerfexCRMCustomer;
    /** @var FetchesPerfexCRMCustomer */

    /** @var FetchesPerfexCRMInvoice */
    private $fetchesPerfexCRMInvoice;

    /** @var CreatePerfexCRMInvoiceProcessor */
    private $createPerfexCRMInvoiceProcessor;

    /**
     *
     * FetchPerfexCRMInvoiceProcessor constructor.
    * @param FetchesPerfexCRMCustomer $fetchesPerfexCRMCustomer
    * @param FetchesPerfexCRMInvoice $fetchesPerfexCRMInvoice
    * @param CreatePerfexCRMInvoiceProcessor $createPerfexCRMInvoiceProcessor
    */
    public function __construct(FetchesPerfexCRMCustomer $fetchesPerfexCRMCustomer,
        FetchesPerfexCRMInvoice $fetchesPerfexCRMInvoice,
        CreatePerfexCRMInvoiceProcessor $createPerfexCRMInvoiceProcessor)
    {
        $this->fetchesPerfexCRMCustomer = $fetchesPerfexCRMCustomer;
        $this->fetchesPerfexCRMInvoice = $fetchesPerfexCRMInvoice;
        $this->createPerfexCRMInvoiceProcessor = $createPerfexCRMInvoiceProcessor;
    }

    public function execute(FetchPerfexCRMInvoiceObject $fetchPerfexCRMInvoiceObject)
    {
        //invoiceId to be returned - fetch or create
        $invoiceId = 0;

        //get the client id
        $customer = $this->fetchesPerfexCRMCustomer->execute($fetchPerfexCRMInvoiceObject->getEmail());
        $transaction = $fetchPerfexCRMInvoiceObject->getTransaction();

        $number = $transaction->owner->bill_no;

        $prefix = "INV-";
        //This will remove the prefix if prefix already exist in the string
        if (substr($number, 0, strlen($prefix)) == $prefix) {
            $number = substr($number, strlen($prefix));
        }

        $invoice = $this->fetchesPerfexCRMInvoice->execute($customer->userid,"INV-", $number);
        if(is_null($invoice)){
            $result = $this->createPerfexCRMInvoiceProcessor->execute($transaction->owner);
            if ($result) {
                $invoiceId = $result->payload['id'];
            } else {
                $log['message'] = 'FetchPerfexCRMInvoiceProcessor failed for transaction > bill_no: '.$number;
                Helper::debugLogger($log);
            }
        }
        else{
            $invoiceId = $invoice->id;
        }

        return $invoiceId;
    }
}
