<?php

namespace App\Http\Controllers\Api;

use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class AuthController extends Controller
{
    public function login(Request $request){
        $credentials = $request->only('username', 'password');
        //dd($credentials);
        $type  = $request -> input('type');
        $branch  = $request -> input('branch');

        try{
            if (! $token = JWTAuth::attempt($credentials))
                return response()->json(['error' => 'invalid_credentials'], 401);
        }catch (JWTException $e){
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        $context = JWTAuth::setToken($token);
        $usr = $context->authenticate();


   
          
        $permissionAdminFlag = false;
        $permissionAgentFlag = false;

        $roles = $usr -> roles() -> get();
        foreach($roles as $role){
            $permissios = $role ->  permissions() -> where('name','use-api-as-agent') -> get();
            if(! $permissios -> isEmpty())
                $permissionAgentFlag = true;
            $permissios = $role ->  permissions() -> where('name','use-api-as-admin') -> get();
            if(! $permissios -> isEmpty())
                $permissionAdminFlag = true;
        }
        if($permissionAdminFlag){
            if(strcmp($type,'admin')!=0){
                return response()->json(['error' => 'invalid_credentials'], 401);
            } else{
                return response()->json(compact('token'))->setCallback(Input::get('callback'));
            }
        }else if($permissionAgentFlag){
            if(strcmp($type,'agent')!=0){
                return response()->json(['error' => 'invalid_credentials'], 401);
            } else{

             if($branch!=$usr -> sucursal_id)
                return response()->json(['error' => 'invalid_credentials'], 411);
                $resp = array('token' => $token, 'procedureId' => $usr -> tramites()  ->  lists('id'));
                return response()->json($resp);
            }

        }else{
            return response()->json(['error' => 'invalid_credentials'], 401);
        }

    }

    public function logout(Request $request){
        $this->validate($request, [
            'token' => 'required'
        ]);

        JWTAuth::invalidate($request->input('token'));
    }
}
