<?php

namespace Hilco\Models;
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();
    }

    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 = []) {
        $totalCartPrice = 0;
        foreach ($distinctPartInfo as $key => $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'])) {

                $totalCartPrice += $webCartItem['basePrice'] * $webCartItem['totalQuantity'];

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