<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Hash;
//use App\Mail\SignUp;
use App\Models\ReferUser;
use Auth;
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 = RouteServiceProvider::HOME;

    /**
     * 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)
    {
      // if($data['user_type']==1){
            return Validator::make($data, [
                'givenname' => ['required', 'string', 'max:255'],
                'familyname' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],
                'nationality' => ['required', 'string','max:255'],
                'dob' => ['required', 'string','date'],
                'optradio' => ['required', 'string','max:255'],
            ]);
       // }

    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(Request $req)
    {
        //if($data['user_type']==1){ 
            $token =Str::random(64);

            $user_check_data =User::where('email',$req->email)->where('user_type',1)->where('sign_up',1)->doesntExist();

            if($user_check_data){
                $user_data = User::create([
                    'first_name' => $req->givenname,
                    'last_name' => $req->familyname,
                    'email' => $req->email,
                    'nationality' => $req->nationality,
                    'dob' => \Carbon\Carbon::parse($req->dob)->format('Y-m-d'),
                    'gender' => $req->optradio,
                    'user_type' => 1,
                    'password' => Hash::make($req->password),
                    'status' => 0,
                    'remember_token' => $token,
                    'sign_up' =>1,
                    'register_type' =>5, // Normal registration student
                    'registered_date' =>now(),
                ]);

            }else{
                return redirect()->to("/login")->with('success','You are already registered. Please login here.');
            }
            

            $refer_user_exists = ReferUser::where('email',$req->email)->first();

            if($refer_user_exists){
                $refer_user_exists->signup =1;
                $refer_user_exists->update();
            }

            $data['token'] = $token;
            $data['name'] = $req->givenname .' '.$req->familyname;
            $data['receive_email']=$req->email;
            $user_mail = $req->email;
            $from = 'asraful@revinr.com';

            Mail::send('email.student_signup_verify_email',$data, function ($message) use ($user_mail,$from) {
                $message->from($from);
                $message->to($user_mail)->subject('Email Verification Required: Complete your Registration');
            });

          return redirect()->to("/login")->with('success','Your registration successfully saved. Please check your email for verification');
        //}


    }

    public function showRegistrationForm()
    {

        return view('auth.register');
    }



    public function email_verification($token)
     {
        $data = User::where('remember_token',$token)->first();
        if($data->email_verification ==1){
            return Redirect('/login');  
        } 
        $data->email_verification=1;
        $data->email_verified_at=now();
        $data->status=1;
        $data->update(); 
        return Redirect('/login')->with('success','Your e-mail has been verified successfully. Please login to your account');
        
     }
}
