<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use Auth;
use Ixudra\Curl\Facades\Curl;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function logout() {
        session()->forget('token');
        session()->forget('nama');
        session()->forget('foto');
        session()->forget('sEmpID');
        session()->forget('sDeptID');
        session()->forget('password');
        Auth::guard('web')->logout();
        return redirect()->route('login');
    }

    public function login(Request $request)
    {
        $response = Curl::to(api_url('presensi/auth/login'))
        ->withData([
            'permission' => 'login',
            'username' => $request->username,
            'password' => $request->password
        ])->asJson()->post();

        if (!empty($response->status_code)) {
            if ($response->status_code == 200) {
                $request->session()->put('token',$response->login->data->api_token);
                $request->session()->put('nama',$response->login->data->sFisrtName);
                $request->session()->put('foto',$response->login->data->foto);
                $request->session()->put('sEmpID',$response->login->data->sEmpID);
                $request->session()->put('sDeptID',$response->login->data->sDeptID);
                $request->session()->put('password',$response->login->data->Pwd);
                return redirect()->route('dashboard');
            } else {
                return back()->with('msg',['type'=>'danger','text'=>$response->message])->withInput();
            }
        } else {
            return back()->with('msg',['type'=>'danger','text'=> 'Terjadi Kesalahan Pada Server'])->withInput();
        }
    }
}
