<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Transfer;
use yii\db\Expression;
use yii\base\Object;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\Account;
use common\components\Helper;
use common\components\RoleDefinition;

/**
 * TransferSearch represents the model behind the search form about `common\models\Transfer`.
 */
class TransferSearch extends Transfer
{
	public $searchObjectName;
	public $searchTypeName;
	public $searchUserName;
	public $start;
	public $end;
	
	public $timestampStart;
	public $timestampEnd;
	
	public $accountTotals;
	public $fullTotal;
	
	public $types;
	public $totals;
	
	public $customer_name;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[  'id_account','id_user', 'type','status','payment_method'], 'integer'],
        	[['customer_name'],'safe'],
//             [[ 'searchObjectName' ], 'string'],
//         	[[ 'start', ], 'date'  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd'  ],
//         	[[ 'end' , ], 'date'    , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd' ],
        		[[ 'start',  ], 'date', 'format' =>Yii::$app->formatter->datetimeFormat  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm' ,'timeZone' => 'UTC' ],
        		[[ 'end' , ], 'date'  ,'format' =>Yii::$app->formatter->datetimeFormat  , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm' ,'timeZone' => 'UTC' ],
        	['types', 'each', 'rule' => ['integer']],
        ];
    }

    /**
     * @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 = Transfer::find();
        
        $query->innerJoinWith('account');
       	$query->innerJoin('user', " user.id = transfer.id_user");
       	$query->leftJoin('customer', " transfer.id_customer = customer.id_customer");

        
        if ( !RoleDefinition::isAdmin() ){
        	$query->innerJoin("user_account_assignment",'transfer.id_account = user_account_assignment.id_account' );
        	$query->andWhere(['user_account_assignment.id_user' => Yii::$app->user->id ]);
        	$query->andWhere(['account.type' => Account::TYPE_ALL ]);
        	
        	if ( RoleDefinition::isReception()){
        		$query->andWhere(['transfer.id_user' => Yii::$app->user->id ]);
        	}
        }
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        	'sort' =>[
        		'defaultOrder' =>[
        				'created_at' => SORT_DESC
        		],
        		'attributes' =>[
        				'paid_at' =>[
        						'asc' => ['transfer.paid_at' => SORT_ASC ],
        						'desc' => ['transfer.paid_at' => SORT_DESC],
        				],
        				'created_at' =>[
        						'asc' => ['transfer.created_at' => SORT_ASC ],
        						'desc' => ['transfer.created_at' => SORT_DESC],
        				],
        				'status' =>[
        						'asc' => ['transfer.status' => SORT_ASC ],
        						'desc' => ['transfer.status' => SORT_DESC],
        				],
        				'money' =>[
        						'asc' => ['transfer.money' => SORT_ASC ],
        						'desc' => ['transfer.money' => SORT_DESC],
        				],
        				'count' =>[
        						'asc' => ['transfer.count' => SORT_ASC ],
        						'desc' => ['transfer.count' => SORT_DESC],
        				],
        				'item_price' =>[
        						'asc' => ['transfer.item_price' => SORT_ASC ],
        						'desc' => ['transfer.item_price' => SORT_DESC],
        				],
        				'id_account' =>[
        						'asc' => ['account.name' => SORT_ASC ],
        						'desc' => ['account.name' => SORT_DESC],
        				],
        				'id_user' =>[
        						'asc' => ['user.username' => SORT_ASC ],
        						'desc' => ['user.username' => SORT_DESC],
        				],
        				'id_customer' =>[
        						'asc' => ['customer.name' => SORT_ASC ],
        						'desc' => ['customer.name' => SORT_DESC],
        				],
        		]
        	]
        ]);

        
//         $query->addSelect( ['*'  ]);
        
        $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;
        }

        
        $query->andFilterWhere([
            'transfer.id_account' => $this->id_account,
            'transfer.type' => $this->type,
        	'transfer.status' => $this->status,
        	'transfer.payment_method' => $this->payment_method,
        	'customer.name' => $this->customer_name
        ]);
        
        $query->andFilterWhere(['in' ,'transfer.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]);
        
        if ( isset($this->id_user)){
	        $query->andFilterWhere([
	        		 'or',
	        		['transfer.id_user' => $this->id_user],
	        		['transfer.paid_by' => $this->id_user],
	        ]);
        }
        
        
        if (!RoleDefinition::isAdmin()){
        	Helper::restrictIfNotAdminTheStartDate($query, $this->timestampStart,['transfer.created_at','transfer.paid_at']);
        }
        
        return $dataProvider;
    }
    
    
    public function totalsTransfers( ){
    	$accountTotals = [];
    	$fullTotal = [
    	'label' => Yii::t('common/transfer', 'Total'),
    	'money' => 0
    	];
    	 
    	 
    	$accounts =  Account::read();
    	$accountMap = ArrayHelper::map( $accounts ,'id_account','name' );
    	$idUser = $this->id_user;
    	 
    	/**mk totals need date time format*/
    	$start = $this->timestampStart;
    	if ( isset($start) && !empty($start)){
    		$start .= " 00:00";
    	}
    	
    	
    	$this->totals = Transfer::mkTotals($start, $this->timestampEnd, $idUser, $this->types, $this->id_account, $accounts, $accountMap);
    	 
    
    }
    
    
    
    
}
