<?php

namespace App\Http\Controllers\Auth;

use App\Events\UserRegistered;
use App\Rules\Mobile;
use App\User;
use App\Http\Controllers\Controller;
use App\Verification;
use Carbon\Carbon;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */
    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */

    protected $redirectTo = '/panel';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'rules' => 'accepted',
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'mobile' => ['required', new Mobile(), 'unique:users'],
            'password' => ['required', 'min:8'],

        ], [
            'rules.accepted' => 'پذیرفتن قوانین و مقررات الزامی میباشد'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param array $data
     * @return User
     */
    protected function create(array $data)
    {
        $mustVerifyEmail = config('must_verify_email');
        $mustVerifyMobile = config('must_verify_mobile');

        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'email_verified_at' => $mustVerifyEmail ? null : Carbon::now(),
            'mobile' => $data['mobile'],
            'mobile_verified_at' => $mustVerifyMobile ? null : Carbon::now(),
            'status' => 'active',
            'role' => 'user',
            'password' => $data['password'],
        ]);
    }


    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        if ($user = $this->create($request->all())) {
            $mustVerifyEmail = config('must_verify_email');
            $mustVerifyMobile = config('must_verify_mobile');
            $verificationToken = Verification::createEmailToken();

            if ($mustVerifyEmail and !$mustVerifyMobile) {
                $verification = Verification::create([
                    'user_id' => $user->id,
                    'type' => 'email',
                    'ip' => $request->ip(),
                    'token' => $verificationToken
                ]);
                //call user registered event so we can send email and SMS
                event(new UserRegistered($user, $verification, null));

                return view('auth.verifyEmail', ['email' => $user->email]);
            } elseif ($mustVerifyMobile and !$mustVerifyEmail) {
                $verification = Verification::create([
                    'user_id' => $user->id,
                    'type' => 'sms',
                    'ip' => $request->ip(),
                    'token' => $verificationToken = Verification::createMobileToken()
                ]);

                //call user registered event so we can send email and SMS
                event(new UserRegistered($user, $verification, null));

                return redirect()->route('verify.mobile')->with('mobile', $user->mobile);
            } elseif (!$mustVerifyMobile and !$mustVerifyEmail) {
                $successMsg = 'حساب کاربری شما با موفقیت ساخته شد اکنون میتوانید وارد حساب کاربری خود شوید';
                return redirect()->route('login')->with('success', $successMsg);
            } else {
                $emailVerification = Verification::create([
                    'user_id' => $user->id,
                    'type' => 'email',
                    'ip' => $request->ip(),
                    'token' => $verificationToken
                ]);

                $mobileVerification = Verification::create([
                    'user_id' => $user->id,
                    'type' => 'sms',
                    'ip' => $request->ip(),
                    'token' => Verification::createMobileToken()
                ]);

                //call user registered event so we can send email and SMS
                event(new UserRegistered($user, $emailVerification, $mobileVerification));

                return redirect()->route('verify.mobile')->with('mobile', $user->mobile);
            }
        } //there was a problem creating user account
        else {
            return redirect()->back()
                ->with(['error' => 'در ساخت حساب کاربری خطایی بوجود آمده است'])->withInput();
        }
    }
}
