<?php

namespace App\Http\Controllers;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class AccountController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function registerView() {
        if(!env('REGISTER_ENABLED')){
            return abort(401);
        }
        return view("account.register");
    }

    public function register(Request $request) {
        if(!env('REGISTER_ENABLED')){
            return abort(401);
        }
        $validated = $request->validate([
            'username' => 'required|unique:users|unique:tenants,url|regex:/^[a-z0-9]{8,30}$/i',
            'email' => 'required|unique:users|email:rfc,dns',
            'password' => 'required|min:8|confirmed',
        ]);

        $user = new User();
        $user->password = Hash::make($validated["password"]);
        $user->username = $validated["username"];
        $user->email = $validated["email"];
        $user->saveOrFail();

        $tenant = new Tenant();
        $tenant->name = $validated["username"];
        $tenant->url = $validated["username"];
        $tenant->template = "default";
        $tenant->owner = $user->id;
        $tenant->saveOrFail();

        Auth::attempt(["username" => $user->username, "password" => $validated["password"]]);
        return redirect("/d");
    }

    public function loginView() {
        if(Auth::check()) {
            return redirect("/d");
        }
        return view("account.login");
    }

    public function login(Request $request) {
        $credentials = $request->only('username', 'password');
        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            return redirect("/d");
        }

        return back()->withErrors([
            'username' => 'The provided credentials do not match our records.',
        ]);
    }
}
