<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class AuthController extends Controller
{
    public function showRegister(): View
    {
        return view('auth.register');
    }

    public function register(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'first_name' => ['required', 'string', 'max:100'],
            'surname' => ['required', 'string', 'max:100'],
            'username' => ['required', 'string', 'max:80', 'alpha_dash', 'unique:users,username'],
            'email' => ['required', 'email', 'max:150', 'unique:users,email'],
            'phone' => ['nullable', 'string', 'max:30'],
            'role' => ['required', Rule::in(['account', 'monitoring'])],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $fullName = trim($validated['first_name'].' '.$validated['surname']);

        $user = User::create([
            'first_name' => $validated['first_name'],
            'surname' => $validated['surname'],
            'name' => $fullName,
            'username' => Str::lower($validated['username']),
            'user_no' => $this->generateUserNumber($validated['role']),
            'email' => Str::lower($validated['email']),
            'phone' => $validated['phone'] ?? null,
            'role' => $validated['role'],
            'password' => $validated['password'],
        ]);

        Auth::login($user);

        return redirect()->route('dashboard')->with('success', 'Account created. User number: '.$user->user_no);
    }

    public function showLogin(): View
    {
        return view('auth.login');
    }

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

        $login = Str::lower($credentials['login']);
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (! Auth::attempt([$field => $login, 'password' => $credentials['password']], $request->boolean('remember'))) {
            return back()->withErrors([
                'login' => 'The login details are not correct.',
            ])->onlyInput('login');
        }

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

        return redirect()->intended(route('dashboard'));
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login')->with('success', 'You have been logged out.');
    }

    private function generateUserNumber(string $role): string
    {
        $prefix = $role === 'account' ? 'NG-ACC' : 'NG-MON';

        do {
            $number = $prefix.'-'.now()->format('ymd').'-'.str_pad((string) random_int(1, 99999), 5, '0', STR_PAD_LEFT);
        } while (User::where('user_no', $number)->exists());

        return $number;
    }
}
