<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Bills;

/**
 * BillsSearch represents the model behind the search form of `app\models\Bills`.
 */
class BillsSearch extends Bills
{
    public $user_at_org;
    public $auction_id;

    public function rules()
    {
        return [
            [['user_id', 'auction_id', 'bid_id'], 'integer'],
            [['type'], 'safe'],
            [['user_at_org'], 'string', 'max' => 255],
            [['payed'], 'in', 'range' => array_keys(Bills::payStatuses())],
        ];
    }

    public function search($params)
    {
        $query = Bills::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'payed' => SORT_DESC,
                ],
            ],
        ]);
        $this->load($params);
        if (!$this->validate()) {
            return $dataProvider;
        }
        //$query->joinWith(['user', 'auction']);
        if (!Yii::$app->user->identity->isAdmin) {
            $query->andWhere(['bills.user_id' => Yii::$app->user->id]);
        }        
        $query->andFilterWhere([
            'user_id' => $this->user_id,
            'bid_id' => $this->bid_id,
            'bills.type' => $this->type,
            'bills.payed' => $this->payed,
        ]);

        $query->andFilterWhere([
            'bidding.auction_id' => $this->auction_id,
        ]);
        $query->andFilterWhere(['like', 'user.at_org', $this->user_at_org]);
        
        return $dataProvider;
    }
}
