<?php

namespace App\Classes\Jobs;

use App\Classes\Modules\PerfexCRM\Processors\UpdatePerfexCRMProcessor;
use App\Classes\Modules\PerfexCRM\Processors\FetchPerfexCRMInvoiceProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Classes\Modules\PerfexCRM\DataTransferObjects\UpdatePerfexCRMObject;
use App\Classes\Modules\PerfexCRM\DataTransferObjects\UpdatePerfexCRMInvoiceObject;
use App\Classes\Modules\PerfexCRM\DataTransferObjects\FetchPerfexCRMInvoiceObject;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean;
use App\Classes\ValueObjects\Constants\TransactionType;

class UpdatePerfexCRM implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** @var UpdatePerfexCRMObject */
    private $updatePerfexCRMObject;

    /** @var  */
    private $transaction;

    /** @var Boolean|null */
    private $shouldCreateInvoice;

    /**
     * @param UpdatePerfexCRMObject $updatePerfexCRMObject
     * @param $transaction
     * @param bool|null $shouldCreateInvoice
     */
    public function __construct(UpdatePerfexCRMObject $updatePerfexCRMObject, $transaction, ?bool $shouldCreateInvoice = false)
    {
        $this->updatePerfexCRMObject = $updatePerfexCRMObject;
        $this->transaction = $transaction;
        $this->shouldCreateInvoice = $shouldCreateInvoice;
    }


    public function handle()
    {
        //To use invoice as a reference to decide whether more tasks should be created
        $this->updatePerfexCRMObject->setInvoiceId($this->getInvoiceIdOrCreateInvoice());

        $result = (App()->make(UpdatePerfexCRMProcessor::class))->execute($this->updatePerfexCRMObject);
        if($this->transaction != null && $this->shouldCreateInvoice){
            $updatePerfexCRMInvoiceObject = new UpdatePerfexCRMInvoiceObject(
                $this->updatePerfexCRMObject->getContactEmail(),
                $this->updatePerfexCRMObject->getProjectName(),
                $result->projectId,
                $this->transaction,
                true
            );
            UpdatePerfexCRMInvoice::dispatch($updatePerfexCRMInvoiceObject);
        }
    }

    private function getInvoiceIdOrCreateInvoice(){
        if($this->transaction != null){
            $fetchPerfexCRMInvoiceObject = new FetchPerfexCRMInvoiceObject(
                $this->updatePerfexCRMObject->getContactEmail(),
                $this->transaction
            );
            $invoiceId = (App()->make(FetchPerfexCRMInvoiceProcessor::class))->execute($fetchPerfexCRMInvoiceObject);
            return $invoiceId;
        }
        return 0;
    }
}
