<?php

class PurchaseItems {

    /*************************************************
    / Get FIFO Items for an Ingredient
    *************************************************/
    public static function GetFIFOItems($ingredient_id, $required_qty) {
        global $db;
        $query = "SELECT * FROM ".TABLE_PURCHASE_ITEM." WHERE ingredient_id = '$ingredient_id' AND remaining_qty > 0 ORDER BY purchase_date ASC";
        $rows = $db->fetch_all_array($query);
        
        $fifoItems = [];
        $totalFetchedQty = 0;
        foreach ($rows as $row) {
            $fifoItems[] = $row;
            $totalFetchedQty += $row['remaining_qty'];
            if ($totalFetchedQty >= $required_qty) {
                break;
            }
        }
        
        return $fifoItems;
    }

    /*************************************************
    / Update Remaining Quantity in Purchase Item
    *************************************************/
    public static function UpdateRemainingQty($item_id, $used_qty) {
        global $db;
        $query = "UPDATE ".TABLE_PURCHASE_ITEM." SET remaining_qty = remaining_qty - '$used_qty' WHERE id = '$item_id'";
        $db->query($query);
    }

}

?>
