PHP - 从上个月的结束库存中获取初始库存

I have an orders table and inventory table. I need a function to get the beginning inventory of last month.

This is the formula.

beginning inventory = ending inventory

ending inventory = beginning inventory + deliveries - usage.

To get the ending inventory of last month, I need to get the beginning inventory of last last month but I don't know how to do that.

I am just thinking on how to do it.

    <?php
     function get_beginning_inventory($month_date)
     {
       //do the formula here or the code here
       return $data;
     }
    ?>

Can someone help me please?