<?php

namespace App\Http\Controllers;

use App\Invitation;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\DB;

class ValidateInvitedController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */

    public function __construct()
    {
        //   $this->middleware('guest');
        //	  si el usuario registrado esta logueado con el middleware se cortaba el seteo a DB
    }


    public function index(Request $data)
    {


        $profile = Invitation::where('token', '=', $data['token'])->first();
        if ($profile) {


            if ($profile["status"] == 0) {


                if ($data['login'] == "true") {

                    $profile->status = '1';
                    $profile->save();

                    $user = User::where('email', '=', $profile["email"])->first();

                    DB::table('profile_user')->insert(['profile_id' => $profile['profile_id'], 'user_id' => $user['id']]);

                }


                $router = ($data['login'] == "true") ? "login" : "register";

                return redirect($router . "/?token=" . $data['token'] . "&mail=" . $data['mail']);

            } else {

                die("La invitación caduco");
                exit;
            }
        }else{
            die("La invitación no existe");
            exit;
        }

    }


}
