<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PrivateMediaController extends Controller
{
    /**
     * show private image
     */
    public function index(File $file)
    {
        /** @var App\Models\User $user */
        $user = auth()->user();

        if ($file->visibility != 'private') {
            return redirect()->route('index');
        }

        if (!Storage::disk('private_media')->exists(str_replace('/private_media/', '', $file->url))) {
            return redirect()->route('index');
        }

        if ($user->id === $file->user_id || in_array($user->type, ['admin', 'owner'])) {
            return response()->file(Storage::disk('private_media')->path(str_replace('/private_media/', '', $file->url)));
        } else {
            return redirect()->route('index');
        }
    }
}
