<?php

namespace App\Console\Commands;

use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\Modules\PackingLists\Services\ListsPackingLists;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\CompanyConnection;
use App\Models\Order;
use Carbon\Carbon;
use Exception;
use Illuminate\Console\Command;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;

class FixInvoice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoice:fix {--marking=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix Invoice By Company Module Marking';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $connection = CompanyConnection::where('invitee_reference', $this->option('marking'))->first();
        $company_module_id = $connection->invitee->id;

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

        foreach ($orders as $order){
            $invoices = $order->transactions()->where('transactions.type', TransactionType::SHIPPING_INVOICE)->get();
            foreach ($invoices as $invoice){
    
                dump($invoice->id);
                
                $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'
                );
    
                /** @var Document $document */
                $document = (App()->make(CreatesDocument::class))->execute($invoice, $document_object);
    
                (App()->make(CreatesFiles::class))->execute($document, $document_object);
            }
        }
    }
}
