<?php

namespace App\Classes\Modules\Transactions\Processors;

use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Models\Document;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use Webklex\PDFMerger\Facades\PDFMergerFacade as PDFMerger;

class CreateInvoiceDocumentProcessor
{
    /** @var CreatesDocument */
    private $createsDocument;

    /** @var CreatesFiles */
    private $createsFile;

    /**
     * CreateInvoiceDocumentProcessor constructor.
     * @param CreatesDocument $createsDocument
     * @param CreatesFiles $createsFile
     */
    public function __construct(CreatesDocument $createsDocument, CreatesFiles $createsFile)
    {
        $this->createsDocument = $createsDocument;
        $this->createsFile = $createsFile;
    }

    /**
     * @param $transaction
     * @param $purchaseOrder
     * @param $supplier
     * @param $document_type
     * @return void
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute($transaction, $purchaseOrder, $supplier, $document_type, $voucherRedemption = null)
    {
        $lowercaseDocumentType = strtolower($document_type);

        $order_pdf = LaravelMpdf::loadView('pages.pdfs.' . $lowercaseDocumentType, ['transaction' => $transaction, 'po_order_transaction' => $purchaseOrder, 'supplier' => $supplier, 'voucher_redemption' => $voucherRedemption]);

        if($purchaseOrder->booking->service_id === 4) {
            $purchaseOrderDocuments = $purchaseOrder->booking->documents()->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->get();


            $oMerger = PDFMerger::init();
            $order_pdf->save(storage_path('app/documents/temp.pdf'));

            $oMerger->addPDF(storage_path('app/documents/temp.pdf'), 'all');
            foreach ($purchaseOrderDocuments as $document){
                $oMerger->addPDF(storage_path('app/documents/'.$document->files()->first()->file->file_info->original->file), 'all');
            }

            $oMerger->merge();

            $order_pdf = $oMerger;
        }

        $document_object = new DocumentObject(
            $document_type,
            [chunk_split('data:application/pdf;base64,' . base64_encode($order_pdf->output()))],
            '',
            ApprovalStatus::COMPLETED,
            $lowercaseDocumentType . 's'
        );

        /** @var Document $document */
        $document = $this->createsDocument->execute($purchaseOrder->booking, $document_object);
        $this->createsFile->execute($document, $document_object);

    }
}
