<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

use App\Dashboard;
use App\User;
use Carbon\Carbon;

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 login()
    {
    //   return view('auth.login');
      return view('auth.v2.login');
    }

    public function authenticate(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);

        $credentials = $request->only('email', 'password');

        if (Auth::guard('web')->attempt($credentials)) {

            $auth_user = Auth::guard('web')->user();
            $api_url = config('api.url');
            if($auth_user['roles'] == 'teller'){
                if($auth_user['role_harian'] == 'teller'){
                    $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
                    // return view('homepage.'.$auth_user['role_harian'].'.home',compact('cawangan_info','api_url'));
                    return redirect()->route('home');
                }elseif($auth_user['role_harian'] == 'penilai' || $auth_user['role_harian'] == 'penilai2'){
                    $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
                    $gadaian_semasa = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadaiansemasa/'. $auth_user['cawangan'])->json();
                    $gadaian_belumserah = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/gadaiansemasa/belum_serah/'. $auth_user['cawangan'])->json();
                    // return view('homepage.'.$auth_user['role_harian'].'.home',compact('cawangan_info','gadaian_semasa','gadaian_belumserah','api_url'));
                    return redirect()->route('home');
                }else{
                    return view('not_assign');
                }
            }
            elseif($auth_user['roles'] == 'pc' || $auth_user['roles'] == 'ppc'){
                $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
                // return view('homepage.khazanah.home',compact('cawangan_info','api_url'));
                return redirect()->route('home');
            }
            else{
                $cawangan_info = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/cawangan/'. $auth_user['cawangan'])->json();
                // return view('homepage.'.$auth_user['roles'].'.home',compact('cawangan_info','api_url'));
                return redirect()->route('home');
            }
        }

        return redirect('login')->with('error', 'Oppes! You have entered invalid credentials')->withInput();
    }

    public function loginDashboard(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);

        $credentials = $request->only('email', 'password');

        if (Auth::guard('dashboard')->attempt($credentials,true)) {
            $auth_user = Auth::guard('dashboard')->user();

            $user_login['nama'] = $auth_user['name'];
            $user_login['email'] = $auth_user['email'];
            $user_login['password'] = $auth_user['password'];
            $user_login['icno'] = $auth_user['no_kp'];
            $user_login['apitoken'] = $auth_user['remember_token'];
            return response()->json([
                'success' => true,
                'user' => $user_login
            ]);
        } else {
       //if authentication is unsuccessfull, notice how I return json parameters
            return response()->json([
                'success' => false,
                'message' => 'Invalid Email or Password',
            ], 200);
        }
    }

    public function logoutDashboard(Request $res)
    {
        $login_detail = Dashboard::where([['no_kp','=',$res->nokp],['remember_token','=',$res->header('Authorization')]])->first();
        // dd($login_detail);
        if ($login_detail) {
            // dd($login_detail);
            $logout_user = Dashboard::where([['no_kp','=',$res->nokp],['remember_token','=',$res->header('Authorization')]])->update(array(
                'remember_token' => null
            ));
            // dd($logout_user);
            return response()->json([
            'success' => true,
            'message' => 'Logout successfully'
        ]);
        }else {
            return response()->json([
            'success' => false,
            'message' => 'Unable to Logout'
            ]);
        }
    }

    public function logout(){
        $current = Carbon::now();
        $current = new Carbon();
        $current = $current->toDateString();
        $auth_user = Auth::guard('web')->user();
        Auth::logout();
        Session::flush();
        $session = Http::withOptions(['verify' => config('app.api_verify')])->post(config('api.url') . '/api/logoutsession/' . $auth_user['cawangan'], [
            'id' => $auth_user['id'],
            'nama' => $auth_user['name'],
            'nokp' => $auth_user['no_kp'],
            'email' => $auth_user['email'],
            'taraf' => $auth_user['role_harian'],
            'tarikh' => $current,
            

        ]);

        return Redirect::to('/');
    }

    public function GetRolesHarian(Request $request, $kodcaw){

        if($request->role_harian == 'teller'){
            $kakitangan = User::where([['role_harian','teller'],['cawangan',$kodcaw]])->get();
        }else if($request->role_harian == 'khazanah'){
            $kakitangan = User::where([['role_harian','khazanah'],['cawangan',$kodcaw]])->get();
        }else if($request->role_harian == 'pc'){
            $kakitangan = User::where([['role_harian','pc'],['cawangan',$kodcaw]])->get();
        }else if($request->role_harian == 'penilai'){
            $kakitangan = User::where([['role_harian','penilai'],['cawangan',$kodcaw]])->get();
        }else if($request->role_harian == 'ppc'){
            $kakitangan = User::where([['role_harian','ppc'],['cawangan',$kodcaw]])->get();
        }else{
            $kakitangan = User::all();
        }

        return response()->json($kakitangan,200);
    }
}
