<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;

class UsuariosController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function ReadUsuarios()
    {

        $Usuarios = User::orderBy('name', 'asc')->get();

        foreach ($Usuarios as $u) {
            $u->password1 = "";
            $u->areas = $u->Areas;
            $u->activo = ($u->activo == 1 ? true : false);
        }

        return (new Response($Usuarios, 200));

    }

    public function ReadUsuariosActivos()
    {

        $Usuarios = User::where('activo', '1')
            ->orderBy('name', 'asc')->get();

        foreach ($Usuarios as $u) {
            $u->password1 = "";
            $u->areas = $u->Areas;
            $u->activo = ($u->activo == 1 ? true : false);
        }

        return (new Response($Usuarios, 200));

    }

    public function CreateUsuarios(Request $request)
    {

        $datos = json_decode($request->datos);

        $pr = new User();

        $pr->name = $datos[0]->name;
        $pr->email = $datos[0]->email;
        $pr->password = Hash::make($datos[0]->password1);
        $pr->id_perfil = $datos[0]->id_perfil;
        $pr->activo = $datos[0]->activo;
        $pr->api_token = "";

        $pr->save();

        if ($pr->id_perfil != 1 && $pr->id_perfil != 3) {
            foreach ($datos[0]->areas as $a) {
                $pr->Areas()->attach($a->id);
            }

            $pr->areas = $pr->Areas;

        }

        return (new Response($pr, 200));

    }

    public function UpdateUsuarios(Request $request)
    {

        $datos = json_decode($request->datos);

            $pr = User::find($datos[0]->id);
            $pr->name = $datos[0]->name;
            $pr->email = $datos[0]->email;
            $pr->password = Hash::make($datos[0]->password1);
            $pr->id_perfil = $datos[0]->id_perfil;
            $pr->activo = $datos[0]->activo;

            $pr->save();

            $acs = $pr->areas;

            foreach ($acs as $a) {
                $pr->Areas()->detach($a->id);
            }

            if ($pr->perfil != 1 && $pr->perfil != 3) {
                foreach ($datos[0]->areas as $a) {
                    $pr->Areas()->attach($a->id);
                }
            }

            $pr->areas = $pr->Areas;

            return (new Response($pr, 200));

        

    }
}
