<?php

namespace Hilco\Models;

use DB;
use Illuminate\Database\Eloquent\Model;

/**
 * M3 price lists table with quantity breaks
 * @property-read string $PRRF
 * @property-read string $SAPR
 * @property-read string $NTCD
 */
class OPRICL extends Model {
    protected $table = "OPRICL";
    protected $connection = "hilco-pricelist";

    /**
     * @return mixed
     */
    public function getPriceList() {
        return $this->PRRF;
    }

    /**
     * @return string
     */
    public function getSalePrice() {
        return $this->SAPR;
    }

    /**
     * @return string
     */
    public function getNetCode() {
        return $this->NTCD;
    }

    /**
     * @return bool
     */
    public function isContractPrice() {
        return $this->getNetCode() == "1";
    }

    /**
     * @param $priceListDesc , e.g. "US_CATALOG" (CustomerSegments.def_pricelist_desc)
     * @param $custNo, e.g., "70727975" (Customers.cust_no) OR ""
     * @param $currency , e.g., "USD" (Customers.currency)
     * @param $itemNo , e.g. "1097264" (Parts.part_no, WebParts.part_number, etc)
     * @param $quantity , e.g., 1
     * @return OPRICL|null
     */
    public static function findPriceRecordForItem ($priceListDesc, $custNo, $currency, $itemNo, $quantity): ?OPRICL {
        return
            OPRICL::where('PRRF', $priceListDesc)
                    ->where('CUNO', $custNo)
                    ->where('CUCD', $currency)
                    ->where('ITNO', $itemNo)
                    ->where('QTYL', '<=', $quantity)
                    ->where('FVDT', '<=', DB::raw("DATE_FORMAT(CURDATE(), '%Y%m%d')"))
                    ->where('VFDT', '<=', DB::raw("DATE_FORMAT(CURDATE(), '%Y%m%d')"))
                    ->where("LVDT", ">=", DB::raw("DATE_FORMAT(CURDATE(), '%Y%m%d')"))
                    ->orderBy('QTYL', 'DESC')
                    ->limit(1)
                    ->first();
    }
}