<?php

declare(strict_types=1);


namespace App\Blog\Controllers;

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

class AuthController extends Controller
{
    public function showLogin()
    {
        if (auth()->check()) {
            return redirect()->route('home');
        }

        return theme_view('login');
    }

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

        // 支持邮箱或用户名登录
        $login = $credentials['email'];
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';

        $user = User::query()->where($field, $login)->first();

        if ($user && $user->verifyPassword($credentials['password'])) {
            Auth::login($user, $request->boolean('remember'));
            $user->forceFill([
                'logincount' => $user->logincount + 1,
                'loginip' => $request->ip(),
                'logintime' => now(),
            ])->save();

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

        return back()->withErrors(['email' => '账号或密码错误'])->withInput();
    }

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

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

    public function showRegister()
    {
        if (auth()->check()) {
            return redirect()->route('home');
        }

        return theme_view('register');
    }

    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:50', 'unique:users,name'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'url' => ['nullable', 'url', 'max:255'],
        ]);

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'url' => $data['url'] ?? null,
            'regip' => $request->ip(),
        ]);
        $user->assignRole('member');

        Auth::login($user);

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

    public function profile()
    {
        return theme_view('profile');
    }
}
