<?php

namespace App\Http\Controllers;

use App\Pipeline;
use App\Profile;
use App\Invitation;
use App\User;
use App\ProfileUser;
use Illuminate\Http\Request;
use App\Events\CreateProfile;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\StoreProfile;
use App\Http\Requests\UpdateProfile;
use App\Http\Controllers\Admin\PipelineController;
use Spatie\Permission\Traits\HasRoles;
use App\Http\Controllers\MailController;


class ProfileController extends Controller
{
    //


    public function index()
    {
        if (Auth::user()->hasRole('supervisor') || Auth::user()->hasRole('administrador') || Auth::user()->hasRole('teamleader')) {
            $profiles = Profile::all();
        } else {
//            $profiles = ProfileUser::where('user_id', '=', Auth::user()->id)->get();

            $profiles = Auth::user()->profiles;
            //$profiles = Profile::where('user_id', '=', Auth::user()->id)->get();

        }
        return view('profile.collection', array(
            'profiles' => $profiles,
        ));

    }

    public function create($type = null)
    {
//        dd($type);
        return view('profile.create', array(
            'type' => $type,
        ));
    }


    public function edit($id)
    {

        $profile = Profile::findOrFail($id);
        if(is_null($profile))
        {
            App::abort(404);
        }

        // 0 pendiente, 1 registrados

        //$invitations = Invitation::select('email','status')->where('profile_id', '=', $id)->Where('status', 0)->orWhere('status', 1)->get();
        $invitations = Invitation::select('email','status')->where('profile_id', '=', $id)->get();

        return view('profile.edit', array(
            'profile'     => $profile,
            'invitations' => (!empty($invitations))?$invitations->toArray():null
        ));



    }

    /**
     * @param StoreProfile $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */

    public function store(StoreProfile $request)
    {
       // $profile = new Profile();
        $profile=Profile::create($request->all());
        $profile->user_id = Auth::user()->id;
        $profile->status = 1;
        $profile->save();

        $profile->users()->save(Auth::user());
        $this->addInvitations($profile->id,$request,null,null);


    //    event(new CreateProfile($profile));


        if($request->formType != null){
            $profiles = Profile::where('user_id', '=', Auth::user()->id)->get();
            $pipelines = Pipeline::orderBy('hidden')->get();
            return view('task.create', array(
                    'profiles' => $profiles,
                    'type' => $request->formType,
                    'pipelines' => $pipelines
                )
            );

        } else {
            return redirect()->action('ProfileController@index');
        }

        //return redirect()->back()->with('message', 'Perfil creado');
        /**
        $profile->name = $request->name;
        $profile->surname = $request->surname;
        $profile->email = $request->email;
        $profile->area = $request->area;
        $profile->user_id = Auth::user()->id;
         */


    }

    public function update(UpdateProfile $request)
    {

//         dd(json_decode($request->email_list));

        $perfilId          = Profile::find($request->id);
        $perfilId->user_id = Auth::user()->id;
        $profile           = $request->all();

        $perfilId->update($profile);

        //  Borrar en profile User   mantener formato 

        if(!empty($request->email_list)){

            $email_json = json_decode($request->email_list);

            $invitedall = array();

            foreach ($email_json as $key3 => $value3) {

                array_push($invitedall,(object)array("email"=>$value3->email));
               
            }
        }


        $getInvitation = Invitation::select('email')->where('profile_id', '=', $request->id)->get()->toArray();


        if(!empty($getInvitation)){

            $getdb = array();

            foreach ($getInvitation as $key5 => $value5) {

                array_push($getdb,$value5['email']);
               
            }
        }


        // limpiar el array de emails nuevos

        if((!empty($invitedall))&&(!empty($getdb))){


            foreach ($invitedall as $key6 => $value6) {               

                if (in_array($value6->email, $getdb)){

                       unset($invitedall[$key6]);

                }
            }
        }


        if(!empty($invitedall )){ //agregè este if xq se rompe solo cuando cambio el estado

            $this->addInvitations($request->id,$request,$invitedall,true);
        }


        return redirect()->back()->with('message', 'Perfil actualizado');

    }

    public function delete(Request $request)
    {

        $profile = Profile::destroy($request->id);
        return redirect()->back()->with('message', 'Perfil eliminado');


    }


    public function removeinvited(Request $request){

        $Invitation               = Invitation::where('profile_id', '=', $request->profile_id)->where('email', '=', $request->email)->first();
        $Invitation->status       = '2';
        $Invitation->save();

    }



    public function updateProfile(Request $request)
    {
        if ($request->user()) {
            $email = $request->user()->email;
        }
    }


    public function addInvitations($id,$data,$cleared,$edit){

        
        if ($data->email_list) {
        
            $email_list = ($edit)?$cleared:json_decode($data->email_list);



            foreach ($email_list as $e) {

                $random_string = md5(microtime());
                $invitation = new Invitation();
                $invitation->profile_id = $id;
                $invitation->email = $e->email;
                $invitation->token = $random_string;
                $invitation->save();
                $user = User::where('email', '=', $e->email)->get();

                if ($user->count() == 0){
                    (new MailController)->sendMail($random_string,$e->email,$data->area);
                } else {
                    (new MailController)->sendMailLogin($random_string,$e->email,$data->area);
                }

            }

        }

    }


}
