<?php

namespace App\Http\Controllers\Frontend\Auth;

use App\Http\Controllers\Controller;
use App\Mail\InviteCreated;
use App\Models\Auth\Invite;
use App\Models\Auth\User;
use App\Models\Messages\ExtendedThread;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class InviteController extends Controller
{
    public function invite()
    {
        // show the user a form with an email field to invite a new user
        return view('frontend.auth.invite');
    }

    public function process(Request $request)
    {
        // validate the incoming request data
        // is this email already invited to this lab?
        if (Invite::where(['email' => $request->get('email')])
            ->whereIn('created_by', ['created_by' => auth()->user()->id])->exists()) {
            return redirect()->route('frontend.user.account')->withFlashDanger($request->get('email') . ' has already been invited');
        }
        // 20200519 is this user... themselves?
        if (auth()->user()->email == $request->get('email')) {
            return redirect()->route('frontend.user.account')->withFlashDanger('You are already in this lab :)');
        }
        do {
            //generate a random string using Laravel's str_random helper
            // $token = "This_is_a_token".time();
            $token = openssl_random_pseudo_bytes(16);
            $token = bin2hex($token);
            //dd($token);
        } //check if the token already exists and if it does, try again
        while (Invite::where('token', $token)->first());
        //create a new invite record
        $invite = Invite::create([
            'email' => $request->get('email'),
            'token' => $token,
            'created_by' => auth()->user()->id
        ]);

        // send the email
        Mail::to($request->get('email'))->send(new InviteCreated($invite));
        // redirect back where we came from
        return redirect()->route('frontend.user.account')->withFlashSuccess("Invitation sent to " . $request->get('email'));
//        return redirect()
//            ->back();
    }

    public function accept($token)
    {
        // Look up the invite
        if (!$invite = Invite::where('token', $token)->first()) {
            //if the invite doesn't exist do something graceful with it
            return redirect()->route('frontend.auth.register')->withFlashDanger("That's not a valid invitation, but you can still sign up!");
        }
        // dd($invite->user->myLab->name);
        // @TODO if the user is already in the system, add them to the lab
        if (User::where('email', $invite->email)->exists()) {
            //dd(User::where('email', $invite->email));
            // dd($invite->user->myLab->name);
            return redirect()->route('frontend.user.account')->withFlashSuccess("Please login to accept the invitation");;
        } else {
            return redirect()->route('frontend.auth.register')->withFlashSuccess("Please register to accept the invitation");
        }

    }

    public function acceptfromnotification($id)
    {
        $invite = Invite::find($id);
        // check to see that it's the right invite

        if ($invite->email == auth()->user()->email) {
            $labname = $invite->user->myLab->name;
            // is there enough licences for this?
            if($invite->user->myLab->members()->count()<$invite->user->my_lab->user_limit) {
                if (!$invite->user->myLab->members->contains(auth()->user())) {
                    $invite->user->myLab->members()->attach(auth()->user());
                }
                //add the lab member role to this user, along with any others they may have
                $roles = ['lab member'];
                if (auth()->user()->role) {
                    $roles[] = auth()->user()->role->name;
                }
                auth()->user()->assignRole($roles);
                // update the message thread
                $message = $invite->messagethread->latest_message;
                $message->body = "You accepted the invitation to {$labname} on " . Carbon::now()->locale('en_AU')->isoFormat('lll');
                $message->save();
                // delete the invite
                $invite->delete();
                return redirect()->route('frontend.index')->withFlashSuccess('You have been added to the lab ' . $labname);
            }else{
                return redirect()->route('frontend.index')->withErrors('There are no spare licences, please contact the lab admin');
            }
        } else {
            return redirect()->route('frontend.index')->withErrors('There was a problem with the invite');
        }

    }

    public function rejectfromnotification($id)
    {
        $invite = Invite::find($id);
        if ($invite->email == auth()->user()->email) {
            $labname = $invite->user->myLab->name;
            $message = $invite->messagethread->latest_message;
            $message->body = "You declined this invitation to {$labname} on " . Carbon::now()->locale('en_AU')->isoFormat('lll');
            $message->save();
            $invite->delete();
            return redirect()->route('frontend.index')->withFlashSuccess('Invite to ' . $labname . ' rejected');
        } else {
            return redirect()->route('frontend.index')->withErrors('There was a problem with rejecting the invite');
        }
    }

    public function resendinvite($id){
        $invite = Invite::find($id);
        try {
            Mail::to($invite->email)->send(new InviteCreated($invite));
            return array(
                'status' => 0,
            );
        }catch (\Exception $e){
            return array(
                'status' => 1,
                'message'=>$e->getMessage()
            );
        }

    }

    public function deleteinvite($id){
        $invite = Invite::find($id);
        $invite->delete();
        return array(
            'status' => 0,
        );
    }
}

