<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class AccountThreshold extends ActiveRecord
{
    public function rules()
    {
        return [
            [['account_id', 'threshold_value', 'max_notifications', 'cooldown_period'], 'required'],
            [['threshold_value'], 'number', 'min' => 0],
            [['max_notifications', 'cooldown_period'], 'integer', 'min' => 0],
            [['last_notification_at'], 'safe'],
            [['account_id'], 'exist', 'targetClass' => Account::class, 'targetAttribute' => 'id'],
            [['last_notification_at'], 'date', 'format' => 'php:Y-m-d H:i:s'],
        ];
    }

    public static function tableName()
    {
        return 'account_thresholds';
    }

    public function getAccount()
    {
        return $this->hasOne(Account::class, ['id' => 'account_id']);
    }

    public function getNotifications()
    {
        return $this->hasMany(Notification::class, ['threshold_id' => 'id']);
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($insert) {
                $this->last_notification_at = null;
            }
            return true;
        }
        return false;
    }
}