<?php

namespace Hilco\Models;
use Arr;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class Promotion
 * @package Hilco\Models
 * @property integer $minimum_dollar
 * @property integer $almost_qualified
 * @property boolean $use_rewardsexcluded_list
 */
class PromotionCurrentOrderTrigger extends PromotionTriggerDetails
{
    protected $table = 'PromotionCurrentOrderTriggers';
    protected $fillable = ['via_web', 'via_cst', 'minimum_dollar', 'almost_qualified', 'commit_sequence', 'use_rewardsexcluded_list'];
    protected $casts = ['use_rewardsexcluded_list' => 'boolean'];

    public function hasAlmostQualifyingField() {
        return true;
    }

    public function webGroups() {
        return $this
            ->morphedByMany(WebGroup::class, 'product',
                            'PromotionCurrentOrderTrigger_Product', 'promotioncurrentordertrigger_id')
            ->withPivot(['excluded'])
            ->whereNull('PromotionCurrentOrderTrigger_Product.deleted_at')
        ;
    }

    public function webCategories() {
        return $this
            ->morphedByMany(WebCategory::class, 'product',
                            'PromotionCurrentOrderTrigger_Product', 'promotioncurrentordertrigger_id')
            ->withPivot(['excluded'])
            ->whereNull('PromotionCurrentOrderTrigger_Product.deleted_at')
        ;
    }

    public function webCollections() {
        return $this
            ->morphedByMany(WebCollection::class, 'product',
                            'PromotionCurrentOrderTrigger_Product', 'promotioncurrentordertrigger_id')
            ->withPivot(['excluded'])
            ->whereNull('PromotionCurrentOrderTrigger_Product.deleted_at')
        ;
    }

    public function webFamilies() {
        return $this
            ->morphedByMany(WebFamily::class, 'product',
                            'PromotionCurrentOrderTrigger_Product', 'promotioncurrentordertrigger_id')
            ->withPivot(['excluded'])
            ->whereNull('PromotionCurrentOrderTrigger_Product.deleted_at')
        ;
    }

    public function webParts() {
        return $this
            ->morphedByMany(WebPart::class, 'product',
                            'PromotionCurrentOrderTrigger_Product', 'promotioncurrentordertrigger_id')
            ->withPivot(['excluded'])
            ->whereNull('PromotionCurrentOrderTrigger_Product.deleted_at')
        ;
    }

    public function getRelationForProductTableType($tableType) {
        if($tableType === 'webFamily' || $tableType === 'webCategory') {
            $relationName = substr($tableType, 0, -1);
            $relationName .= 'ies';
        } else {
            $relationName = $tableType . 's';
        }
        return $this->$relationName();
    }

    /**
     * @param Customer $soldToCustomer
     * @param $webCartItems
     * @param $distinctPartInfo -- NOTE: I know this says $distinctPartInfo but it should probably be refactored to $distinctLineInfo (or better yet, its own object or something...)
     * @return bool
     */
    public function isTriggered(Customer $soldToCustomer, $webCartItems, $distinctPartInfo = []) {
        $totalCartPrice = $this->getCurrentQualifyingCartTotal($soldToCustomer, $webCartItems, $distinctPartInfo);

        return $totalCartPrice >= $this->minimum_dollar;
    }

    public function isAlmostQualifying(Customer $soldToCustomer, $webCartItems, $distinctPartInfo = []) {
        $almostQualifyingCount = $this->getCurrentQualifyingCartTotal($soldToCustomer, $webCartItems, $distinctPartInfo);
        return ($almostQualifyingCount >= $this->almost_qualified) ?
            $this->minimum_dollar - $almostQualifyingCount : -1;
    }

    public function getCurrentQualifyingCartTotal(Customer $soldToCustomer, $webCartItems, $distinctPartInfo = []) {
        $skipTypes = ["rewards","customer","promotion"];
        $totalCartPrice = 0;
        foreach ($distinctPartInfo as $index => $webCartItem) {
            if ($this->use_rewardsexcluded_list) {
                $partNumber = $webCartItem['partNum'];
                $part = Part::wherePartNo($partNumber)->first();
                if ($part->isRewardsExcluded()) {
                    continue;
                }
            }
            if (!empty($webCartItem) &&
                isset($webCartItem['basePrice']) &&
                is_numeric($webCartItem['basePrice']) &&
                isset($webCartItem['totalQuantity']) &&
                is_numeric($webCartItem['totalQuantity'])) {

                $extendedPrice = Arr::get($webCartItem, "basePrice", 0) * Arr::get($webCartItem, "totalQuantity", 0);
                if (!$webCartItem["isContractPrice"]) {
                foreach (Arr::get($webCartItem, 'discounts', []) as $discountType => $discountInfo) {
                    if (in_array($discountType, $skipTypes)) {
                        continue;
                    } else {
                        $discAmt = 0;
                        foreach ($discountInfo as $k => $v) {
                            if (str_starts_with($k, "DIA")) {
                                $discAmt = empty($v) ? 0 : $v;
                                break;
                            }
                        }
                        $extendedPrice -= $discAmt;
                    }
                }
                }
                $totalCartPrice += $extendedPrice;

            }
        }
        return $totalCartPrice;
    }

    public function setMinimumDollarAttribute($value) {
        $this->attributes['minimum_dollar'] = $value;
    }

    public function postTriggerOperation($soldToCustomer) {
        // TODO: Implement postTriggerOperation() method.
    }

    public static function boot() {
        parent::boot();

        static::deleted(function (PromotionCurrentOrderTrigger $promotionCurrentOrderTrigger) {
            $promotionCurrentOrderTriggerProducts =
                PromotionCurrentOrderTrigger_Product::where('promotioncurrentordertrigger_id', '=', $promotionCurrentOrderTrigger->id);
            foreach ($promotionCurrentOrderTriggerProducts as $promotionCurrentOrderTriggerProduct) {
                $promotionCurrentOrderTriggerProduct->delete();
            }
        });
    }
}