<?php

namespace common\components;

use Yii;
use common\models\Transfer;
use yii\db\Query;
use common\models\Account;

use common\models\MoneyMovement;
use common\components\RoleDefinition;
use common\models\AccountState;
/**
 * TransferListSearch represents the model behind the search form about `common\models\Transfer`.
 */
class DailyListing 
{
	
	public $mode = "reception";//reception or admin or accountstate
	
	/**
	 * string start date , inclusive
	 * */
	public $start;
	/**
	 * string end date, exclusive
	 * */
	public $end;
	/**
	 * date start date, inclusive
	 * */
	public $timestampStart;
	/**
	 * date end date , exlusive
	 * */
	public $timestampEnd;
	
	public $totals;
	/**available accounts*/
	public $accounts;
	/**
	 * 
	 * */
	public $types;
	
	public $users;
	
	
	/**
	 * all money gained with ticket sell
	 * */
	public $ticketMoney;
	/**
	 * all money gained with ticket sell gruped by user
	 * */
	public $ticketMoneyByUser;
	/**
	 * all money gained with product sell
	 * */
	public $productMoney;
	
	public $productMoneyMoney;
	/**
	 * all money gained with product sell
	 * */
	public $productMoneyNetto;
	/**
	 * all money gained with product sell grouped by category
	 * */
	public $productMoneies;
	/**
	 * all money lost by money movement
	 * */
	public $moneyMovementMoneis;
	public $moneyMovementMoney;
	public $moneyMovementMoneisByUser;
	public $moneyMovementMoneyByUser;
	/**
	 * total gained money brutto
	 * */
	public $total;
	/**
	 * total gained money netto
	 * */
	public $totalNetto;
	
	/**
	 * ticket sale statisitc
	 * */
	public $ticketStats;
	
	public $ticketStatsByUser;
	
	/**
	 * money movements by type
	 * */
	public $moneyMovementsByType;
	
	public $tickets;
	/**
	 * all product transfer
	 * */
	public $products;
	public $moneyMovements;
	
	public $productsByCategory;
	
	public $id_account;
	public $id_user;
	public $type;
	
	public $totalWithCassa;
	
	public $cassaOpen;
	
	public $showWithCassaOpen = false;// if easy total should be displayed with cassa open money
	
	public $accountState; //the cassa object for we load the data
	
	
	
	protected function calcStartDaysSinceToday(){
		$start = $this->timestampStart;
		$now = time();
	
		$d =  \DateTime::createFromFormat("Y-m-d H:i", $start)->getTimeStamp();
		$days_between = ceil(abs($now - $d) / 86400);
	
		return $days_between;
	}
	
	protected function isStartDateToEarly(){
		$days_visiblity = Helper::getReceptionVisibilityDays();
		$days_between = $this->calcStartDaysSinceToday();
		return $days_between > $days_visiblity;
	}
	
	
	/**
	 * cutler győr-ben a nap záráshoz ezt nyomtatjuk ki
	 * Ez a metódus csak akkor használható, ha csak ez a statisztika kell
	 * */
	public function readMixed(){
		$this->readProductsByCategory();
		$this->readTicketStas();
		$this->readMoneyMovements();
	}
	
	public function readTotalEasy(){
		$this->readTicketMoney();
		$this->readProductsMoney();
		$this->readMoneyMovementMoney();
		$this->calcTotal();
	}
	
	public function readTotalDetailed(){
		$this->readTickets();
        $this->readProducts();
        $this->readMoneyMovements();
	}
	public function readTotalMedium(){
		$this->readProductsByCategory();
        $this->readProductsByCategoryDetailed();
        $this->readTicketStas();
        $this->readMoneyMovementsStats();
	}
	
    public function loadFilters($transfer){
    	 $this->start = $transfer->start;
		 $this->end = $transfer->end;
		 $this->id_account = $transfer->id_account;
		 $this->id_user = $transfer->id_user;
		 $this->types = $transfer->types;
		 $this->type = $transfer->type;
		 $this->timestampStart = $transfer->timestampStart;
		 $this->timestampEnd = $transfer->timestampEnd;
    }
    
    public function loadAccountState($accountState){
    	$this->mode = 'accountstate';
    	$this->accountState = $accountState;
    	$this->start = $accountState->start_date;
    	$this->end = $accountState->created_at;
    	$this->timestampStart = $accountState->start_date;
    	$this->timestampEnd =$accountState->created_at;
    	$this->id_account =  $accountState->id_account;
    	$this->id_user = $accountState->id_user;
    }
    
    public function readModeAccountState(){
    	$this->readTotalEasy ();
    	$this->readTotalDetailed ();
    	$this->readTotalMedium ();
    	
    	$this->readCassaOpen();
    	$this->calcTotalWithCassaOpen();
    	
    	$this->showWithCassaOpen = true;
    }
    
	public function isModeAdmin(){
		return $this->mode == 'admin';
	}
	
	public function isModeAccountState(){
		return $this->mode == 'accountstate';
	}
	
	public function isModeReception(){
		return $this->mode == 'reception';
	}
    
    public function calcTotal(){
    	$this->total = 0;
    	$this->total += $this->ticketMoney;
    	$this->total += $this->productMoney;
    	$this->total += $this->moneyMovementMoneis;
    }
    public function calcTotalNetto(){
    	$this->totalNetto = 0;
    	$this->totalNetto += $this->ticketMoney;
    	$this->totalNetto += $this->productMoneyNetto;
    	$this->totalNetto += $this->moneyMovementMoneis;
    }
    
    protected function readCassaOpen(){
    	if ( isset($this->accountState) && $this->accountState->isTypeClose() && isset($this->accountState->prev_state) ){
			$this->cassaOpen =   AccountState::findOne(['id_account_state' => $this->accountState->prev_state]);  		
    	}
    	
    }
    
    protected function calcTotalWithCassaOpen(){
    	$this->totalWithCassa = 0;
    	$this->totalWithCassa += $this->total;
    	if ( isset($this->cassaOpen ) ){
    		$this->totalWithCassa += $this->cassaOpen->money;
    	}
    
    }
    
    
    public function addAccountConstraint($query){
    	
    	if ( $this->isModeAccountState() ){
    		$query->andWhere(['account.type' => Account::TYPE_ALL ]);
    		
    	}else if (!$this->isModeAdmin() || !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 ]);
	    	
	    	if (   RoleDefinition::isReception() || !$this->isModeAdmin()){
	    		$query->andWhere(['transfer.paid_by' => Yii::$app->user->id ]);
	    	}
	    	
	    	
	    	$query->andWhere(['account.type' => Account::TYPE_ALL ]); 
    	}
    	
    }
    
    /**
     * add common transfer conditions.
     * mode and role will be used to build to correct condition
     * */
    public function addQueryFilters($query){
    	$query->innerJoin("account", "transfer.id_account = account.id_account");
    	
    	$this->addAccountConstraint($query);
    	
    	$query->andFilterWhere([
    			'transfer.id_account' => $this->id_account,
    			'transfer.type' => $this->type,
    			'transfer.paid_by' => $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]);
    	
    	if ( $this->isModeReception() || $this->isModeAccountState() ){
    		$query->andWhere(['transfer.payment_method' => Transfer::PAYMENT_METHOD_CASH]);
    	}
    	
    	if ( !RoleDefinition::isAdmin() ){
    		/*
    		if ( $this->isStartDateToEarly() ){
    			 
    			
    			$time = date( "Y-m-d H:i:s", strtotime("today -3 day") );
    			 
    			$start_date_condition = ['or',[ '>=', 'transfer.created_at', $time ] ,[ '>=', 'transfer.paid_at', $time]   ];
    		
    			$query->andFilterWhere( $start_date_condition );
    			 
    		}
    		*/
    	}
    	 
    }
    
    
    public function readTicketStas(){
    
    	$query = (new \yii\db\Query());
    	$query->select(['ticket_type.name as ticket_type_name' , 'coalesce(sum(abs(transfer.count)),0) AS ticket_count', '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");
    	$query->innerJoin("ticket_type", "ticket.id_ticket_type = ticket_type.id_ticket_type");
    	
    	$query->groupBy(['ticket_type.id_ticket_type','ticket_type.name']);
    	$this->addQueryFilters($query);
    	
    
    	$this->ticketStats = $query->all();
    }
    
    
    public 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);
    	$this->ticketMoney = $query->scalar();
    }
    
    public function readTicketStasByUser(){
    
    	$query = (new \yii\db\Query());
    	$query->select([ 'user.id as user_id','user.username as user_username','ticket_type.name as ticket_type_name' , 'coalesce(sum(abs(transfer.count)),0) AS ticket_count', '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");
    	$query->innerJoin("ticket_type", "ticket.id_ticket_type = ticket_type.id_ticket_type");
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	
    	$query->groupBy([ 'user.id as user_id','user.username as user_username','ticket_type.id_ticket_type','ticket_type.name']);
    	$this->addQueryFilters($query);
    
    	$this->ticketStatsByUser = $query->all();
    }
    
    
    public function readTicketMoneyByUser(){
    	 
    	$query = (new \yii\db\Query());
    	$query->select(['user.id as user_id','user.username as user_username',' 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");
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	$query->orderBy(['user.username' => SORT_ASC]);
    	$this->addQueryFilters($query);
    	$this->ticketMoneyByUser = $query->all();
    	$this->ticketMoneyByUser = $this->toArrayByUser($this->ticketMoneyByUser);
    	return $this->ticketMoneyByUser;
    }
    
    public function readProductsByCategory(){
    
    	 
    	$query = (new \yii\db\Query());
    	$query->select(['coalesce(sum(transfer.money),0) AS product_money', 'coalesce(sum(transfer.count),0) as category_count', '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();
    	 
    }
    
    
    public function readProductsByCategoryDetailed(){
    
    	$formatted = [];
    	$formatted['categories'] = [];
    	$formatted['total'] = 0;
    	$prevCategory = null;
    	$curCategory = null;
    	
    	$category = null;
    
    	$query = (new \yii\db\Query());
    	$query->select(['product_category.id_product_category as product_category_id','product_category.name as product_category_name', 'product.name as product_name' ,'coalesce(sum(transfer.money),0) AS product_money', 'coalesce(sum(transfer.count),0) as product_count']);
    	$query->from('transfer');
    	$query->groupBy(['product.id_product','product.name','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");
    	$query->orderBy(['product_category.name'  => SORT_ASC,'product.name'  => SORT_ASC]);
    	$this->addQueryFilters($query);
    
    	$result = $query->all();
    	
    	foreach ($result as $row){
    		$curCategory = $row['product_category_id'];
    		if ( $curCategory  != $prevCategory ){
    			//store last category
    			if ( $category != null ){
    				$formatted['categories'][] = $category;
    			}
    			$prevCategory = $curCategory;
    			//create new category
    			$category = [];
    			$category['category'] = [];
    			$category['category']['name'] = $row['product_category_name'];
    			$category['category']['id'] = $row['product_category_id'];
    			$category['products'] = [];
    			$category['total'] = 0;
    			
    		}
    		$category['products'][] = $row;
    		$category['total'] += $row['product_money'];
    		$formatted['total'] += $row['product_money'];
    			
    	}
    	
    	if ( $category != null ){
    		$formatted['categories'][]= $category;
    	}
    	
    	$this->productsByCategory = $formatted;
    
    }
    
    public function readProductsMoney(){
    
    	 
    	$query = (new \yii\db\Query());
    	$query->select(['coalesce(sum(transfer.money),0) AS product_money' ]);
    	$query->from('transfer');
    	$query->andWhere(['transfer.type' => Transfer::TYPE_PRODUCT]);
    	$query->innerJoin("sale", "sale.id_sale = transfer.id_object");
    	$this->addQueryFilters($query);
    	 
    	$this->productMoney  = $query->scalar();
    	 
    }
    
    public function readProductsMoneyByUser(){
    
    	 
    	$query = (new \yii\db\Query());
    	$query->select(['user.id as user_id','user.username as user_username','coalesce(sum(transfer.money),0) AS product_money' ]);
    	$query->from('transfer');
    	$query->andWhere(['transfer.type' => Transfer::TYPE_PRODUCT]);
    	$query->innerJoin("sale", "sale.id_sale = transfer.id_object");
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	$query->groupBy([ 'user.id as user_id','user.username as user_username','ticket_type.id_ticket_type','transfer.money']);
    	$this->addQueryFilters($query);
    	 
    	$this->productMoneyByUser  = $query->all();
    	 
    }
    public function readProductsMoneyNetto(){
    
    	 
    	$query = (new \yii\db\Query());
    	$query->select(['coalesce(sum(transfer.count * GREATEST((  product.sale_price - coalesce(product.purchase_price,0)),0)),0) AS product_money' ]);
    	$query->from('transfer');
    	$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");
    	$this->addQueryFilters($query);
    	 
    	$this->productMoneyNetto  = $query->scalar();
    	 
    }
    public function readProductsMoneyNettoByUser(){
    
    	 
    	$query = (new \yii\db\Query());
    	$query->select(['coalesce(sum(transfer.count * GREATEST((  product.sale_price - coalesce(product.purchase_price,0)),0)),0) AS product_money' ]);
    	$query->from('transfer');
    	$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("user", "transfer.paid_by = user.id");
    	$query->groupBy([ 'user.id as user_id','user.username as user_username','ticket_type.id_ticket_type','transfer.count' ,'product.sale_price','product.purchase_price']);
    	$this->addQueryFilters($query);
    	 
    	$this->productMoneyNetto  = $query->all();
    	 
    }
    
    
    public function readMoneyMovementMoney(){
    	$query = (new \yii\db\Query());
    	$query->select([' coalesce(sum( case when transfer.direction = ' . Transfer::DIRECTION_IN. ' then transfer.money else -1 * transfer.money end  ),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->scalar();
    }
    public function readMoneyMovementsStats(){
    	$query = (new \yii\db\Query());
    	$query->select([ 'money_movement.type as money_movement_type', ' coalesce(count(transfer.id_transfer),0) AS money_movement_count', 'coalesce(sum( case when transfer.direction = ' . Transfer::DIRECTION_IN. ' then transfer.money else -1 * transfer.money end  ),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");
    	$query->groupBy(['money_movement.type']);
    	$this->addQueryFilters($query);
    
    	$this->moneyMovementsByType  = $query->all();
    	for  ($i = 0; $i < count($this->moneyMovementsByType) ;$i++ ){
    		$this->moneyMovementsByType[$i]['name'] = MoneyMovement::typeName($this->moneyMovementsByType[$i]['money_movement_type']);
    	}
    }
    public function readMoneyMovementMoneyByUser(){
    	$query = (new \yii\db\Query());
    	$query->select(['user.id as user_id','user.username as user_username',' coalesce(sum( case when transfer.direction = ' . Transfer::DIRECTION_IN. ' then transfer.money else -1 * transfer.money end  ),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");
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	$query->groupBy([ 'user.id as user_id','user.username as user_username'  ]);
    	 
    	$this->addQueryFilters($query);
    
    	$this->moneyMovementMoneisByUser  = $query->scalar();
    }
    public function readMoneyMovementsStatsByUser(){
    	$query = (new \yii\db\Query());
    	$query->select([ 'user.id as user_id','user.username as user_username','money_movement.type as money_movement_type', ' coalesce(count(transfer.id_transfer),0) AS money_movement_count', 'coalesce(sum( case when transfer.direction = ' . Transfer::DIRECTION_IN. ' then transfer.money else -1 * transfer.money end  ),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");
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	$query->groupBy([ 'user.id as user_id','user.username as user_username','money_movement.type']);
    	$this->addQueryFilters($query);
    
    	$this->moneyMovementsByTypeByUser  = $query->all();
    	for  ($i = 0; $i < count($this->moneyMovementsByTypeByUser) ;$i++ ){
    		$this->moneyMovementsByTypeByUser[$i]['name'] = MoneyMovement::typeName($this->moneyMovementsByTypeByUser[$i]['money_movement_type']);
    	}
    	
    	$this->moneyMovementsByTypeByUser = $this->toArrayByUser($this->moneyMovementsByTypeByUser);
    	
    }
    
    public function readTickets(){
    	$query = (new \yii\db\Query());
    	$query->select([ 'customer.name as customer_name', 'user.username as user_name',  'account.name as account_name','ticket_type.name as ticket_type_name' , 'transfer.count AS ticket_count', 'transfer.money AS ticket_money','transfer.item_price AS ticket_item_price', 'transfer.created_at as ticket_created_at','transfer.paid_at as ticket_paid_at']);
    	$query->from('transfer');
    	$query->andWhere(['transfer.type' => Transfer::TYPE_TICKET]);
    	$query->innerJoin("ticket", "ticket.id_ticket = transfer.id_object");
    	$query->innerJoin("customer","customer.id_customer = transfer.id_customer");
    	$query->innerJoin("ticket_type", "ticket.id_ticket_type = ticket_type.id_ticket_type");
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	$query->orderBy(['transfer.created_at'  => SORT_ASC]);
    	$this->addQueryFilters($query);
    	 
    	
    	$this->tickets = $query->all();
    	
    	for  ($i = 0; $i < count($this->tickets) ;$i++ ){
    		$this->tickets[$i]['ticket_created_at'] = Yii::$app->formatter->asDatetime($this->tickets[$i]['ticket_created_at'], 'yyyy.MM.dd HH:mm:ss');
    		$this->tickets[$i]['ticket_paid_at'] =  empty($this->tickets[$i]['ticket_paid_at'] ) ? '-' : Yii::$app->formatter->asDatetime($this->tickets[$i]['ticket_paid_at'], 'yyyy.MM.dd HH:mm:ss');
    	}
    	
    }
    
    public function readProducts(){
     
    	$query = (new \yii\db\Query());
    	$query->select([ 'user.username as user_name','account.name as account_name' , 'product_category.name as product_category_name', 'product.name as product_name', 'transfer.money AS product_money', 'transfer.count AS product_count', 'transfer.money AS product_money','transfer.item_price AS product_item_price', 'transfer.created_at as product_created_at','transfer.paid_at as product_paid_at']);
    	$query->from('transfer');
    	$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");
    	
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	$query->orderBy(['transfer.created_at'  => SORT_ASC]);
    	$this->addQueryFilters($query);
    	 
    	$this->products  = $query->all();
    	 
    	for  ($i = 0; $i < count($this->products) ;$i++ ){
    		$this->products[$i]['product_created_at'] = Yii::$app->formatter->asDatetime($this->products[$i]['product_created_at'], 'yyyy.MM.dd HH:mm:ss');
    		$this->products[$i]['product_paid_at'] =  empty($this->products[$i]['product_paid_at'] ) ? '-' : Yii::$app->formatter->asDatetime($this->products[$i]['product_paid_at'], 'yyyy.MM.dd HH:mm:ss');
    	}
    	 
    }
    
    public function readMoneyMovements(){
    	$query = (new \yii\db\Query());
    	$query->select([ 'user.username as user_name','account.name as account_name', 'transfer.direction as transfer_direction' ,'money_movement.type as money_movement_type', 'transfer.money AS money_movement_money', 'money_movement.name as money_movement_name','transfer.created_at as money_movement_created_at', 'money_movement.comment as money_movement_comment' ]);
    	$query->from('transfer');
    	$query->andWhere(['transfer.type' => Transfer::TYPE_MONEY_MOVEMENT_OUT]);
    	$query->innerJoin("money_movement", "money_movement.id_money_movement = transfer.id_object");
    	$query->innerJoin("user", "transfer.paid_by = user.id");
    	$query->orderBy(['transfer.created_at'  => SORT_ASC]);
    	$this->addQueryFilters($query);
    
    	$this->moneyMovements  = $query->all();
    	 
    	for  ($i = 0; $i < count($this->moneyMovements) ;$i++ ){
    		$this->moneyMovements[$i]['money_movement_type_name'] = MoneyMovement::typeName($this->moneyMovements[$i]['money_movement_type']);
    		$this->moneyMovements[$i]['money_movement_created_at'] = Yii::$app->formatter->asDatetime($this->moneyMovements[$i]['money_movement_created_at'], 'yyyy.MM.dd HH:mm:ss');
    		$this->moneyMovements[$i]['signed_money'] = Transfer::toSignedMoney($this->moneyMovements[$i]['transfer_direction'],$this->moneyMovements[$i]['money_movement_money']);
    	}
    }
    
    
    protected function toArrayByUser($flat, $totalField = null){
    	$result = [];
    	$id_user_prev = null;
    	$id_user = null;
    	$arr;
    	
    	foreach ( $flat as $item){
	    	$id_user = $item['user_id'];
    		 
    			if ($id_user_prev == null || $id_user != $id_user_prev){
    				if ($id_user_prev != null ){
    					$result[] = $arr;
    				}
    				$arr =[];
    				$arr['username'] = $item['user_username'];
    				$arr['items'] = [];
    				$arr['user_id'] = $id_user;
    				$arr['total'] = 0;
    			}
    			
   			$id_user_prev = $id_user;
   			
   			$arr['items'][] = $item;
   			if ( isset($totalField)){
   				$arr['total'] += $item[$totalField];
   			}
   			
    	}
    	
    	if ( isset($arr )  && count($arr) > 0 ){
    		$result[] = $arr;
    	}
    	return $result;
    }
    
}
