<?php

declare(strict_types=1);

function log_permission_change(
    PDO $pdo,
    int $user_id,
    string $role_key,
    string $module_key,
    array $old,
    array $new
): void {

    try {

        $stmt = $pdo->prepare("
            INSERT INTO permission_audit_logs
            (
                changed_by_user_id,
                role_key,
                module_key,
                old_view,
                old_create,
                old_edit,
                old_delete,
                new_view,
                new_create,
                new_edit,
                new_delete,
                ip_address
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $user_id,
            $role_key,
            $module_key,
            $old['can_view'] ?? 0,
            $old['can_create'] ?? 0,
            $old['can_edit'] ?? 0,
            $old['can_delete'] ?? 0,
            $new['view'] ?? 0,
            $new['create'] ?? 0,
            $new['edit'] ?? 0,
            $new['delete'] ?? 0,
            $_SERVER['REMOTE_ADDR'] ?? null
        ]);

    } catch (Throwable $e) {
        // Fail silently — do not block permission update
    }
}