<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;

class AuthenticatedSessionController extends Controller
{
    public function create()
    {
        return view('auth.login');
    }

    public function store(LoginRequest $request)
    {
        $request->authenticate();

        $user = Auth::user();
        
        // Check if user has admin or operator role
        if (!$user->hasRole(['admin', 'operation'])) {
            Auth::logout();
            return back()->withErrors([
                'email' => 'You do not have permission to access the dashboard.',
            ]);
        }

        // Check if account is deactivated
        if ($user->deactivated_at) {
            Auth::logout();
            return back()->withErrors([
                'email' => 'Your account is deactivated. Please contact the administrator.',
            ]);
        }

        // Check if account is locked
        if ($user->locked_until && $user->locked_until > now()) {
            Auth::logout();
            return back()->withErrors([
                'email' => 'Your account is locked. Please try again later.',
            ]);
        }

        // Reset login attempts on successful login
        $user->login_attempts = 0;
        $user->locked_until = null;
        $user->save();

        // Update last login information
        $user->last_login_at = now();
        $user->last_login_ip = $request->ip();
        $user->last_login_user_agent = $request->userAgent();
        $user->save();

        // Set session timeout
        $request->session()->put('last_activity', now());

        // Regenerate session ID for security
        $request->session()->regenerate();

        // Set remember me cookie if requested
        if ($request->boolean('remember')) {
            $rememberToken = Hash::make($user->id . $request->ip() . time());
            $user->remember_token = $rememberToken;
            $user->save();
            
            $cookie = cookie('remember_token', $rememberToken, 43200); // 30 days
            return redirect()->intended(RouteServiceProvider::HOME)->withCookie($cookie);
        }

        return redirect()->intended(RouteServiceProvider::HOME);
    }

    public function destroy(Request $request)
    {
        $user = Auth::user();
        
        // Clear remember me token
        if ($user) {
            $user->remember_token = null;
            $user->save();
        }

        Auth::guard('web')->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }
} 