<?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.
 * @property-read string $REQT
 * @property-read string $STQT
 */
class MITBAL extends Model {
    protected $table = "Inventory";

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

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

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

    /**
     * @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();
    }
}