<?php

namespace App\Http\Controllers\API\Sales\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\API\Stock\LoginRequest;
use App\User;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class IndexController extends Controller
{
    public function login(LoginRequest $request)
    {
        if (!filter_var($request->user, FILTER_VALIDATE_EMAIL)) {
            $expIdEmploye = explode('-', $request->user);
            if ($expIdEmploye[0] !== 'SS') {
                return response('Maaf akun anda tidak terdaftar', 421);
            }
            $user = User::where('id_employee', $request->user)->first();
            if (!$user) {
                return response('Invalid Credentials', 400);
            }
            $credentials = [
                'email' => $user->email,
                'password' => $request->password
            ];
        } else {
            $user = User::where('email', $request->user)->first();
            $expIdEmploye = explode('-', $user->id_employee);
            if ($expIdEmploye[0] !== 'SS') {
                return response('Maaf akun anda tidak terdaftar', 421);
            }
            $credentials = [
                'email' => $request->user,
                'password' => $request->password
            ];
        }

        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json('Invalid Credentials', 400);
            }
        } catch (JWTException $e) {
            return response()->json('Invalid Credentials', 500);
        }

        return response()->json(compact('token'));
    }
}
