<?php

namespace frontend\models;

use common\components\DateUtil;
use Yii;
use yii\data\ActiveDataProvider;
use common\models\Transfer;
use common\models\Account;
use yii\web\NotFoundHttpException;

/**
 * TransferSearch represents the model behind the search form about `common\models\Transfer`.
 */
class TransferSearchToday extends Transfer
{
	
	 
	
	public $totals;
	
	public $accounts;
	
	public $types;

    public $timestampStart;

    public $timestampEnd;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        	['types', 'each', 'rule' => ['integer']],
        ];
    }


    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @return ActiveDataProvider
     * @throws NotFoundHttpException
     */
    public function search($params)
    {

        if ( !isset( $this->id_account ) ){
            throw  new NotFoundHttpException("Kassza nem található");
        }


        $this->timestampStart =  DateUtil::formatDateUtc( DateUtil::todayStart() ) ;
        $this->timestampEnd = DateUtil::formatDateUtc( DateUtil::tomorrowStart() );
        $query = Transfer::find();

        $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');
        }
        $query->andWhere( ['or',['id_user' => Yii::$app->user->id ] , ['paid_by' => Yii::$app->user->id],] );
        $query->andWhere(['transfer.id_account' => $this->id_account]);

        $query->andFilterWhere([
            'type' => $this->type,
        ]);
        
        $query->andFilterWhere(['in' ,'type', $this->types]);

        $created_condition = ['and',[ '>=', 'transfer.created_at', $this->timestampStart ] ,[ '<', 'transfer.created_at', $this->timestampEnd ]  ];
        $paid_condition = ['and',[ '>=', 'transfer.paid_at', $this->timestampStart ] ,[ '<', 'transfer.paid_at', $this->timestampEnd ]  ];
        
        $query->andFilterWhere(['or' , $created_condition , $paid_condition]);
        

        return $dataProvider;
    }

    /**
     * @throws \yii\db\Exception
     */
    public function totalsTransfers(){
    	$accounts =  Account::find()->orderBy("name asc")->all();
    	$idUser = Yii::$app->user->id;
    	$this->totals = Transfer::mkTotals($this->timestampStart, $this->timestampEnd, $idUser, $this->types, $this->id_account, $accounts);
    }
    
}
