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

namespace Hilco\Models;
use DB;


/**
 */
class SubscriptionOrderLine extends UuidModel
{
    protected $table = 'SubscriptionOrderLines';

    protected $fillable = ['customer_reference', 'quantity'];

    //todo I've commented out all of the relationships which aren't and probably don't need to be implemented
//    public function salesOrderStatus() {
//        return $this->hasMany(SalesOrderStatus::class, 'salesordermainline_id', 'id');
//    }

    public function salesOrderLines(){
        return $this->belongsToMany(Order::class, 'SalesOrderLine_SubscriptionOrderLine', 'subscriptionorderline_id', 'salesorderline_id')
            ->wherePivot('deleted_at', '=', '0000-00-00 00:00:00');
    }

    public function salesOrderLinesNeedingUpdate(){
        return $this->salesOrderLines()->wherePivot('needs_update', '=', '1');
    }

    public function miscLine()
    {
        return $this->hasOne(OrderMiscLine::class, 'id', 'parent_id')->with('miscCharge');
    }

//    public function subLines()
//    {
//        return $this->hasMany(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderDiscLines');
//    }
//
//    public function orderLineSchedules()
//    {
//        return $this->hasMany(SalesOrderLineSchedule::class, 'salesordermainline_id');
//    }
//
//    public function discLines(){
//        return $this->hasMany(OrderDiscountLine::class, 'salesorderline_id')->whereNull('deleted_at');
//    }

//    public function miscSubLines()
//    {
//        return $this->hasMany(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderMiscLines')->whereNull('deleted_at')->with('miscLine.miscCharge');
//    }
//
//    public function miscLines(){
//        return $this->hasMany(OrderMiscLine::class, 'salesorderline_id')->where('deleted_at', '=', '0000-00-00 00:00:00')->with('miscCharge');
//    }
//
//    public function attnSubLine() {
//        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderAttnLines')->with('attnLine');
//    }
//
//    public function instructionSubLine() {
//        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderInstructionLines')->with('instructionLine');
//    }
//
//    public function xrefSubLine() {
//        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderXrefLines')->with('xrefLine');
//    }
//
//    public function commentLine()
//    {
//        return $this->hasOne(OrderSubLine::class, 'salesordermainline_id')->where('parent_type', 'SalesOrderCommentLines')->with('commentLine');
//    }

    /**
     * todo we might need this one, it won't work as is
     * @param $subLine
     * @return array
     */
    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');
    }

    public function shipWarehouse() {
        return $this->belongsTo(Warehouse::class, 'warehouse_id');
    }

    public function shipBinLocation() {
        return $this->belongsTo(BinLocation::class, 'binlocation_id');
    }

    public function getTotalDiscount() {
        return 0;
        //todo calculate discont maybe?
//        $totalDiscount = 0;
//        foreach ($this->discLines as $discLine) {
//            $totalDiscount += $discLine->discount_amount;
//        }
//        return $totalDiscount;
    }

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

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

    // Do we have any use for this?

    public function priceLists() {
        return $this->hasMany(PriceList::class, 'part_id', 'part_id');
    }

    public function getPriceListPriceAttribute() {
        $priceLists = $this->priceLists->sortByDesc('quantity_level');
        foreach ($priceLists as $priceList) {
            if ($this->quantity >= $priceList->quantity_level) {
                return $priceList->price;
            }
        }
        return null;
    }

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

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

    public function getExtensionPriceAttribute(){
        $price = $this->extension_base_price;
//        $discounts = OrderDiscountLine::where('salesorderline_id', '=', $this->id)->get();
//        foreach($discounts as $discount){
//            if($discount->discount_code === 'Rewards' || $discount->discount_code === 'REWARDS'){
//                if($discount->discount_amount > 0){
//                    $price -= $discount->discount_amount;
//                    break;
//                }
//            }
//        }

        return $price;
    }
    
    public function scopeActive($query){
        return $query->whereHas('subscriptionOrder', function ($query) {
            return $query->active();
        });
    }

    public function scopeForActiveUser($query){
        return $query->forUser(auth()->user());
    }
    
    public function scopeForUser($query, $user){
        if ($user){
            return $query->whereHas('subscriptionOrder', function ($query) use ($user){
                    return $query->forUser($user);
            });
        }else{
            return $query->whereRaw('1=0');
        }
    }

    public function subscriptionOrder(){
        return $this->belongsTo(SubscriptionOrder::class, 'subscriptionorder_id');
    }

    public function getSubscriptionPeriodAttribute() {
        return $this->subscriptionOrder->subscription_period;
    }

    public function getWebPartAttribute() {
        return $this->part->webPart;
    }

    public function getPartNumberAttribute() {
        return $this->part->part_no;
    }
}