<?php

namespace App\Http\Controllers\User;

use App\Enums\AppStatus;
use App\Http\Controllers\Controller;
use App\Models\AppModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ViewController extends Controller
{
    public function login()
    {
        if (Auth::guard('web')->check()) {
            return redirect('/user/');
        }

        return view('user.login');
    }

    public function register()
    {
        if (Auth::guard('web')->check()) {
            return redirect('/user/');
        }

        return view('user.register');
    }

    public function forgotPassword()
    {
        if (Auth::guard('web')->check()) {
            return redirect('/user/');
        }

        return view('user.forgot-password');
    }

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

        $loginField = $this->resolveLoginField($credentials['username']);
        $attemptData = [
            $loginField => $credentials['username'],
            'password' => $credentials['password'],
            'status' => 1,
        ];

        if (Auth::guard('web')->attempt($attemptData)) {
            $request->session()->regenerate();
            $user = Auth::guard('web')->user();
            $user->incrementLoginCount($request->ip());

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

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

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

        return redirect('/user/login');
    }

    public function index()
    {
        return view('layouts.user');
    }

    public function dashboard()
    {
        return view('user.dashboard');
    }

    public function accountIndex()
    {
        return view('user.account.index');
    }

    public function accountPassword()
    {
        return view('user.account.password');
    }

    public function disabledApp(string $appId)
    {
        $app = AppModel::where('app_id', $appId)->first();

        if (! $app || $app->status === AppStatus::ENABLED) {
            abort(404);
        }

        return view('errors.user-app-disabled', ['appName' => $app->name]);
    }

    private function resolveLoginField(string $input): string
    {
        if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
            return 'email';
        }

        if (preg_match('/^1[3-9]\d{9}$/', $input)) {
            return 'phone';
        }

        return 'username';
    }
}
