<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckUserPermission
{
    /**
     * Map security access matrices per dynamic actor group
     */
    protected $permissions = [
        'Super Admin' => [
            'cashbook.create', 'cashbook.update', 'cashbook.delete',
            'transactions.approve', 'reports.read', 'settings.update', 'auditLogs.read'
        ],
        'Company Admin' => [
            'cashbook.create', 'cashbook.update',
            'transactions.approve', 'reports.read', 'settings.update'
        ],
        'Cashier' => [
            'cashbook.create', 'cashbook.update'
        ],
        'Accountant' => [
            'cashbook.create', 'cashbook.update', 'reports.read'
        ],
        'Auditor' => [
            'transactions.approve', 'reports.read', 'auditLogs.read'
        ],
    ];

    /**
     * Handle incoming web/API request authorizations
     */
    public function handle(Request $request, Closure $next, string $permission)
    {
        $user = Auth::user();

        if (!$user || !$user->is_active) {
            Auth::logout();
            return redirect()->route('login')->with('error', 'আপনার একাউন্টটি সাময়িকভাবে বন্ধ আছে।');
        }

        $userRole = $user->role;
        $allowedPermissions = $this->permissions[$userRole] ?? [];

        if (!in_array($permission, $allowedPermissions)) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Unauthorized action access denied.'], 403);
            }
            return redirect()->route('dashboard')->with('error', 'এই অ্যাকশনটি সম্পন্ন করার অনুমতি আপনার নেই।');
        }

        return $next($request);
    }
}
