<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    public function handle(Request $request, Closure $next, string $permission): Response
    {
        if (!auth()->check()) {
            return redirect()->route('login');
        }

        $user = auth()->user();
        $hasPermission = false;

        switch ($permission) {
            case 'manage_employees':
                $hasPermission = $user->canManageEmployees();
                break;
            case 'manage_access':
                $hasPermission = $user->canManageAccess();
                break;
            case 'approve_extension':
                $hasPermission = $user->canApproveExtension();
                break;
            case 'view_reports':
                $hasPermission = in_array($user->role, ['super_admin', 'admin_hr', 'manager']);
                break;
            case 'system_admin':
                $hasPermission = $user->isSuperAdmin();
                break;
            default:
                $hasPermission = false;
        }

        if (!$hasPermission) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Forbidden. Permission required: ' . $permission
                ], 403);
            }

            return redirect()->route('dashboard')->with('error', 'Anda tidak memiliki izin untuk melakukan aksi ini.');
        }

        return $next($request);
    }
}