<?php

namespace App\Http\Controllers\Core\Auth;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Core\Auth\User\UserRegistrationRequest;
use App\Models\Core\Auth\User;
use App\Repositories\Core\Setting\SettingRepository;
use App\Repositories\Core\Status\StatusRepository;
use App\Services\Core\Auth\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserRegistrationController extends Controller
{
    public function __construct(UserService $service)
    {
        $settings = resolve(SettingRepository::class)->getFormattedSettings();
        if ('cli' != php_sapi_name()) {
            throw_if(($settings['registration'] == 0), new GeneralException(trans('default.action_not_allowed'), 404));
        }
        $this->service = $service;
    }

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

    public function store(UserRegistrationRequest $request)
    {
        DB::transaction(function () use ($request) {
            $invitation_token = base64_encode($request->email . '-invitation-from-us'.date('YmdHis'));
            $user = $this->service->register($invitation_token)->getModel();
            $this->service->setModel($user)->assignRole([2]);

            $this->service->sendVerificationMail($user, $invitation_token);

        });
        return created_responses('user');
    }

    public function confirm()
    {
        $status = resolve(StatusRepository::class)->userActive();
        $user = User::where(['email' => request()->email, 'invitation_token' => request()->token])->first();

        throw_if(!$user, new GeneralException(trans('default.invalid_token')));

        $user->fill(['status_id' => $status, 'invitation_token' => NULL])
            ->save();

        auth()->login($user);

        return redirect()->route(home_route()['route_name'], ['params' => home_route()['route_params']]);

    }

    public function showResentEmail()
    {
        return view('frontend.user.resent_verify_link');
    }

    public function resentVerifyEmail(Request $request)
    {
        $status = resolve(StatusRepository::class)->userUnverified();

        $user = User::findByEmail($request->email);

        throw_if(!$user , new GeneralException(trans('default.email_invalid')));
        throw_if( optional($user)->status_id !== $status , new GeneralException(trans('default.email_invalid')));

        $invitation_token = base64_encode($request->email . '-invitation-from-us');
        $user->fill(['invitation_token' => $invitation_token])
            ->save();

        $this->service->sendVerificationMail($user, $invitation_token);
        return custom_response('user_verification_email_resent');
    }
}
