<?php

namespace App\Domains\Invoice\Controllers;

use App\Enumerations\CostUnitType;
use App\Resources\InvoiceResource;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class ShowInvoiceController extends CommonController {
    public function __invoke(int $invoiceId) : JsonResponse{
        $invoice = $this->invoices->getAsTreasurer($invoiceId);

        $runningJobs = $this->costUnits->getCostUnitsForNewInvoice(CostUnitType::COST_UNIT_TYPE_RUNNING_JOB);
        $currentEvents = $this->costUnits->getCostUnitsForNewInvoice(CostUnitType::COST_UNIT_TYPE_EVENT);

        return response()->json([
            'invoice' => new InvoiceResource($invoice)->toArray(),
            'costUnits' => array_merge($runningJobs, $currentEvents),
        ]);
    }

    public function showReceipt(int $invoiceId): BinaryFileResponse
    {
        $invoice = $this->invoices->getAsTreasurer($invoiceId);
        if (null === $invoice) {
            abort(404, 'Datei nicht gefunden');
        }

        if (null === $invoice->document_filename) {
            abort(404, 'Datei nicht gefunden');
        }

        $path = $invoice->document_filename;
        // Pfad zur Datei
        $fullPath = 'private/' . $path;




        if (!Storage::exists($path)) {



            abort(404, 'Datei nicht gefunden');
        }

        return response()->file(storage_path('app/' . $fullPath), [
            'Content-Type' => 'application/pdf'
        ]);
    }
}
