<?php

namespace Hilco\Models;

class PromotionTrigger extends WebModel {
    protected $table = 'PromotionTriggers';
    protected $fillable = ['sequence', 'promotion_id', 'trigger_id', '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();
    }

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