<?php

namespace App\Http\Controllers;

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

class LoginController extends Controller
{
    //
    public function register(Request $request){
        // messageStatus success|failure|not permitted


        $json = ["messageStatus" => "failure", "errorMessage" => __("controller_messages.LoginController.unknown_error")];

        $mail = $request->input('mail');
        $username = $request->input('username');
        $password = Hash::make($request->input('password'));
        $token = $request->input('token');

        if(preg_match('/@c3gov\.de$/', $mail) != 1){
            return ["messageStatus" => "not permitted", "errorMessage" => __("controller_messages.LoginController.not_permitted")];
        }

        $rt = RegisterToken::where('token', $token)->first();
        if($rt) {
            $u = User::whereEmail($mail)->first();
            if($u) {
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.LoginController.email_in_use")];
            }
            try {
                $u = new User();
                $u->name = $username;
                $u->email = $mail;
                $u->email_verified_at = now();
                $u->password = $password;
                $u->save();

                $rt->delete();
            } catch (\Exception $e) {
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.LoginController.unknown_error_with_details", ["error" => $e->getMessage()])];
            }
        } else {
            return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.LoginController.invalid_token")];
        }

        return ["messageStatus" => "success", "errorMessage" => ""];
    }

    public function login(Request $request){
        $mail = $request->input('mail');
        $password = $request->input('password');

        $u = User::whereEmail($mail)->first();
        if($u){
            $u_pw = $u->password;

            if(Hash::check($password, $u_pw)){
                Auth::login($u);
                return ["messageStatus" => "success", "errorMessage" => ""];
            } else {
                return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.LoginController.wrong_credentials")];
            }
        } else {
            return ["messageStatus" => "failure", "errorMessage" => __("controller_messages.LoginController.wrong_credentials")];
        }
    }

}
