<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\Modules\Transactions\Processors\CreateSupplierTransactionProcessor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\General\AWSS3Helper;
use Illuminate\Support\Facades\Storage;

class DownloadMockUpWhiteFormPdfLogic
{

    /** @var FetchesCompany */
    private $fetchesCompany;

    /** @var CreateSupplierTransactionProcessor */
    private $createSupplierTransactionProcessor;

    /**
     * DownloadMockUpWhiteFormPdfLogic constructor.
     * @param FetchesCompany $fetchesCompany
     * @param CreateSupplierTransactionProcessor $createSupplierTransactionProcessor
     */
    public function __construct(FetchesCompany $fetchesCompany, CreateSupplierTransactionProcessor $createSupplierTransactionProcessor)
    {
        $this->fetchesCompany = $fetchesCompany;
        $this->createSupplierTransactionProcessor = $createSupplierTransactionProcessor;
    }


    /**
     * @param Request $request
     * @return string|\Symfony\Component\HttpFoundation\Response
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(Request $request)
    {

        $supplier = $this->fetchesCompany->execute(['id' => $request->route('id')]);

        $rate =  $request->input('rate');

        $payments = array_map(function($value){
            return ['id' => $value];
        }, json_decode($request->input('payments')));

        DB::beginTransaction();

        $this->createSupplierTransactionProcessor->execute($supplier, $rate, $payments);

        if(!count($this->createSupplierTransactionProcessor->getBills())) return 'unexpected error';

        $pdf = LaravelMpdf::loadView('pages.pdfs.currency_vendor_order', ['transactions' => $this->createSupplierTransactionProcessor->getBills(), 'transferFeeTransactions' => $this->createSupplierTransactionProcessor->getTransferTransactions(), 'supplier' => $supplier]);

        DB::rollBack();

        $exportFileName = 'MockUpWhiteForm.pdf';
        $filesystemDriver = Storage::getDefaultDriver();
        if($filesystemDriver === 's3'){
            $pdfContent = $pdf->output();
            return response([ 'src' =>  AWSS3Helper::S3PDF($exportFileName, $pdfContent) ]);
        }
        else{
            return $pdf->stream($exportFileName);
        }
    }
}
