<?php

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

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

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

        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'));
    }
}
