<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\UserActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

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

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

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        if (! $user->is_active) {
            throw ValidationException::withMessages([
                'email' => ['Your account has been deactivated.'],
            ]);
        }

        Auth::login($user);

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

        UserActivityLog::logLogin($user, $request, $request->client_time);

        return redirect()->intended('/pos');
    }

    public function logout(Request $request)
    {
        $user = Auth::user();
        if ($user) {
            UserActivityLog::logActivity($user, 'logout', 'User logged out', [], $request, $request->client_time);
        }

        Auth::logout();

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

        return redirect('/login');
    }

    public function autoLogout(Request $request)
    {
        $user = Auth::user();
        $clientTime = $request->input('client_time');

        if ($user) {
            UserActivityLog::logAutoLogout($user, $request->ip(), $clientTime);
        }

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

        return response()->json(['success' => true]);
    }
}
