<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Api\Auth\AuthController;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;

class WebAuthenticate
{
    public function handle(Request $request, Closure $next, ...$roles)
    {
        $token = $request->cookie('_absensiku_karyawan_token');

        if (!$token) {
            Cookie::queue(Cookie::forget('_absensiku_karyawan_token'));
            return redirect(route('auth.login'))->with('error', 'Sesi telah berakhir. Silahkan login kembali.');
        }

        $user = app(AuthController::class)->getUserByToken($token)->getData()->data;

        if (!$user) {
            Cookie::queue(Cookie::forget('_absensiku_karyawan_token'));
            return redirect(route('auth.login'))->with('error', 'Sesi telah berakhir. Silahkan login kembali.');
        }

        $validRole = false;
        foreach($roles as $role) {
            if($user->role === $role) {
                $validRole = true;
            }
        }

        if (!$validRole) {
            Cookie::queue(Cookie::forget('_absensiku_karyawan_token'));
            return redirect(route('auth.login'))->with('error', 'Anda tidak memiliki hak akses.');
        }

        view()->share('user', $user);

        return $next($request);
    }
}
