<?php

namespace Hilco\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use LogicException;

class PromotionTrigger extends WebModel {
    protected $table = 'PromotionTriggers';
    protected $fillable = ['sequence', 'trigger_type', 'commit_sequence'];

    public function promotion() {
        return $this->belongsTo(Promotion::class, 'promotion_id', 'id');
    }

    public function details() {
        return $this->belongsTo($this->getActualClassNameForMorph($this->trigger_type), 'trigger_id', 'id');
    }

    public static function selectList() {
        return self::select('trigger_type')->distinct()->get()
//            ->map(function ($promoTrigger) {
//                if ($promoTrigger->trigger_type === 'codeTrigger') $promoTrigger->trigger_type = 'Promo Code';
//                else if ($promoTrigger->trigger_type === 'currentOrderTrigger') $promoTrigger->trigger_type = 'Min. Order';
//                else if ($promoTrigger->trigger_type === 'customerTrigger') $promoTrigger->trigger_type = 'Target Customer';
//                else if ($promoTrigger->trigger_type === 'sourceTrigger') $promoTrigger->trigger_type = 'Target Platform';
//                else if ($promoTrigger->trigger_type === 'itemQuantityTrigger') $promoTrigger->trigger_type = 'Min. Qty';
//                return $promoTrigger;
//            }
//            )
        ;
    }

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

        static::created(function (PromotionTrigger $trigger) {
            $className = $trigger->getActualClassNameForMorph($trigger->trigger_type);
            $details = $className::create();
            $trigger->details()->associate($details);
            $trigger->save();
        });

        static::deleted(function (PromotionTrigger $trigger) {
            $details = $trigger->details;
            $details->delete();
        });
    }

    use HasCommitSequence;
}
