<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Organization;
use App\Support\IdFormatter;
use App\Support\ColorHelper;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;

class OrganizationsMiddleware
{
    public function handle($request, Closure $next)
    {
        // Auth middleware đã chạy trước, Auth::user() luôn available
        $user = Auth::user();

        if (!$user) {
            abort(403, 'Forbidden');
        }

        // Xác định organization từ route param (nếu có) hoặc từ user
        $orgParam = $request->route('organization') ?? $request->route('organization_id');
        $org = null;

        if ($orgParam) {
            $org = IdFormatter::findOrganizationByHex($orgParam);
        }

        if (!$org && !empty($user->organization_id)) {
            $userOrgBin = $user->getAttributes()['organization_id'] ?? null;
            $org = Organization::where('id', $userOrgBin)->first();
        }

        if (!$org) {
            abort(403, 'Forbidden');
        }

        $request->attributes->set('current_organization', $org);

        // Chia sẻ màu primary hue của organization ra view
        $hue = (int)($org->primary_hue ?? 210);
        $hex = ColorHelper::hslToHex($hue, 75, 50);

        try {
            View::share('app_primary_hue', $hue);
            View::share('app_primary_hex', $hex);
        } catch (\Throwable $e) {
            // Không làm gì nếu share lỗi
        }

        return $next($request);
    }
}
