Help with making object flush with border with any rotation

Hi, I’m trying to make a placement system, but I stumbled across the problem where I can’t make my object flush with the border if it has a different rotation other than 0,0,0. I did manage to get it working so that the object goes up to the border with one rotated axis only, but I can’t figure out how to do the rest. Anyone have any ideas?

https://gyazo.com/9072e724796fdcfb5205ac387f86f8cd Gyazo shows that it goes up to the border on the Z axis, but not on the X.

function Placement:CalculateCanvas(Model, mouse, orientation)

    local surfaceCFrame = self.CanvasPart.CFrame * CFrame.new(0, self.CanvasPart.Size.Y/2, 0)

    local relativeMouse = surfaceCFrame:PointToObjectSpace(mouse.Hit.p)

    local modelSize = CFrame.fromEulerAnglesYXZ(0,0,orientation) * Model.PrimaryPart.Size
    modelSize = Vector3.new(math.abs(modelSize.x),math.abs(modelSize.y),math.abs(modelSize.Z))
    local half = (self.CanvasPart.Size - modelSize)/2


    local x = math.clamp(relativeMouse.X, -half.X, half.X)
    local z = math.clamp(relativeMouse.Z, -half.Z, half.Z)
    if self.GridUnit > 0 then 

        x = math.sign(x)*(math.abs(x) - (math.abs(x) % self.GridUnit) + (half.x % self.GridUnit))
        z = math.sign(z)*(math.abs(z) - (math.abs(z) % self.GridUnit) + (half.z % self.GridUnit))

    end

    local modelcf = surfaceCFrame * CFrame.new(x,Model.PrimaryPart.Size.Y/2,z) * CFrame.Angles(0,0,math.pi/2)

    return modelcf
end