<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Form;
use app\components\Utilities;

/**
 * FormSearch represents the model behind the search form of `app\models\Form`.
 */
class FormSearch extends Form
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['_id', 'name', 'type', 'createdAt', 'status'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        // $query = Form::find();

        $query = null;
        // The admin can see all forms, but normal users can only see the forms in the assigned groups
        if(Yii::$app->user->can('Admin')){
            $query = Form::find();
        }
        else{
            $forms_permissions = Utilities::getUserPermissions();
            $forms_IDs = [];
            if($forms_permissions){
                foreach($forms_permissions as $group){
                    foreach($group as $form => $permissions){
                        $forms_IDs[] = Utilities::getIdAsObject($form);
                    }
                }
            }
            
            $query = Form::find()
                ->where([
                    '_id' => [
                        '$in' => $forms_IDs
                    ]
                ])
                // Inactive forms will not be shown for users
                ->andWhere(['status' => 'Active']);
        }

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'type' => $this->type,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'createdAt', $this->createdAt]);

        return $dataProvider;
    }
}
