<?php

namespace Hilco\Models;

class PromotionAction extends WebModel {
    protected $table = 'PromotionActions';
    protected $fillable = ['sequence', 'promotion_id', 'action_id', 'action_type'];

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

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

    public static function selectList() {
        return self::select('action_type')->distinct()->get();
    }

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

        static::created(function (PromotionAction $action) {
            $className = $action->getActualClassNameForMorph($action->action_type);
            $details = $className::create();
            $action->details()->associate($details);
            $action->save();
        });

        static::deleted(function (PromotionAction $action) {
            $details = $action->details;
            $details->delete();
        });
    }
}