<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class SessionSecurity
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // Cek session timeout (2 jam)
        $lastActivity = session('last_activity');
        $timeout = 7200; // 2 jam dalam detik
        
        if ($lastActivity && (time() - $lastActivity) > $timeout) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            
            Log::info('Session timeout', [
                'user_id' => Auth::id(),
                'ip' => $request->ip(),
                'last_activity' => $lastActivity,
                'timestamp' => now()
            ]);
            
            return redirect()->route('login')
                ->with('error', 'Session telah berakhir. Silakan login kembali.');
        }
        
        // Update last activity
        session(['last_activity' => time()]);
        
        // Cek user masih aktif
        if (Auth::check() && !Auth::user()->is_active) {
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            
            Log::warning('Inactive user access attempt', [
                'user_id' => Auth::id(),
                'email' => Auth::user()->email ?? 'unknown',
                'ip' => $request->ip(),
                'timestamp' => now()
            ]);
            
            return redirect()->route('login')
                ->with('error', 'Akun Anda telah dinonaktifkan. Hubungi administrator.');
        }
        
        return $next($request);
    }
}
