<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Accounts;
use yii\db\Expression;

/**
 * accountsSerach represents the model behind the search form about `backend\models\Accounts`.
 */
class Accountssearch extends accounts
{
    public $telephone;
    public $postcode;
    public $town;
    public $contact;
    public $related;
    public $nickname;
    public $primaryrecord;
    public $created_at_range;
    public $updated_at_range;
    public $tempaccounts;

    /**
     * {@inheritdoc}
     */
    public function rules() : array
    {
        return [
            [['telephone', 'postcode', 'town', 'contact', 'type', 'intid', 'nickname' ], 'safe'],
            [['account_code', 'name', 'email', 'web_email', 'stop', 'web_stop'], 'safe'],
            [['stop'], 'boolean'],
            [['created_at_range','updated_at_range','updatedby_name', 'createdby_name'], 'string'],
        ];
    }

    /**
     * {@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 = accounts::find()
            ->where(['!=', 'accounts.status', 'Deleted']);

        $this->load($params);

        if ($this->telephone !== null || $this->postcode !== null || $this->town !== null) {
            $query->joinwith('addressl');
        }

        // add conditions that should always apply here

        $pagesizeName = 'per-page';
        $psize = !empty(Yii::$app->request->get($pagesizeName)) || Yii::$app->request->get($pagesizeName) == 0 ? Yii::$app->request->get($pagesizeName) : (empty(Yii::$app->params['gridsize']) == false ? Yii::$app->params['gridsize'] : 20);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSizeParam' => $pagesizeName,
                'pageSize' => $psize,
            ],
        ]);



        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            if (!empty($this->created_at_range) && strpos($this->created_at_range, '-') !== false) {
                list($start_date, $end_date) = explode(' - ', $this->created_at_range);
                $query->andFilterWhere(['between', 'accounts.created_at', strtotime(str_replace('/', '-', $start_date)), strtotime(str_replace('/', '-', $end_date))]);
            }
            if (!empty($this->updated_at_range) && strpos($this->updated_at_range, '-') !== false) {
                list($start_date1, $end_date1) = explode(' - ', $this->updated_at_range);
                $query->andFilterWhere(['between', 'accounts.updated_at', strtotime(str_replace('/', '-', $start_date1)), strtotime(str_replace('/', '-', $end_date1))]);
            }

            return $dataProvider;
        }

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

        $query->andFilterWhere(['like', 'accounts.account_code', $this->account_code])
            ->andFilterWhere(['=', 'accounts.stop', $this->stop])
            ->andFilterWhere(['like', 'accounts.name', $this->name])
            ->andFilterWhere(['like', 'accounts.type', $this->type])
            ->andFilterWhere(['like', 'accounts.email', $this->email])
            ->andFilterWhere(['like', 'accounts.web_mail', $this->web_email])
            ->andFilterWhere(['like', 'address.town', $this->town])
            ->andFilterWhere(['like', 'address.telephone', $this->telephone])
            ->andFilterWhere(['like', 'address.postcode', $this->postcode])
            ->andFilterWhere(['like', 'address.contact', $this->contact])
            ->andFilterWhere(['like', 'accounts.updatedby_name', $this->updatedby_name])
            ->andFilterWhere(['like', 'accounts.createdby_name', $this->createdby_name]);

        return $dataProvider;
    }
    public function relatedbranchsearch($id, $params)
    {

        $expression = new Expression("CASE WHEN R.sourceid = '$id' THEN 1 ELSE null END AS related");
        $query = Settings::find()
            ->select(['sys_settings.*', 'R.primaryrecord as primaryrecord', 'R.data as account_code'])
            ->addSelect($expression)
            ->where(['not', ['=', 'sys_settings.nickname', '']])
            ->andfilterwhere(['=', 'sys_settings.status', 'Active'])
            ->joinwith('rlookup as R')
            ->orderby(['related' => SORT_DESC, 'nickname' => SORT_ASC])
            ->distinct()
        //    ->asArray();
        ;
        $dataProvider = new ActiveDataProvider(
            [
                'query' => $query,
                //    'sort' => ['attributes' => ['nickname' => SORT_ASC],],
                'pagination' => false,
            ]
        );


        $dataProvider->setSort(
            [
                'attributes' => [
                    'sys_settings.nickname' => [
                        'asc' => ['nickname' => SORT_ASC],
                        'desc' => ['nickname' => SORT_DESC],
                        'label' => 'Sort By Branch name',
                    ],
                ]
            ]
        );
        $this->load($params);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere(
            [
                //'parent.category_name' => $this->ParentCategory,
                'related' => $this->related,
            ]
        );

        $query
            //->orFilterWhere(['like', 'categories.name', $this->category_name])
            ->orFilterWhere(['like', 'sys_settings.nickname', $this->nickname])
            ->orFilterWhere(['like', 'related', $this->related]);
        return $dataProvider;
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function userSearch($params, $model)
    {
        $this->tempaccounts = !empty($model->adv->sysaccounts) ? array_keys($model->adv->sysaccounts) : (!empty($model->accountData) && array_key_exists('accCode', $model->accountData) ? [$model->accountData['accCode']] : []);
     
        $query = Accounts::find()
            ->where(['!=', 'accounts.status', 'Deleted'])
            ->andfilterWhere(['in', 'account_code', $this->tempaccounts])
            ->distinct();
        $query2 = Accounts::find()
            ->where(['!=', 'accounts.status', 'Deleted'])
            ->andfilterWhere(['not in', 'account_code', $this->tempaccounts])
            ->distinct();
            
        
        $unionQuery = (new \yii\db\Query())
            ->from([
                'query' => $query->union($query2)
                    ->indexby('account_code')
                    ->distinct()
            ]);
     
        $this->load($params);


        if ($this->telephone !== null || $this->postcode !== null || $this->town !== null) {
            $query->joinwith('addressl');
        }

        // add conditions that should always apply here

        $pagesizeName = 'per-page';
        $psize = !empty(Yii::$app->request->get($pagesizeName)) || Yii::$app->request->get($pagesizeName) == 0 ? Yii::$app->request->get($pagesizeName) : (empty(Yii::$app->params['gridsize']) == false ? Yii::$app->params['gridsize'] : 20);
        $dataProvider = new ActiveDataProvider([
            'query' => $unionQuery,
            'pagination' => [
                'pageSizeParam' => $pagesizeName,
                'pageSize' => $psize,
            ],
        ]);



        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;
        }

        if (!empty($this->created_at_range) && strpos($this->created_at_range, '-') !== false) {
            list($start_date, $end_date) = explode(' - ', $this->created_at_range);
            $query->andFilterWhere(['between', 'accounts.created_at', strtotime(str_replace('/', '-', $start_date)), strtotime(str_replace('/', '-', $end_date))]);
        }
        if (!empty($this->updated_at_range) && strpos($this->updated_at_range, '-') !== false) {
            list($start_date1, $end_date1) = explode(' - ', $this->updated_at_range);
            $query->andFilterWhere(['between', 'accounts.updated_at', strtotime(str_replace('/', '-', $start_date1)), strtotime(str_replace('/', '-', $end_date1))]);
        }

        $query2->andFilterWhere(['like', 'accounts.name', $this->name])
            ->andFilterWhere(['like', 'accounts.account_code', $this->account_code]);

        return $dataProvider;
    }
}
