<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class AuthController extends Controller
{
    public function showLogin()
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        return view('auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'login' => 'required',
            'password' => 'required'
        ]);

        $loginType = filter_var($request->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'employee_id';

        $credentials = [
            $loginType => $request->login,
            'password' => $request->password
        ];

        if (Auth::attempt($credentials)) {

            $request->session()->regenerate();

            session(['token_version' => Auth::user()->token_version]);

            Redis::lpush('login_logs', json_encode([
                'user_id' => Auth::id(),
                'event' => 'login',
                'ip' => request()->ip(),
                'time' => now()
            ]));

            return redirect('/dashboard');
        }

        return back()->withErrors([
            'login' => 'ID Pekerja / Email atau Password salah.'
        ]);
    }

    public function logout(Request $request)
    {
        $userId = Auth::id(); // ambil dulu sebelum logout

        Redis::lpush('login_logs', json_encode([
            'user_id' => $userId,
            'event' => 'logout',
            'ip' => request()->ip(),
            'time' => now()
        ]));

        Auth::logout();

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

        return redirect('/login');
    }
}
