<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class OwnerMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();

        // Admins can access owner modules for platform-wide oversight.
        if ($user && $user->role === 'admin') {
            return $next($request);
        }

        if (!$user || $user->role !== 'owner' || !$user->company_id) {
            return response()->json([
                'success' => false,
                'message' => 'Access denied. Only company owners can access this resource.',
            ], 403);
        }

        return $next($request);
    }
}

