<?php

namespace App\Http\Controllers\Web;


use Request;
use App\User;
use Validator;
use App\Services\Util;
use GuzzleHttp\Client;
use App\Services\SysLog;
use App\Mail\MailContact;
use App\Models\UserHistory;
use App\Models\UserRegister;
use App\Services\UserService;
use App\Mail\MailVerifyAccount;
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;


class RegisterController extends Controller
{

    protected $userRepo;
    /**
     * Create a new controller instance.
     *
     * @return void
     */

    public function __construct(UserRepository $userRepo)
    {
        $this->middleware('guest');
        $this->userRepo = $userRepo;
    }

    public function showConsentPage()
    {
        $data = [
            'from_member_id' => session('from_member_id')
        ];
        return view('auth.recaptcha-consent', $data);
    }

    public function acceptConsent()
    {
        if (!Request::has('recaptcha_consent')) {
            return back()->withErrors(['error' => 'Bitte stimmen Sie der Verwendung von reCAPTCHA zu']);
        }
        
        session(['recaptcha_consent' => true]);
        return redirect()->route('register.form');
    }

    public function showRegistrationForm()
    {
        if (!session('recaptcha_consent')) {
            return redirect()->route('register.consent');
        }
        $data = [
            'from_member_id' => session('from_member_id')
        ];
        return view('auth.register', $data);
    }

    public function member($from_member_id = false)
    {
        $this->userRepo->clearUserRegister();

        if(!$from_member_id){
            return redirect()->route('register.consent');
        }

        //ist ein gültiger Member ID und ist aktiv?
        $user_id = (int) str_replace('gs', '', $from_member_id) - config('main.add_number_id');
        $user = User::find($user_id);
        if(!$user || !$user->isActive() ||  !$user->isActiveAccount()){
            return redirect()->route('register.consent');
        }
        session(['from_member_id' => $from_member_id]);
        return redirect()->route('register.consent');

        /*
        //hat einen Member ID?
        if(!$member_id){
            return redirect('/registrierung');
        }

        //ist ein gültiger Member ID und ist aktiv?
        $user_id = (int) str_replace('gs', '', $member_id) - config('main.add_number_id');
        $user = User::find($user_id);
        if(!$user || !$user->isActive() ||  !$user->isActiveAccount()){
            return redirect('/registrierung');
        }
        
        if (!session('recaptcha_consent')) {
            $data = [
                'from_member_id' => Request::get('from_member_id')
            ];
            return view('auth.recaptcha-consent', $data);

            //return redirect()->route('register.consent')->with(['from_member_id' => $member_id]);
        }
        
        $data = [
            'from_member_id' => $member_id
        ];
        return view('auth.register', $data);
        */
    }


    public function register(){
        $this->userRepo->clearUserRegister();
        // Überprüfe zuerst die reCAPTCHA-Einwilligung
       
       /* if (!Request::has('recaptcha_consent')) {
            return back()->withErrors(['recaptcha_consent' => 'Bitte stimmen Sie der Verwendung von reCAPTCHA zu'])->withInput(Request::all());
        }*/
    
        // Überprüfe reCAPTCHA
        $recaptchaResponse = Request::input('g-recaptcha-response');
        if (!$this->verifyRecaptcha($recaptchaResponse)) {
            return back()->withErrors(['g-recaptcha-response' => 'Bitte bestätigen Sie, dass Sie kein Roboter sind'])->withInput(Request::all());
        }
    
        $rules = array(
            'salutation' => 'required',
            'first_name'=>'required|string|min:2',
            'last_name'=>'required|string|min:2',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'password_confirmation' => 'required|string|min:6',
            'accepted_data_protection' => 'required',
            'g-recaptcha-response' => 'required',
        );
    
        $validator = Validator::make(Request::all(), $rules);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput(Request::all());
        }

        //search in UserRegister
        $data = Request::all();

        $UserRegister = UserRegister::where('identifier', $data['email'])->first();
        if($UserRegister){
            $exists = [
                'register_email' => $data['email']
            ];
            return view('auth.existing', $exists);
        }

        $userObj = $this->userRepo->createUserRegister($data);
        $from_member_id = session('from_member_id');
        $user_id = isset($from_member_id) ? (int) str_replace('gs', '', $from_member_id) - config('main.add_number_id') : config('app.main_user_id'); // Krummel
        try {
            Mail::to($userObj->email)->bcc(config('app.info_mail'))->send(new MailVerifyAccount($userObj->confirmation_code, $userObj));
        }
        catch(\Exception $e){
            SysLog::action('register-user', 'auth_register', 5)
                ->setUserId($user_id)
                ->setModel(null, UserRegister::class)
                ->setMessage('Error send register E-Mail: '.$e->getMessage())
                ->save();
        }
        UserHistory::create(['user_id' => $user_id, 'action'=>'register', 'status'=>0]);

        return redirect('/user_register/finish');
    }

    // Neue Methode zur Überprüfung des reCAPTCHA
    private function verifyRecaptcha($recaptchaResponse)
    {
        if (empty($recaptchaResponse)) {
            return false;
        }

        $client = new Client();
        $response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
            'form_params' => [
                'secret' => config('services.recaptcha.secret_key'),
                'response' => $recaptchaResponse
            ]
        ]);

        $body = json_decode((string)$response->getBody());
        return $body->success;
    }

    public function finish()
    {
        $data = [

        ];
        return view('auth.finish', $data);
    }

    public function verify($confirmation_code){

        if( ! $confirmation_code)
        {
            return redirect('/status/error');
        }

        $UserRegister = UserRegister::where ('instance', $confirmation_code)->first();
       
        if ( ! $UserRegister)
        {
            return redirect('/status/not/found');
        }

        $user = $this->userRepo->create($UserRegister);

        //Login!
        Auth::login($user);

        return redirect('/home');
    }

    public function registerAgain(){
        $data = Request::all();
        if(!isset($data['register_email'])){
            abort(403, "No E-Mail");
        }
        $UserRegister = UserRegister::where('identifier', $data['register_email'])->first();
        if(!$UserRegister){
            abort(403, "No E-Mail Register");
        }
        Mail::to($UserRegister->identifier)->bcc(config('app.info_mail'))->send(new MailVerifyAccount($UserRegister->instance, $UserRegister->content));
        return redirect('/user_register/finish');

    }
}