<?php

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

/**
 * Class Promotion
 * @package Hilco\Models
 *
 * @method static Builder active()
 */
class PromotionCurrentOrderTrigger extends PromotionTriggerDetails
{
    protected $table = 'PromotionCurrentOrderTriggers';
    protected $fillable = ['via_web', 'via_cst', 'minimum_dollar', 'almost_qualified', 'commit_sequence'];

    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 (!empty($webCartItem) &&
                array_key_exists('basePrice', $webCartItem) &&
                is_numeric($webCartItem['basePrice']) &&
                array_key_exists('totalQuantity', $webCartItem) &&
                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();
            }
        });
    }
}