<?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 TransferSummarySearch extends Transfer
{
	public $searchObjectName;
	public $searchTypeName;
	public $searchUserName;
	public $start;
	public $end;
	
	public $timestampStart;
	public $timestampEnd;
	
	
	public $types;
	
	/**
	 * all money gained with ticket sell
	 * */
	public $ticketMoney;
	/**
	 * all money gained with product sell grouped by category
	 * */
	public $productMoneies;
	/**
	 * all money lost by money movement 
	 * */
	public $moneyMovementMoneis;
	/**
	 * total gained money
	 * */
	public $total;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[  'id_account','id_user', 'type'], 'integer'],
//             [[ 'searchObjectName' ], 'string'],
        	[[ 'start', ], 'date'  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd'  ],
        	[[ 'end' , ], 'date'    , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd' ],
        	['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)
    {

        
        
        $this->load($params);

        if (!$this->validate()) {
//             $query->where('0=1');
//             return $dataProvider;
        }

        
        $this->readTicketMoney();
        $this->readProductsByCategory();
        $this->readMoneyMovements();
        $this->calcTotal();
    }
    
    protected function calcTotal(){
    	$this->total = 0;
    	$this->total += $this->ticketMoney;
    	$this->total -= $this->moneyMovementMoneis['money_movement_money'];
    	foreach ($this->productMoneies as $pm ){
    		$this->total += $pm['product_money'];
    	}
    }
    
    
    protected function addQueryFilters($query){
    	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->andFilterWhere([
    			'transfer.id_account' => $this->id_account,
    			'transfer.type' => $this->type,
    			'transfer.id_user' => $this->id_user,
    	]);
    	
    	$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]);
    	
    	$query->andWhere(['transfer.status' => Transfer::STATUS_PAID]);
    	
    }
    
    
    protected function readTicketMoney(){
    	
    	$query = (new \yii\db\Query());
    	$query->select([' coalesce(sum(abs(transfer.money)),0) AS ticket_money']);
    	$query->from('transfer');
    	$query->andWhere(['transfer.type' => Transfer::TYPE_TICKET]);
    	$query->innerJoin("ticket", "ticket.id_ticket = transfer.id_object");
    	$this->addQueryFilters($query);
    	
//     	$query = Transfer::find();
//     	$query->andWhere(['type' => Transfer::TYPE_TICKET]);
//     	$this->addQueryFilters($query);
    	$this->ticketMoney = $query->scalar();
		print_r($this->ticketMoney);
    }
    
    protected function readProductsByCategory(){

    	
    	$query = (new \yii\db\Query());
    	$query->select(['coalesce(sum(transfer.money),0) AS product_money', 'product_category.name as category_name']);
    	$query->from('transfer');
    	$query->groupBy(['product_category.id_product_category','product_category.name']);
    	$query->andWhere(['transfer.type' => Transfer::TYPE_PRODUCT]);
    	$query->innerJoin("sale", "sale.id_sale = transfer.id_object");
    	$query->innerJoin("product", "sale.id_product = product.id_product");
    	$query->innerJoin("product_category", "product.id_product_category = product_category.id_product_category");
    	$this->addQueryFilters($query);
    	
    	$this->productMoneies  = $query->all();
    	
    }
    
    
    protected function readMoneyMovements(){
    	$query = (new \yii\db\Query());
    	$query->select([' coalesce(sum(abs(transfer.money)),0) AS money_movement_money']);
    	$query->from('transfer');
    	$query->andWhere(['transfer.type' => Transfer::TYPE_MONEY_MOVEMENT_OUT]);
    	$query->innerJoin("money_movement", "money_movement.id_money_movement = transfer.id_object");
    	$this->addQueryFilters($query);
    	 
    	$this->moneyMovementMoneis  = $query->one();
    }
    
    
    
}
