<?php

namespace App\Http\Controllers;

use App\Models\Print\PrintQueueItem;
use App\Models\Dsar\Dsar;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PrintQueueController extends Controller {

    public function preview(Request $request, int $id) {
        $item = PrintQueueItem::with(['document.owner', 'owner'])->findOrFail($id);

        if ($item->file_path) {
            abort_unless(Storage::exists($item->file_path), 404);
            $content  = Storage::get($item->file_path);
            $filename = basename($item->file_path);
        } else {
            $docPath = $item->document->owner->getDocumentStoragePath() . $item->document->file_name;

            if (Storage::exists($docPath)) {
                $content = Storage::get($docPath);
            } elseif (Storage::disk('public')->exists($docPath)) {
                $content = Storage::disk('public')->get($docPath);
            } else {
                abort(404);
            }

            $filename = $item->document->file_name;
        }

        return response()->make($content, 200, [
            'Content-Type'        => 'application/pdf',
            'Content-Disposition' => 'inline; filename="' . rawurlencode($filename) . '"',
        ]);
    }
}
