<?php

namespace Hilco\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

/**
 * M3 inventory balances table
 * NOTE: MITBAL is the original name of the table before Hilco changed the filename to Inventory.txt. $table is changed
 * to reflect this but the class name is left as MITBAL to keep it distinguished from other similarly named classes and
 * tables like InventoryItems. It's also technically the short-name of the same data object storage in M3.
 * @property-read string $Available
 */
class MITBAL extends Model {
    protected $table = "Inventory";

    /**
     * @return int
     */
    public function getNetAvailableQuantity(): int {
        return intval($this->Available);
    }

    /**
     * @param $inventoryConnection
     * @param string $warehouseCode
     * @param string $itemNumber
     * @param array $select
     * @return Builder|Model<MITBAL>|object|null
     */
    public static function findBalanceRecord ($inventoryConnection, string $warehouseCode, string $itemNumber, array $select = []) {
        $query = MITBAL::on($inventoryConnection);
        if (!empty($select)) {
            $query = $query->select($select);
        }

        return $query->where("ITNO", $itemNumber)->where("WHLO", $warehouseCode)->first();
    }

    /**
     * @param $inventoryConnection
     * @param string $itemNumber
     * @param array $select
     * @return Builder[]|Collection<MITBAL>
     */
    public static function findBalanceRecordsForItem ($inventoryConnection, string $itemNumber, array $select = []) {
        $query = MITBAL::on($inventoryConnection);
        if (!empty($select)) {
            $query = $query->select($select);
        }

        return $query->where("ITNO", $itemNumber)->get();
    }

    /**
     * @param $inventoryConnection
     * @param string $warehouseCode
     * @param array $itemNumbers
     * @param array $select
     * @return Builder[]|Collection<MITBAL>
     */
    public static function findBalanceRecordsByWarehouse ($inventoryConnection, string $warehouseCode, array $itemNumbers, array $select = []) {
        $query = MITBAL::on($inventoryConnection);
        if (!empty($select)) {
            $query = $query->select($select);
        }

        return $query->where("WHLO", $warehouseCode)->whereIn("ITNO", $itemNumbers)->get();
    }
}