<?php
namespace manager\controllers;
use app\models\Inquirer;
use app\models\InquirerAnswer;
use  Yii;

class InquirerController extends BaseController
{
    public function actionIndex()
    {
        return $this->render('index');
    }
    public function actionUpdate($id)
    {
		$model = $this->findModel($id);
		if (Yii::$app->request->isPost && $post = Yii::$app->request->post()){
			if( $model->load($post, 'Inquirer') && $model->save() ){
				if( isset($post['Inquirer']['text_answer']) ){
					$answer_do = InquirerAnswer::findAll(['idq'=>$id]);
					$a = array();
					foreach( $answer_do as $item ){
						$a[$item->id] = $item->id;
					}
					foreach( $post['Inquirer']['text_answer'] as $key => $item ){
						if( isset( $a[$key] ) ){ unset($a[$key]); }
						$answer = InquirerAnswer::findOne(['id'=>$key]);
						if( $answer ){
							$answer->text = $item;
							$answer->idq = $id;
							$answer->save();
						}
					}
					foreach( $a as $item ){
						$answer = InquirerAnswer::findOne(['id'=>$item]);
						$answer->delete();
					}
				}
				if( isset($post['Inquirer']['text_new']) ){
					foreach( $post['Inquirer']['text_new'] as $item ){
						$answer = new InquirerAnswer();
						$answer->text = $item;
						$answer->idq = $id;
						$answer->save();
					}
				}
			}
		}else{
			return $this->render('Update', ['model'=>$model]);
		}
		return  $this->redirect('index');
    }

    public function actionCreate()
    {
		$model = new Inquirer();
		if (Yii::$app->request->isPost && $post = Yii::$app->request->post()){
			if( $model->load($post, 'Inquirer') && $model->save() ){
				if( isset($post['Inquirer']['text_new']) ){
					foreach( $post['Inquirer']['text_new'] as $item ){
						$answer = new InquirerAnswer();
						$answer->text = $item;
						$answer->idq = $model->id;
						$answer->save();
					}
				}
			}
		}else{
			return $this->render('Create', ['model'=>$model]);
		}
		return  $this->redirect('index');
    }

	public function actionShow($id)
    {
		$model = $this->findModel($id);
		if($model) $model->Show($id);
        return $this->redirect('index');
    }

    public function actionActive($id)
    {
		$model = $this->findModel($id);
		if($model) $model->Active($id);
        return $this->redirect('index');
    }

    protected function findModel($id)
    {
        if (($model = Inquirer::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Ой! рубрика не найдена.');
        return false;
    }
}
