<?php

namespace app\controllers;

use app\models\Parameter;
use app\models\ParameterForm;
use app\models\ParameterSearch;

use yii\web\NotFoundHttpException;
use yii\web\Request;

class ListController extends \yii\web\Controller
{
    public function actionIndex(Request $request)
    {
        $searchModel = new ParameterSearch();
        $dataProvider = $searchModel->search($request->queryParams);

        return $this->render(
            'index',
            [
                'provider' => $dataProvider,
                'searchModel' => $searchModel,
            ]
        );
    }

    public function actionEdit(Request $request)
    {
        $id = $request->getQueryParam('id');
        
        $parameter = Parameter::findOne($id);
        if ($parameter === null && $id !== null) {
            throw new NotFoundHttpException();
        }
        
        $model = new ParameterForm();
        if ($parameter) {
            $model->setAttributes([
                'title' => $parameter->title,
                'type'  => $parameter->type,
            ]);
        }

        if ($request->isPost) {
            $data = $request->post();
            $model->load($data);

            if ($model->validate()) {
                if ($id) {
                    $model->edit($parameter);
                } else {
                    $id = $model->create();
                }

                return $this->redirect('/list?ParameterSearch[id]=' . $id);
            }
        }

        return $this->render(
            'edit',
            [
                'id' => $id,
                'model' => $model,
            ]
        );
    }

    public function actionDelicon(Request $request)
    {
        $id = $request->getQueryParam('id');
        $type = $request->getQueryParam('type');
        if ($id === null || !($type == 'normal' || $type == 'gray')) {
            return $this->redirect('/list');
        }

        $param = Parameter::find()->where([ 'id' => $id ])->one();
        if ($param === null) {
            return $this->redirect('/list');
        }

        $param->setAttribute($type == 'normal' ? 'icon' : 'icon_gray', null);
        $param->save();
        return $this->redirect('/list?ParameterSearch[id]='. $id);
    }
}