<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\helpers\Url;
use yii\helpers\Html;
use \yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "subscriptions".
 *
 * @property User $user
 * @property Category $category
 * @property integer $id
 * @property integer $user_id
 * @property integer $category_id
 * @property integer $created_at
 */
class Subscriptions extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'subscriptions';
    }

    public function behaviors(){
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ]
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'category_id'], 'required'],
            [['user_id', 'category_id', 'created_at'], 'integer'],
            [['category_id'], 'exist', 'targetClass' => Category::className(), 'targetAttribute' => 'id'],
            [['user_id'], 'exist', 'targetClass' => User::className(), 'targetAttribute' => 'id'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'user_id' => Yii::t('app', 'User ID'),
            'category_id' => Yii::t('app', 'Category Name'),
            'created_at' => Yii::t('app', 'Created At'),
            'fio' => Yii::t('app', 'FIO'),
            'email' => Yii::t('app', 'Email'),
        ];
    }

    public function getUser(){
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getCategory(){
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    public static function subscribe($category_id, $user_id){
        if(false != (Subscriptions::findOne(['category_id' => $category_id, 'user_id' => $user_id]))){
            return false;
        }
        $subscription = new Subscriptions(['user_id' => $user_id, 'category_id' => $category_id]);
        return $subscription->save();
    }

    public static function createNewsletter($auction){
        $category = $auction->category;
        if(!$category){
            return false;
        }
        foreach(Subscriptions::find()->where(['category_id' => $category->id])->all() as $subscription){
            $mail = new Mails([
                'email' => $subscription->user->email,
                'title' => Yii::t('app', 'New Lot in category: "{category}"', ['category' => $category->name]),
                'text' => Yii::t('app', 'View: {link}', ['link' => Url::to(['/publishing/view', 'id' => $auction->id], true)]),
            ]);
            $mail->save(false);
        }
        return true;
    }
}
