<?php

namespace App\Http\Controllers\Api;

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

/**
 * تسليم صور خدمات الراكب عبر Laravel عندما يفشل الوصول المباشر إلى public/storage (500 أو symlink).
 */
class PassengerExtraServiceMediaController extends Controller
{
    public function __invoke(Request $request)
    {
        $relative = $request->query('path', '');
        if (! is_string($relative) || $relative === '') {
            abort(404);
        }

        $relative = str_replace('\\', '/', $relative);
        if (str_contains($relative, '..')) {
            abort(404);
        }

        $allowedPrefixes = [
            'passenger_extra_services/',
            'passenger_extra_service_items/',
        ];
        $isAllowed = false;
        foreach ($allowedPrefixes as $prefix) {
            if (str_starts_with($relative, $prefix)) {
                $isAllowed = true;
                break;
            }
        }
        if (! $isAllowed) {
            abort(404);
        }

        if (! Storage::disk('public')->exists($relative)) {
            abort(404);
        }

        return Storage::disk('public')->response($relative, basename($relative), [
            'Cache-Control' => 'public, max-age=86400',
        ]);
    }
}
