<?php
/**
 * Created by PhpStorm.
 * User: steven
 * Date: 7/30/19
 * Time: 4:27 PM
 */

namespace Hilco\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * @property mixed $id
 * @property mixed $division_id
 * @property mixed $salesorder_id
 * @property int $line_number
 * @property mixed $line_status
 * @property mixed $plant_id
 * @property mixed $warehouse_id
 * @property mixed $binlocation_id
 * @property bool $nocharge_flag
 * @property int $part_id
 * @property int $quantity
 * @property float $unit_price
 * @property bool $taxable
 * @property string $date_created
 * @property string $date_modified
 * @property string $date_uploaded
 * @property string $deleted_at
 * @property bool $is_kit
 * @property float $override_price
 * @property string $pricelist
 * @property int $is_contract
 * @property string $customer_reference
 * @property float $ext_tax
 * @property-read mixed $id_string
 * @mixin \Eloquent
 * @property Part part
 * @property-read OrderPartLine $partLines
 * @property-read Collection|OrderDiscountLine[] $salesOrderDiscLines
 */
class SalesOrderLine extends UuidModel {
    protected $table = 'SalesOrderLines';
    protected $connection = 'hilco-live';

    /**
     * @deprecated salesorderstatuses no longer exist
     */
    public function salesOrderStatus() {
        return $this->hasMany(SalesOrderStatus::class, 'salesordermainline_id', 'id');
    }

    /**
     * @deprecated misc-lines no longer exist
     */
    public function miscLine()
    {
        return $this->hasOne(OrderMiscLine::class, 'id', 'parent_id')->with('miscCharge');
    }

    /**
     * @deprecated sub-lines no longer exist
     */
    public function subLines()
    {
        return $this->hasMany(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderDiscLines');
    }

    /**
     * @deprecated line-schedules no longer exist
     */
    public function orderLineSchedules()
    {
        return $this->hasMany(SalesOrderLineSchedule::class, 'salesordermainline_id');
    }

    /**
     * @deprecated replace with SalesOrderLine::salesOrderDiscLines()
     */
    public function discLines(){
        return $this->hasMany(OrderDiscountLine::class, 'salesorderline_id')->whereNull('deleted_at');
    }

    /**
     * @return HasMany
     */
    public function salesOrderDiscLines(): HasMany {
        return $this->hasMany(OrderDiscountLine::class, "salesorderline_id", "id");
    }

    /**
     * @deprecated sub-lines no longer exist
     */
    public function miscSubLines()
    {
        return $this->hasMany(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderMiscLines')->whereNull('deleted_at')->with('miscLine.miscCharge');
    }

    /**
     * @deprecated misc-lines no longer exist
     */
    public function miscLines(){
        return $this->hasMany(OrderMiscLine::class, 'salesorderline_id')->where('deleted_at', '=', '0000-00-00 00:00:00')->with('miscCharge');
    }

    /**
     * @deprecated sub-lines no longer exist
     */
    public function attnSubLine() {
        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderAttnLines')->with('attnLine');
    }

    /**
     * @deprecated sub-lines no longer exist
     */
    public function instructionSubLine() {
        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderInstructionLines')->with('instructionLine');
    }

    /**
     * @deprecated sub-lines no longer exist
     */
    public function xrefSubLine() {
        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderXrefLines')->with('xrefLine');
    }

    /**
     * @deprecated sub-lines no longer exist
     */
    public function commentLine()
    {
        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderCommentLines')->with('commentLine');
    }

    public function extractComments($subLine) {
        if (is_null($subLine)) return [];
        $commentLine = $subLine->commentLine;
        $comments = [];
        if ($commentLine->line_comment_all != null && $commentLine->line_comment_all != '') {
            $comments['A'] = $commentLine->line_comment_all;
        }
        if ($commentLine->line_comment_external != null && $commentLine->line_comment_external != '') {
            $comments['E'] = $commentLine->line_comment_external;
        }
        if ($commentLine->line_comment_internal != null && $commentLine->line_comment_internal != '') {
            $comments['I'] = $commentLine->line_comment_internal;
        }
        if ($commentLine->line_comment_display != null && $commentLine->line_comment_display!= '') {
            $comments['D'] = $commentLine->line_comment_display;
        }
        return $comments;
    }

    public function shipPlant() {
        return $this->belongsTo(Plant::class, 'plant_id');
    }

    /**
     * @deprecated Warehouses no longer exist
     */
    public function shipWarehouse() {
        return $this->belongsTo(Warehouse::class, 'warehouse_id');
    }

    public function order() {
        return $this->belongsTo(Order::class, 'salesorder_id');
    }

    /**
     * @deprecated BinLocations no longer exist
     */
    public function shipBinLocation() {
        return $this->belongsTo(BinLocation::class, 'binlocation_id');
    }

    public function getTotalDiscount() {
        $totalDiscount = 0;
        foreach ($this->salesOrderDiscLines as $discLine) {
            $totalDiscount += $discLine->discount_amount;
        }
        return $totalDiscount;
    }

    public function getDiscountUnitPriceExtension() {
        return $this->getLinePrice() - $this->getTotalDiscount();
    }

    /**
     * @return BelongsTo
     */
    public function part() {
        return $this->belongsTo(Part::class, 'part_id');
    }

    /**
     * @deprecated PriceLists no longer exist
     */
    public function priceLists() {
        return $this->hasMany(PriceList::class, 'part_id', 'part_id');
    }

    /**
     * @deprecated PriceLists no longer exist
     */
    public function getPriceListPriceAttribute() {
        $priceLists = $this->priceLists->sortByDesc('quantity_level');
        foreach ($priceLists as $priceList) {
            if ($this->quantity >= $priceList->quantity_level) {
                return $priceList->price;
            }
        }
        return null;
    }

    /**
     * @deprecated Replace with SalesOrderLine::getDiscountUnitPriceExtension().
     * I don't think this is relevant or necessary anymore -- rewards discounts no longer exist, and it's just
     * confusingly named ("customer" discount method returns only "rewards" discounts?).
     */
    public function getLineCustomerDiscountPrice(){
        $extendedPrice = $this->getLinePrice();
        $discountLines = $this->salesOrderDiscLines;
        foreach($discountLines as $discountLine){
            if($discountLine->discount_code === 'Rewards' || $discountLine->discount_code === 'REWARDS'){
                if($discountLine->discount_amount > 0){
                    $extendedPrice -= $discountLine->discount_amount;
                    break;
                }
            }
        }

        return $extendedPrice;
    }

    public function getLineStatus() {
        return $this->line_status;
    }

    public function getQuantity() {
        return $this->quantity;
    }

    public function getUnitPrice() {
        return $this->unit_price;
    }

    public function getLinePrice() {
        return $this->unit_price * $this->quantity;
    }

    public function getTrayInfo() {
        return $this->customer_reference;
    }

}