<?php

namespace App\Http\Controllers\Api;

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

use App\Danoral\Entidades\EUser;
use App\Danoral\Entidades\Entidad;
use App\Danoral\Entidades\EntidadUserView;
use App\Http\Resources\User as UserResources;


class AuthController extends Controller
{
    public static $TYPE_LOGIN_NULL = 0;
    public static $TYPE_LOGIN_CODCLIENTE = 1;
    public static $TYPE_LOGIN_EMAIL = 2;
    public static $TYPE_LOGIN_USERNAME = 3;
    public static $TYPE_LOGIN_IDUSER = 4;
    public static $TYPE_LOGIN_ERROR = 99;

    public function getUserSession() {
        if(auth()->user()){

            return response()->json(new UserResources(auth()->user()),200);

        }else{
            return response()->json([
                'message'   =>'No hay usuario activo',
            ], 401);
        }
    }

    public function login(Request $request) {

        $vData = $request->validate([
            'username'      =>'required',
            'password'      =>'',
            'idUser'        =>'',
        ]);

        $username = $vData['username']; // username | email | codCliente
        $password = isset($vData['password'])?$vData['password']:null;
        $idUser   = isset($vData['idUser'])?$vData['idUser']:null;
    
        $typeLogin = self::$TYPE_LOGIN_NULL;
        $entidad = null;

        if($idUser){
            $typeLogin = self::$TYPE_LOGIN_IDUSER;
            $user = EntidadUserView::firstWhere([
                ['idE', $idUser],
            ]);

            if($user) { 
                if(is_null($user->password)){
                    $user->password = Hash::make($password);
                    $user->save();
                }

                if( !Hash::check($password, $user->password)) {

                    return response()->json([
                        'typeLogin' => self::$TYPE_LOGIN_ERROR,
                        'message'   =>'Identificación no validida',
                    ],401);
                }
            }else{
                return response()->json([
                    'typeLogin' => self::$TYPE_LOGIN_ERROR,
                    'message'   =>'Usuario id no encontrado',
                ],401);
            }
        }else{

            if(is_numeric($username) && strlen($username)==6){
                $typeLogin = self::$TYPE_LOGIN_CODCLIENTE;
                $user = EntidadUserView::firstWhere([
                    ['codCliente', $username],
                ]);
                if(!$user){
                    return response()->json([
                        'typeLogin' => self::$TYPE_LOGIN_ERROR,
                        'message'   =>'No se encontro el codigo cliente'
                    ],401);
                }


            }else if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
                $typeLogin = self::$TYPE_LOGIN_EMAIL;
                $user = EntidadUserView::firstWhere([
                    ['email', $username],
                ]);
                if (!$user) { 
                    return response()->json([
                        'typeLogin' => self::$TYPE_LOGIN_ERROR,
                        'message'   =>'Usuario no existe (email)',
                    ],401);
                }                

            }else{
                $typeLogin = self::$TYPE_LOGIN_USERNAME;
                $user = EntidadUserView::firstWhere([
                    ['username', $username],
                ]);
                if(!$user){ 
                    return response()->json([
                        'typeLogin' => self::$TYPE_LOGIN_ERROR,
                        'message'   =>'Usuario no existe',
                    ],401);
                }
            }
        }

        switch($typeLogin) {
            case self::$TYPE_LOGIN_USERNAME:
            case self::$TYPE_LOGIN_EMAIL:

                return response()->json([
                    'typeLogin' => $typeLogin,
                    'id'        => strval($user->idE),
                ],200);

            case self::$TYPE_LOGIN_CODCLIENTE:
            case self::$TYPE_LOGIN_IDUSER:

                $token = $user->createToken('EntidadToken')->plainTextToken;

                return response()->json([
                    'typeLogin' => $typeLogin,
                    'id'        => strval($user->idE),
                    'token'     => $token,
                ],200);

        }
    }

    public function registerEntidadUser(Request $request){

        $vData = $request->validate([
            'idE'           =>'required',
            'email'         =>'required|email|unique:pgsql.admin.entidades_users',
            'username'      =>'required|unique:pgsql.admin.entidades_users',
            'password'      =>'',
            'idU'           =>'',
            'nameE'         =>'',
        ]);

        if(isset($vData['password'])) {
            $vData['password'] = Hash::make($vData['password']);
        }

        DB::beginTransaction();
        try{ 

            $entidad = Entidad::find($vData['idE']);
            if(!$entidad){
                $entidad = new Entidad;
                $entidad->idE       = $vData['idE'];
                $entidad->typeE     = 4;
                $entidad->enableE   = true;
                $entidad->idESuper  = null;
                $entidad->datose    = json_encode([
                    'name'  => [
                        'type'  => 1100,
                        'value' => $vData['nameE'],
                    ]
                ], JSON_UNESCAPED_UNICODE);
                $entidad->save();
            }

            $user = EUser::create($vData);

            DB::commit();

            return response()->json($user, 200);

        }catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'message'   => 'ERROR: '. $e->getMessage(),
            ], 200);
        }            
    }

    public function logout() {
        auth()->user()->tokens()->delete();

        return response()->json([
            'message'   => 'logout ok',
        ], 200);

    }

    public function loginx(Request $request){
        
        $credentials = $request->validate([
            'email'=>'required|email',
            //'username'=>'required',
            'password'=>'required'
        ]);

        if (!auth()->attempt($credentials)) {
            return response(['mensage'=>'Invalid credentials']);
        }

        $token = auth()->user()->createToken('AuthToken');
        // $tokenE = Auth::guard('danoral')->user()->createToken('EntidadToken');

        // $tokenE = auth()->entidad()->createToken('EntidadToken');

        return response([
            'user'      => auth()->user(),
            'token'     => $token,
            //'tokenE'    => $tokenE,

        ]);


    }

}
