<?php

namespace App\Http\Controllers\Web\Auth;

use App\Http\Controllers\Controller;
use App\Models\Auth\Verification;
use App\Models\User;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function twoFactorLogin(Request $request)
    {
        $request->merge(['phone_number' => substr(str_replace(['+', '(', ')', '-'], '', $request->phone_number), 3)]);

        $request->validate([
            'phone_number' => ['required', 'integer', 'between:61000000,65999999'],
            'verification_code' => ['nullable', 'integer'],
        ]);

        if ($request->filled('verification_code')) {
            return $this->login($request);
        }

        sendSMSVerification($request->phone_number);

        return response()->rest();
    }

    public function login(Request $request)
    {
        $verification = Verification::where('username', $request->phone_number)
            ->where('code', $request->verification_code)
            ->first();

        if (! $verification) {
            return response()->rest([], 401, 'Verification not found');
        }

        $user = User::firstOrCreate(
            ['phone_number' => $request->phone_number],
            [
                'first_name' => 'Ulanyjy',
                'last_name' => 'Ulanyjy',
                'email' => $request->phone_number.'user@fakemail.com',
            ]
        );

        auth()->login($user);

        return response()->rest([], 200, 'Login');
    }
}
