<?php
class Stock {

    // add one stock row (seeded from purchase_item)
    public static function AddStock($data) {
        global $db;
        return $db->query_insert(TABLE_STOCK, $data);
    }

    // generic update (for future adjustments/restores)
    public static function UpdateStock($id, $data) {
        global $db;
        return $db->query_update(TABLE_STOCK, $data, "id='$id'");
    }

    // simple getters (front-end will order for FIFO)
    public static function GetStockById($id) {
        global $db;
        $q = "SELECT * FROM ".TABLE_STOCK." WHERE id='$id'";
        $row = $db->query_first($q);
        return ($db->affected_rows > 0) ? $row : false;
    }

    public static function GetStockList($filter = "", $pageno = "null", $pagesize = "null") {
        global $db;
        $q = "SELECT * FROM ".TABLE_STOCK." ".$filter." ORDER BY datetime ASC, id ASC";
        $rows = $db->fetch_all_array($q, $pageno, $pagesize);
        return ($db->affected_rows > 0) ? $rows : false;
    }
  
 /**********************************************************
/ This function will return StockSetup totals per product
/ Only products with stock (total_qty > 0) are shown
**********************************************************/
public static function GetStockSetupList($filter = "", $pageno = "null", $pagesize = "null") {
    global $db;

    $query = "
        SELECT 
            s.product_id,
            SUM(s.remaining_qty) AS total_qty,
            SUM(s.remaining_qty * s.unit_cost) AS total_cost
        FROM " . TABLE_STOCK . " s
        $filter
        GROUP BY s.product_id
        HAVING total_qty > 0
    ";

    //print($query);exit;
    $rows = $db->fetch_all_array($query, $pageno, $pagesize);

    if ($db->affected_rows > 0) {
        return $rows;
    } else {
        return false;
    }
}//StockSetup


}
