<?php

namespace AhmadFatoni\ApiGenerator\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use TPS\Birzha\Classes\ErrorResponseApi;

class EmailVerificationController extends KabinetAPIController
{
    public function sendEmailVerificationLink(Request $request)
    {
        $inputData = $request->all();

        $rules = [
            'locale' => 'required|in:ru,tm,en'
        ];

        $validator = Validator::make($inputData, $rules);
        if($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        if(!$this->user->email_verified) {
            $code = sha1(time());
            $vars = [
                'verification_link' => url('verify-email', ['id' => $this->user->id, 'code' => $code])
            ];

            try {
                \Mail::queue('tps.birzha::mail.' . $inputData['locale'] . '.email_verify', $vars, function($message) {
                    $message->to($this->user->email, 'Birzha User');
                    $message->subject(\Lang::get('rainlab.user::lang.account.email_verification'));
                });
            } catch(Throwable $th) {
                \Log::info($th);
                
                return response()->json(ErrorResponseApi::translateErrorMessage('api.cannot_verify_invalid_email'), 400);
            }

            $this->user->email_activation_code = $code;
            $this->user->save();

            return response()->json(trans('validation.api.verification_link_sent', [], $inputData['locale']), 201);

        } else {
            return response()->json(ErrorResponseApi::translateErrorMessage('api.email_already_verified'), 200);
        }
    }
}
