<?php

namespace App\Http\Controllers;

use App\Models\LoginLog;
use App\Models\ActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function index()
    {
        if (Auth::check()) {
            return redirect()->route('admin.dashboard');
        }
        return view('auth.login');
    }

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

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            $user = Auth::user();

            // Catat log login berhasil
            $log = LoginLog::create([
                'user_id'     => $user->id,
                'user_name'   => $user->name,
                'role'        => $user->role,
                'email'       => $user->email,
                'ip_address'  => $request->ip(),
                'user_agent'  => $request->userAgent(),
                'status'      => 'success',
                'logged_in_at'=> now(),
            ]);

            // Simpan id log di session untuk update logout nanti
            session(['login_log_id' => $log->id]);

            // Catat juga di activity log
            ActivityLog::record(
                "Login ke sistem sebagai {$user->role}",
                'User', $user->id
            );

            // Redirect sesuai role
            return match ($user->role) {
                'guru'   => redirect()->intended('/guru/dashboard'),
                'kepsek' => redirect()->intended('/kepsek/dashboard'),
                default  => redirect()->intended('/admin/dashboard'),
            };
        }

        // Catat log login gagal
        LoginLog::create([
            'user_id'     => null,
            'user_name'   => 'Unknown',
            'role'        => null,
            'email'       => $request->email,
            'ip_address'  => $request->ip(),
            'user_agent'  => $request->userAgent(),
            'status'      => 'failed',
            'logged_in_at'=> now(),
        ]);

        return back()->withErrors([
            'email' => 'Email atau password salah.',
        ])->onlyInput('email');
    }

    public function logout(Request $request)
    {
        $user = Auth::user();

        // Update waktu logout di login_log
        $loginLogId = session('login_log_id');
        if ($loginLogId) {
            LoginLog::where('id', $loginLogId)->update([
                'logged_out_at' => now(),
            ]);
        }

        // Catat di activity log
        if ($user) {
            ActivityLog::record(
                "Logout dari sistem",
                'User', $user->id
            );
        }

        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login');
    }
}
