<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User\UserModel;

class Login
{

    public function handle(Request $request, Closure $next)
    {
        // Get List Roles -> Example roleowner:1,3,5 will get result [1, 3, 5]
        $roles = array_slice(func_get_args(), 2);
        // Loop roles
        foreach ($roles as $role) {

            $users = UserModel::where('id', session()->get('users_id'))->first();
            if ((Hash::check('bkpeduli', $users->password)) || (Hash::check('bk-peduli', $users->password))) {
                return redirect()->route('password.change')->with('gagal', 'Silakan ganti password Anda terlebih dahulu.');
            }

            // Set current session with existing role_id
            $user = session()->get('role');

            // Check user and role
            if ($user == $role) {
                return $next($request);
            }
        }

        // Checking session status was active will be redirected to the dashboard
        if (session()->get('status') == 1) {
            return redirect('/dashboard');
        }
        return redirect('/login')->with('error', 'Mohon Login Terlebih Dahulu');
    }
}
