<?php
namespace app\controllers;
use app\models\Inquirer;
use yii\web\NotFoundHttpException;
use  Yii;

class InquirerController extends \yii\web\Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function beforeAction($action)
	{
		if (in_array($action->id, ['ajax'])) {
			$this->enableCsrfValidation = false;
		}
		return parent::beforeAction($action);
	}

    public function actionView($id){
		$model = Inquirer::findOne(['id'=>$id]);

		if( ( !$model instanceof Inquirer ) || $model->active == 'N' ){
			throw new NotFoundHttpException("Опросник не найден");
        }
        return $this->render("view",["model"=>$model]);
    }
    public function actionWidget($id){
		$model = Inquirer::findOne(['id'=>$id]);

		if( ( !$model instanceof Inquirer ) || $model->active == 'N' ){
			throw new NotFoundHttpException("Опросник не найден");
        }
        return $this->renderPartial("widget",["model"=>$model]);
    }
    public function actionAjax(){
		$this->enableCsrfValidation = false;
		if(\Yii::$app->request->isPost){
			if(\Yii::$app->request->post('idq') && \Yii::$app->request->post('ask')  ){
				$ida = (int) \Yii::$app->request->post('ask');	//ответ
				$idq = (int) \Yii::$app->request->post('idq');	//вопрос
				$ua =  \Yii::$app->request->getUserAgent();
				$uip = \Yii::$app->request->getRemoteIP().",".\Yii::$app->request->getUserIP();
				$model = Inquirer::findOne(['id'=>$idq]);
				if( $model ){
					$log=$model->getLog();
					$hash = md5( $ua.$uip );	//метка пользователя
					$ret = $log->testq($idq, $hash);	//голосовал ли этот клиент

					$session = Yii::$app->session;
					$session->set('askq_'.$idq.'_'.$hash, time());

					if( !$ret ){
						$log->add($idq, $ida, $hash);
						$answer = $model->getAnswer($idq, $ida);
						$answer->count++;
						$answer->save();
						return $this->asJson(['status'=>'ok','ret'=>'14']);
					}
					return $this->asJson(['status'=>'ok','ret'=>'15']);
				}
				return $this->asJson(['status'=>'ok','ret'=>'5']);
			}
		}
		return $this->asJson(['status'=>'ok','ret'=>'10']);
	}
}
