<?php

namespace App\Http\Middleware;

use Closure;

/**
 * Role 3 = Jawatankuasa Kehadiran: only counter/kehadiran-related APIs.
 * Other roles pass through unchanged.
 */
class AttendanceCommitteeRoleMiddleware
{
    public function handle($request, Closure $next)
    {
        $user = $request->user();
        if (!$user || (int) $user->role !== 3) {
            return $next($request);
        }

        if ($this->attendanceCommitteeMayAccess($request)) {
            return $next($request);
        }

        return response()->json([
            'status' => 'failed',
            'message' => 'Akses ditolak. Akaun ini hanya untuk halaman kehadiran.',
        ], 403);
    }

    /**
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    private function attendanceCommitteeMayAccess($request)
    {
        if ($request->isMethod('get') && $request->is('api/v1/admin/information')) {
            return true;
        }
        if ($request->isMethod('get') && $request->is('api/v1/admin/logout')) {
            return true;
        }
        if ($request->isMethod('post') && $request->is('api/v1/admin/impersonate/leave')) {
            return true;
        }
        if ($request->isMethod('get') && $request->is('api/v1/voter')) {
            return true;
        }
        if ($request->isMethod('post') && $request->is('api/v1/voter/*/verify-fizikal-registration')) {
            return true;
        }
        if ($request->is('api/v1/allowance/*')) {
            return true;
        }

        return false;
    }
}
