<?php

namespace App\Http\Middleware;

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

class StampCompanySession
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // After request processes, stamp session row with company_id/user_id
        if (auth('web')->check()) {
            $user      = auth('web')->user();
            $sessionId = $request->session()->getId();

            DB::table('company_sessions')
                ->where('id', $sessionId)
                ->update([
                    'company_id'   => $user->company_id,
                    'user_id'      => $user->id,
                    'logged_in_at' => DB::raw('COALESCE(logged_in_at, NOW())'),
                ]);
        }

        return $response;
    }
}
