<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "subscriber".
 *
 * @property integer $id_subscriber
 * @property string $name
 * @property string $email
 * @property integer $status
 * @property string $token
 * @property string $created_at
 * @property string $updated_at
 */
class Subscriber extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'subscriber';
    }
    
    
    public function behaviors()
    {
    	return ArrayHelper::merge(  [
    			[
    					'class' => TimestampBehavior::className(),
    					'value' => function(){  return date('Y-m-d H:i:s'   ); }
    			],
    			], parent::behaviors());
    }
    

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email'], 'email'],
            [['status','email','name'], 'required'],
            [['status'], 'integer'],
            [['name'], 'string', 'max' => 255],
        	['status' ,'validateSubscribe' ,'skipOnEmpty' => false, 'skipOnError' => false  ,'on' => 'subscribe']
        ];
    }
    
    public function validateSubscribe($attr,$param){
    	if ( $this->status != '1'){
    		$this->addError( "status", "Feliratkozáshoz be kell jelölnie ezt a mezőt!");
    	}
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_subscriber' => Yii::t('common/subscriber', 'Id Subscriber'),
            'name' => Yii::t('common/subscriber', 'Név'),
            'email' => Yii::t('common/subscriber', 'Email'),
            'status' => Yii::t('common/subscriber', 'Szeretnék hírlevelet kapni'),
            'token' => Yii::t('common/subscriber', 'Token'),
            'created_at' => Yii::t('common/subscriber', 'Created At'),
            'updated_at' => Yii::t('common/subscriber', 'Updated At'),
        ];
    }
    
    public function beforeSave($insert){
    	if ( parent::beforeSave($insert)){
    		$this->token = Yii::$app->security->generateRandomString() . '_' . time();
    	}
    	return true;
    }
    
}
