<?php

namespace common\modules\cases\models;

use common\components\ActiveRecordModel;
use common\modules\triggers\models\CasesSchedule;
use Yii;
use common\modules\users\models\User;

/**
 * This is the model class for table "cases_bids".
 *
 * @property integer $id
 * @property string $email
 * @property string $date
 */
class CasesBids extends ActiveRecordModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cases_bids';
    }

    /**
     * @inheritdoc
     */
    public function name() {
        return 'Подписка на кейсы';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email', 'date'], 'required'],
            [['email'], 'unique', 'message' => 'Вы уже подписаны на рассылки по кейсам'],
            [['date'], 'safe'],
            [['email'], 'string', 'max' => 255],
        ];
    }

    /**
     * @param bool $insert
     * @param array $changedAttributes
     * @return bool
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if (!is_null($this->email)) {
            /** @var User $user */
            $user = User::find()->where(['email' => $this->email])->one();
            if (!is_null($user)) {
                $user->afterSubscribe(['email' => $this->email], true);
            }
            Yii::$app->session->set('user_email', $this->email);
        }
    }

    /**
     * @return bool
     */
    public function beforeDelete(){
        if (!parent::beforeDelete())
            return false;

        $users = User::find()->where(['email' => $this->email])->all();
        foreach($users as $user) {
            CasesSchedule::deleteAll(['user_id' => $user->id]);
        }

        return true;
    }

    /**
     * @return array
     */
    public function behaviors(){
        return [];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'email' => 'Email',
            'date' => 'Дата подписки',
        ];
    }
}
