<?php

namespace common\modules\blog\models;

use common\models\Settings;
use common\modules\users\models\User;
use Yii;
use \common\modules\testings\models\Session;
use \common\components\ActiveRecordModel;

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

    /**
     * @inheritdoc
     */
    public function name() {
        return 'Подписка на блог';
    }

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

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

    /**
     * @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->afterSubscribeToBlog(['email' => $this->email], true);
            }
            BlogSchedule::generate($this->email, (!is_null($user) ? $user : null));
            Yii::$app->session->set('user_email', $this->email);
        }
    }

    public function beforeDelete(){
        if (!parent::beforeDelete())
            return false;

        BlogSchedule::deleteAll(['email' => $this->email]);

        return true;
    }

    public function behaviors(){
        return [];
    }

    public function send()
    {
        try
        {
            $session = null;
            if(Yii::$app->session->has('SessionId'))
            {
                $session = Session::findOne(Yii::$app->session->get('SessionId'));
            }

            $email = Settings::getValue('bids-support-email');

            $message = Yii::$app->controller->view->render('@common/modules/bids/views/bid/mail-all', [
                'model' => $this,
                'session' => $session,
            ]);

            $headers = "MIME-Version: 1.0\r\n".
                "Content-Transfer-Encoding: 8bit\r\n".
                "Content-Type: text/html; charset=\"UTF-8\"\r\n".
                "X-Mailer: PHP v.".phpversion()."\r\n".
                "From: Заявка с сайта TaskOn <".Settings::getValue('bids-support-email-from').">\r\n";

            $subject = "Заявка №".$this->id.". С сайта task-on.com поступила заявка на подписку на блог.";

            @mail($email, $subject, $message, $headers);
        }
        catch (Exception $e)
        {
        }
    }
}
