<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\StoreUnit;
use App\Pipeline;
use App\Profile;
use App\Unittype;
use App\UserAutotag;
use App\UserUnit;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Unit;
use App\User;
use App\TeamRole;
use Illuminate\Http\Response;
use App\Http\Requests\DeleteUserUnitRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use App\Libraries\Utils;



class UnitController extends Controller
{
    public function index()
    {

        $units = Unit::all();

        $data = array(
            'units' => $units,
        );
        return view('unit.collection', $data);
    }

    public function create()
    {

        $unittypes = Unittype::all();

        $data = array(
            'unitTypes' => $unittypes,
        );
        return view('unit.create', $data);

    }

    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {

        //tag profile
        $perfilarray = array();
        $perfiles = Profile::where('status',1)->get()->unique('email');

        foreach ($perfiles as $perfil){

            array_push($perfilarray, ['id'=>$perfil->id,'area'=>$perfil->area]);
        }
        //fin tag profile

        //prueba

        $unit = Unit::find($id);
        $unitTypes = Unittype::all();
        $users = User::all()->sortBy('name');
        $teamroles = TeamRole::all();

        $pipeline = Pipeline::all();
        $auto_tag = UserAutotag::where('unit_id',$id)->where('pipeline_id','<>',null)->where('profile_id','=',null)->get();
        $autotag_Profile = UserAutotag:: where('unit_id',$id)->where('profile_id','<>',null)->where('pipeline_id','=',null)->get();//tag profile


        $data = array(
            'unit' => $unit,
            'unitTypes' => $unitTypes,
            'users' => $users,
            'teamroles' => $teamroles,
            'pipeline'=>$pipeline,
            'auto_tag' =>$auto_tag,
            'arrayperfil' => $perfilarray,
            'autotag_profile' => $autotag_Profile,

        );
        return view('unit.edit', $data);

    }

    public function update(StoreUnit $request)
    {
        $res = Unit::find($request->id);
        $res->name = $request->name;
        $res->slug = $request->slug;
        $res->color = $request->color;
        $res->unitType_id = $request->unitType_id;
        $res->save();
        return redirect()->back()->with('message', 'Unidad Actualizada');

    }

    public function store(StoreUnit $request)
    {

        Unit::create([
            'name' => $request->name,
            'slug' => $request->slug,
            'color' => $request->color,
            'unitType_id' => $request->unitType_id,
        ]);

        return redirect()->back()->with('message', 'Unidad Creada');
    }

    public function addUser()
    {

        $unit_id = request('unit_id');
        $teamrole_id = request('teamrole_id');
        $user_id = request('user_id');

        $rol_id = 0; //declaro la variable

        $teamLeaderRole = Role::where('name', 'teamleader')->first();
        $teamMemberRole = Role::where('name', 'teammember')->first();

        if ($teamrole_id == 1){         //si es teamleader =>id =2

            $rol_id = $teamLeaderRole->id;

        } elseif ($teamrole_id == 2){    //si es teamMember =>id =3


            $rol_id = $teamMemberRole->id;
        }

        $user_has_role = 0;

        if($rol_id == $teamLeaderRole->id ) {

            $user_has_role = DB::table('user_has_roles')//busca si hay en la tabla user_has_roles si el usuario tiene un role (como teamleder,teammember)en la tabla
            ->where('user_id', $user_id)
            ->where('role_id', $teamLeaderRole->id )->count();

        }elseif ($rol_id == $teamMemberRole->id){
            $user_has_role = DB::table('user_has_roles')//busca si hay en la tabla user_has_roles si el usuario tiene un role (como teamleder,teammember)en la tabla
            ->where('user_id', $user_id)
            ->where('role_id', $teamMemberRole->id)->count();

        }

        if ( $user_has_role == 0 && $rol_id != 0){

        //si el usuario no tiene asignado los roles consultados => se le asigna nuevo rol

            DB::table('user_has_roles')->insert(
                [
                    'role_id' => $rol_id,
                    'user_id' => $user_id,
                ]
            );

        }




        //busca si existe en la tabla user_unit existe usuario con el mismo teamrole y unidad

        $exists = DB::table('user_unit')->where('user_id', '=', $user_id)->where('unit_id', '=', $unit_id)->where('teamrole_id', '=', $teamrole_id)->first();

        if ($exists) {          //si existe el usuario en la tabla user_unit con el mismo rol => notifica que está en la unidad

            return redirect()->back()->with('message', 'El usuario ya está registrado en la unidad.');

        } else {  // si no esta en exists guarda en la tabla user_unit el nuevo rol

            $user = User::find($user_id);

            $user = Unit::find($unit_id)->users()->save($user, array('teamrole_id' => $teamrole_id));

            return redirect()->back()->with('message', 'El usuario ha sido registrado.');
        }

    }


    /**
     * Elimina de la tabla user_unit el teamrole_id del user_seleccionado
     */

    public function deleteUser(Request $request)
    {
//        $user = User::where('id', $request->user_id)->first();

        $user_unit =  DB::table('user_unit')->where('id', '=', $request->id_userUnit)->first();


        if (is_countable($user_unit)){

            $row = DB::table('user_unit')->where('id', '=', $request->id_userUnit)->delete();

        }

        $user = User::where('id', $user_unit->user_id)->first();


//        $teamLeaderRole = Role::where('name', 'teamleader')->first();
//        $teamMemberRole = Role::where('name', 'teammember')->first();

        //if not team leader at any Unit remove team leader role

        if ($user->isTeamLeaderAtAnyUnit() == false) {
//            DB::select('user_has_roles')->where('user_id', $userId)->where('role_id', $teamLeaderRole->id)->delete();

            $user->removeRole('teamleader'); //removeRole https://github.com/spatie/laravel-permission
        }

        //if not team member at any Unit remove team member role
        if ($user->isTeamMemberAtAnyUnit() == false) {
            $user->removeRole('teammember');

//            DB::select('user_has_roles')->where('user_id', $userId)->where('role_id', $teamMemberRole->id)->delete();

        }

        return response()->json('{"deleted":' . $request->id_userUnit . '}')->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);


    }


    public function unitUserRoleWalker()
    {

        $units = Unit::all();

        $teamleaders = array();
        $teammembers = array();

        foreach ($units as $index => $unit) {


            foreach ($unit->teamleaders as $tl) {
                array_push($teamleaders, $tl->id);

            }


            foreach ($unit->teammembers as $tm) {
                array_push($teammembers, $tm->id);
                echo '<br/>';
            }


        }


        $teamLeaderRole = Role::where('name', 'teamleader')->first();
        $teamMemberRole = Role::where('name', 'teammember')->first();


        DB::table('user_has_roles')->where('role_id', $teamLeaderRole->id)->delete();
        DB::table('user_has_roles')->where('role_id', $teamMemberRole->id)->delete();


        $uniqueTeamLeaders = array_unique($teamleaders, SORT_REGULAR);
        $uniqueTeamMembers = array_unique($teammembers, SORT_REGULAR);


        foreach ($uniqueTeamLeaders as $u) {
            DB::table('user_has_roles')->insert(
                [
                    'role_id' => $teamLeaderRole->id,
                    'user_id' => $u,
                ]
            );
        }

        foreach ($uniqueTeamMembers as $u) {
            DB::table('user_has_roles')->insert(
                [
                    'role_id' => $teamMemberRole->id,
                    'user_id' => $u,
                ]
            );
        }


    }

    /**
     * @param Request $request
     * @return arreglo de tag pipeline del usuario selecionado
     * Falta devolver los nombres de pipeline en la tabla desde index unit y el boton de desetiquetar

     */
    public function autoTagPipeline(Request $request){



        if (is_countable($request->pipelines)){


            $pipelines = $request->pipelines;

            $arrayPipelinesName =array();

            foreach ($pipelines as $p) {

                if($p != null){

                    $user_autotag = UserAutotag::where('user_id',$request->user_id)
                        ->where('unit_id',$request->unit_id)
                        ->where('pipeline_id',$p)
                        ->where('teamrole_id',$request->teamrole_id)->get();

                    if(count($user_autotag) == 0){

                        $pipeline = Pipeline::find($p);

                        array_push($arrayPipelinesName,[$pipeline->name,$pipeline->id]);


                        UserAutotag::create([
                            'user_id' =>$request->user_id,
                            'unit_id' =>$request->unit_id,
                            'pipeline_id' =>$p,
                            'teamrole_id' =>$request->teamrole_id,
                        ]);

                    }
                }
            }

        }

        return $arrayPipelinesName;
    }
/**
 *
 *  */
    public  function unTagPipeline(Request $request){


        if($request->id_pipeline){

            $id_userAutotag = UserAutotag::select('id')->where('user_id',$request->user_id)
                ->where('unit_id',$request->unit_id)
                ->where('pipeline_id', (int)($request->id_pipeline))
                ->where('teamrole_id',$request->teamrole_id)->first()->id;

            $userAutotag= UserAutotag::destroy($id_userAutotag);

        }
        return $request->id_pipeline;
    }


    /**
     * @param recibe por parametro datos requeridos para cambiar de perfile
     * @return array de perfiles tag
     */

    public function addProfile(Request $request)
    {

//        dd($request->all());
        if ($request->all()) {
            $arrayProfiles = array();


               if (is_countable($request->ids_profile)){

                $profiles = $request->ids_profile;


                foreach ($profiles as $p) {

                    if ($p != null) {

                        $id_autotag = UserAutotag::where('user_id', $request->user_id)
                            ->where('unit_id', $request->unit_id)
                            ->where('profile_id', (int)$p)
                            ->where('teamrole_id', $request->teamrole_id)->first();


                        if (count($id_autotag) == 0) {

                            $profile = Profile::find($p);

                            array_push($arrayProfiles, [Utils::cutText($profile->area, 20), $profile->area, $p]);

                            $autotag = new UserAutotag();
                            $autotag->user_id = $request->user_id;
                            $autotag->unit_id = $request->unit_id;
                            $autotag->profile_id = $p;
                            $autotag->teamrole_id = $request->teamrole_id;
                            $autotag->save();

                        }
                    }
                }
            }

            return $arrayProfiles;
        }
    }


    /**
     * @param Request $request recibe  datos requeridos para eliminar tag de perfil
     * @return id de perfil eliminado
     */
    public  function unTagProfile(Request $request){

        if($request->id_profile){

            $id_userAutotag = UserAutotag::select('id')->where('user_id',$request->user_id)
                ->where('unit_id',$request->unit_id)
                ->where('profile_id', (int)($request->id_profile))
                ->where('teamrole_id',$request->teamrole_id)->first()->id;

            $userAutotag= UserAutotag::destroy($id_userAutotag);

        }
        return $request->id_profile;
    }


}
