<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Models\Document;

class RegenerateShippingInvoiceTransactionLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Regenerate Shipping Invoice',
            'message' => 'You have successfully regenerated shipping invoice'
        ];
    }

    /** @var CreatesDocument */
    private $createsDocument;

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

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

    public function logic(Request $request) : JsonResponse
    {

        $orders = Order::where('company_module_id', $request->route('company_module_id'))->get();

        foreach ($orders as $order){
            $invoices = $order->transactions()->where('transactions.type', TransactionType::SHIPPING_INVOICE)->get();
            foreach ($invoices as $invoice){
    
                $invoice->documents()->delete();
    
                $transaction_invoice_pdf = LaravelMpdf::loadView('pages.pdfs.shipping_invoice', ['invoice_transaction' => $invoice]);
    
                $document_object = new DocumentObject(
                    DocumentType::SHIPPING_INVOICE,
                    [chunk_split('data:application/pdf;base64,'.base64_encode($transaction_invoice_pdf->output()))],
                    '',
                    ApprovalStatus::COMPLETED,
                    'shipping_invoice'
                );
    
                $document =$this->createsDocument->execute($invoice, $document_object);
    
                $this->createsFiles->execute($document, $document_object);
    
                // dump($document);
            }
        }

        return $this->response([]);
    }

}
