<?php

namespace app\models;
use app\models\InquirerAnswer;
use app\models\InquirerLog;
use Yii;

/**
 * This is the model class for table "inquirer_question".
 *
 * @property int $id
 * @property string $text
 * @property string $active доступна
 * @property string $show показывать на главной
 * @property string $dt_cr
 * @property string $dt_pub
 * @property string $dt_end
 */
class Inquirer extends \yii\db\ActiveRecord
{
	/**
     * @var bin
    */

	protected  $log = NULL;
	public	$resetTime = 60*60;
	public $description = '';
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'inquirer_question';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['text'], 'required'],
            [['text', 'active', 'show'], 'string'],
            [['dt_cr', 'dt_pub', 'dt_end'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'text' => 'Вопрос',
            'active' => 'Доступна',
            'show' => 'Активный опрос',
            'dt_cr' => 'Дата создания',
            'dt_pub' => 'Дата публикации',
            'dt_end' => 'Дата окончания опроса',
        ];
    }

    public function getAnswers()
    {
        return InquirerAnswer::findAll(['idq'=>$this->id]);
    }

    public function getAnswer($idq, $ida)
    {
        return InquirerAnswer::find()->where(['idq'=>$idq, 'id'=>$ida])->One();;
    }

    public function getLog()
    {
		if( !$this->log  ){
			$this->log = new InquirerLog();
		}
        return $this->log;
    }

    public function getPart() //проверка на участие
    {
		$session = Yii::$app->session;
		$ua =  \Yii::$app->request->getUserAgent();
		$uip = \Yii::$app->request->getRemoteIP().",".\Yii::$app->request->getUserIP();
		$hash = md5( $ua.$uip );	//метка пользователя
		$do = $session->has('askq_'.$this->id.'_'.$hash);
		if( $do ){
			$do = ($session->get('askq_'.$this->id.'_'.$hash)+$this->resetTime< time())?false:true;
		}
		return $do;
    }

	public function Show($id, $state = -1)
    {
		if( $state < 0 ){
			$this->show = ($this->show == 'Y')?'N':'Y';
		}else{
			$this->show = $state;
		}
		return $this->save();
	}

	public function Active($id, $state = -1)
    {
		if( $state < 0 ){
			$this->active = ($this->active == 'Y')?'N':'Y';
		}else{
			$this->active = $state;
		}
		return $this->save();
	}

}
