<?php

namespace App\Api\V1\Controllers;

use App\Models\User;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tymon\JWTAuth\JWTAuth;
use App\Http\Controllers\Controller;
use App\Api\V1\Requests\LoginRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Auth;
use Illuminate\Http\Request;

use Dingo\Api\Routing\Helpers;

class LoginController extends Controller
{
    use Helpers;
    
    /**
     * Log the user in
     *
     * @param LoginRequest $request
     * @param JWTAuth $JWTAuth
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $request->only(['email', 'password']);


       // $user->password = 'clave123';


       /* $user = new User([
            'name' => 'Alex',
            'email' => 'alex101616@email.com',
            'password' => 'clave123',
            'first_name' => 'alex',
            'last_name' => 'leiva',
            'user_type_id' => '4'
        ]);

        $user->save(); */


        try {
            $token = Auth::guard()->attempt($credentials);

            if(!$token) {
                throw new AccessDeniedHttpException();
            }

            $user = Auth::user();

            // valida solo choferes y apoderados
            /*$allowedUserTypes = [1,2];
            if (!in_array($user->user_type_id, $allowedUserTypes)) {
                return response()->json([
                    'message' => '403 Forbidden',
                    'status_code' => 403
                ], 403);
            }*/
        

        } catch (JWTException $e) {
            throw new HttpException(500);
        }

        $userId = Auth::id();
        return response()
            ->json([
                'status' => 'ok',
                "id" => $userId,
                'token' => $token,
                'expires_in' => Auth::guard()->factory()->getTTL() * 60
            ]);
    }
} 