<?php
/**
 * Role-Based Access Control Middleware
 * Checks if the authenticated user has permission for the requested action.
 */

class RBACMiddleware {

    /**
     * Check if user has permission for given module + action.
     * Admin role bypasses all checks.
     * 
     * @param PDO $db
     * @param object $user Authenticated user object
     * @param string $module e.g., 'purchase', 'sale', 'setup', 'users'
     * @param string $action e.g., 'view', 'create', 'edit', 'delete', 'print'
     * @throws Exception if not authorized
     */
    public static function check(PDO $db, object $user, string $module, string $action): void {
        // Admin bypasses all permission checks
        if ($user->role === 'admin') {
            return;
        }

        $column = 'can_' . $action;
        $validColumns = ['can_view', 'can_create', 'can_edit', 'can_delete', 'can_print'];

        if (!in_array($column, $validColumns)) {
            Response::error("Invalid permission action: {$action}", 400);
        }

        $stmt = $db->prepare("
            SELECT {$column} as allowed 
            FROM permissions 
            WHERE user_id = ? AND module = ?
        ");
        $stmt->execute([$user->id, $module]);
        $perm = $stmt->fetch();

        if (!$perm || !$perm['allowed']) {
            Response::forbidden("معذرت، آپ کو '{$module}' کے '{$action}' عمل کی اجازت نہیں ہے۔");
        }
    }
}
