<?php


namespace App\Http\Controllers;

use App\User;
use Auth;
use Validator;
use Request;
use Carbon\Carbon;
use Illuminate\Database\Connection;
use App\Mail\MailActivateUser;
use Illuminate\Support\Facades\Mail;

class UserUpdateEmailController extends Controller
{


    protected $db;

    protected $table = 'user_update_emails';

    protected $resendAfter = 60; //1min


    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    public function index()
    {
        return view('user.update_email');

    }

    public function update(Request $request)
    {
        $user = Auth::user();

        $rules = array(
            'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:' . Auth::user()->id,
            //'email-confirm' => 'required|same:email',
        );

        Validator::extend('users_update_email', function ($attribute, $value, $parameters, $validator) {
            if($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()){
                return false;
            }
            return true;

        });
        $validator = Validator::make(Request::all(), $rules);
        if ($validator->fails()) {
            // redirect our user back to the form with the errors from the validator
            $messages = $validator->messages();

            return view('user.update_email')->withErrors($validator);


        }else{
            $this->sendActivationMail($user, Request::all());
            \Session()->flash('alert-success', __('We sent you an activation code. Check your email!'));
            return redirect(route('user_update_email'));
        }

    }


      public function adminChangeMail($user_id)
    {
        if(!Auth::user()->isAdmin()){
            abort(404);
        }
        $data = [
            'user' => User::findOrFail($user_id),
        ];
        return view('admin.change_email', $data);

    }
      public function adminUpdateMail(Request $request, $user_id)
    {
        if(!Auth::user()->isAdmin()){
            abort(404);
        }
        $user = User::findOrFail($user_id);
        $data = [
            'user' => $user,
        ];


        $rules = array(
            'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:' . $user->id,
            //'email-confirm' => 'required|same:email',
        );

        Validator::extend('users_update_email', function ($attribute, $value, $parameters, $validator) {
            if($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()){
                return false;
            }
            return true;

        });
        $validator = Validator::make(Request::all(), $rules);
        if ($validator->fails()) {
            // redirect our user back to the form with the errors from the validator
            $messages = $validator->messages();

            return view('admin.change_email', $data)->withErrors($validator);


        }else{

            $this->sendActivationMail($user, Request::all());
            \Session()->flash('alert-success', __('An activation code was sent to the account by e-mail!'));
            return redirect(route('admin_lead_edit', [$user->id]));
        }

    }




    public function activateMail($token)
    {

        if ($updateEmail = $this->getUpdateEmailByToken($token)) {
            $user = User::findOrFail($updateEmail->user_id);
            if($user->id == $updateEmail->user_id){
                $user->fill([
                    'email' => $updateEmail->email
                ])->save();
                $this->deleteUpdateEmail($token);
                //Login!
                Auth::login($user);
                \Session()->flash('alert-success', __('Your e-mail has been changed.'));
                return redirect('/home');

            }
        }
        return redirect('/home');
        abort(404);
    }


    public function sendActivationMail($user, array $data)
    {
        $token = $this->createActivation($user, $data);
        Mail::to($data['email'])->send(new MailActivateUser($token, $user));
    }


    protected function getToken()
    {
        return hash_hmac('sha256', str_random(40), config('app.key'));
    }

    public function createActivation($user, array $data)
    {

        $updateEmail = $this->getUpdateEmail($user);

        if (!$updateEmail) {
            return $this->createToken($user, $data);
        }
        return $this->regenerateToken($user, $data);

    }

    private function regenerateToken($user, array $data)
    {

        $token = $this->getToken();
        $this->db->table($this->table)->where('user_id', $user->id)->update([
            'email' => $data['email'],
            'token' => $token,
            'created_at' => new Carbon()
        ]);
        return $token;
    }

    private function createToken($user, array $data)
    {
        $token = $this->getToken();
        $this->db->table($this->table)->insert([
            'user_id' => $user->id,
            'email' => $data['email'],
            'token' => $token,
            'created_at' => new Carbon()
        ]);
        return $token;
    }

    public function getUpdateEmail($user)
    {
        return $this->db->table($this->table)->where('user_id', $user->id)->first();
    }


    public function getUpdateEmailByToken($token)
    {
        return $this->db->table($this->table)->where('token', $token)->first();
    }

    public function deleteUpdateEmail($token)
    {
        $this->db->table($this->table)->where('token', $token)->delete();
    }
}