<?php

namespace App\Http\Middleware;

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

class TrackUserSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Only track sessions for authenticated users
        if ($request->user()) {
            // Get the current session ID
            $sessionId = $request->session()->getId();
            
            // Use Agent package to parse user agent
            $agent = new Agent();
            $agent->setUserAgent($request->userAgent());
            
            // Determine device type
            $deviceType = 'Unknown';
            if ($agent->isDesktop()) {
                $deviceType = 'Desktop';
            } elseif ($agent->isPhone()) {
                $deviceType = 'Phone';
            } elseif ($agent->isTablet()) {
                $deviceType = 'Tablet';
            }
            
            // Get device name
            $deviceName = $agent->device();
            if (empty($deviceName)) {
                $deviceName = $deviceType;
            }
            
            // Get browser and platform
            $browser = $agent->browser() . ' ' . $agent->version($agent->browser());
            $platform = $agent->platform() . ' ' . $agent->version($agent->platform());
            
            // For location and country, we would typically use a geolocation service
            // For simplicity, we'll just use the IP address for now
            // In a production environment, you would integrate with a service like MaxMind GeoIP
            $location = 'Unknown';
            $country = 'Unknown';
            
            // Update the session record with device info
            DB::table('sessions')
                ->where('id', $sessionId)
                ->update([
                    'device_type' => $deviceType,
                    'device_name' => $deviceName,
                    'browser' => $browser,
                    'platform' => $platform,
                    'location' => $location,
                    'country' => $country
                ]);
        }

        return $response;
    }
}