Something is wrong with my texture mapping code

Hi! I've been working on a 3D game for a week for now, and I'm currently working on making a texture mapping function so I can make buildings not just a white polygon, sadly something is not coming together well, and so far it seems like the math is wrong somewhere, but for the life of me I couldn't figure it out.

function draw_mapped(img, x1, y1, x2, y2, x3, y3, x4, y4)
    if not img or type(img) ~= "userdata" then
        print("Invalid image")
        return
    end

    local width, height = img:getSize()

    local min_x = math.min(x1, x2, x3, x4)
    local max_x = math.max(x1, x2, x3, x4)
    local min_y = math.min(y1, y2, y3, y4)
    local max_y = math.max(y1, y2, y3, y4)

    local target_width = max_x - min_x
    local target_height = max_y - min_y

    -- don't you dare to divide by zero
    target_width = math.max(target_width, 1)
    target_height = math.max(target_height, 1)

    -- simplified affine transformation
    local dx1 = x2 - x1
    local dy1 = y2 - y1
    local dx2 = x4 - x1
    local dy2 = y4 - y1

    local scaleX = target_width / width
    local scaleY = target_height / height

    local rotation_x = dx1 / width
    local rotation_y = dy1 / width
    local rotation_u = dx2 / height
    local rotation_v = dy2 / height

    img:drawSampled(
        min_x, min_y,           -- target x, y
        target_width, target_height,  -- target width, height
        0.5, 0.5,               -- center x, y (normalized)
        rotation_x, rotation_u, -- dxx, dyx
        rotation_y, rotation_v, -- dxy, dyy
        x1, y1,                 -- dx, dy (translation)
        1,                      -- z
        0,                      -- tilt angle
        false                   -- tile
    )
end

I came here with hopes that someone smarter might now a fix to this. If yes, thanks so much, if no, I don't blame you, this is hard.