<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Transfer;
use yii\base\Object;
use yii\db\Query;
use yii\db\Expression;
use common\models\Account;

use yii\helpers\ArrayHelper;
use common\models\MoneyMovement;
use common\components\RoleDefinition;
use common\components\Helper;
/**
 * TransferSearch represents the model behind the search form about `common\models\Transfer`.
 */
class TransferTicketSearch extends Transfer
{
	
	/**
	 * if mode is recepion, date restriction will be used
	 * if mode is admin, date restriction will be used based on user role
	 * */
	public $mode  = 'reception';
	
	public $start;
	public $end;
	
	public $timestampStart;
	public $timestampEnd;
	
	
	
// 	public $totalsCreatedAt = ['total' => 0, 'accounts' =>[] ];
// 	public $totalsCreatedAtNotPaid= ['total' => 0, 'accounts' =>[]];
// 	public $totalsCreatedAtPaid= ['total' => 0, 'accounts' =>[]];
// 	public $totalsPaidAt= ['total' => 0, 'accounts' =>[]];
// 	public $totalsPaidAtNotCreatedAt= ['total' => 0, 'accounts' =>[]];
	
	
	public $totals;
	
	public $accounts;
	
	public $types;
	
	public $users;
	
	
	/**
	 * all money gained with ticket sell
	 * */
	public $ticketMoney;
	/**
	 * total gained money
	 * */
	public $total;
	
	/**
	 * ticket sale statisitc
	 * */
	public $ticketStats;
	
	public $tickets;
	
	public $customer;
	
	public $ticketTypes;
	public $id_ticket_type;
	
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        		
        	[[ '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' ],
        		
			[ [ 'id_account','id_user' ,'id_ticket_type'  ] , 'integer'],
        	['types', 'each', 'rule' => ['integer']],
        	[['customer' ] , 'string' , 'max' => 200 ]
        ];
    }

    
    public function attributeLabels(){
    	$result = parent::attributeLabels();
    	$result['id_ticket_type'] = 'Bérlet típus';
    	$result['customer'] = 'Vendég';
    	return $result;
    }
    

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Transfer::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        
        
        $this->load($params);
        

        if (!$this->validate()) {
        }
         
        
        
        $this->readTicketMoney();
        $this->calcTotal();
        
        $this->readTicketStas();
        
        
        $this->readTickets();
        
    }
    
    
    
    protected function calcTotal(){
    	$this->total = 0;
    	$this->total += $this->ticketMoney;
    }
    
    
    protected function addAccountConstraint($query){
    	$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()){
    		$query->andWhere(['transfer.id_user' => Yii::$app->user->id ]);
    	}
    	
    	$query->andWhere(['account.type' => Account::TYPE_ALL ]);
    	
    }
    
    protected 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,
    			'ticket_type.id_ticket_type' => $this->id_ticket_type,
    	]);
    	
    	$query->andFilterWhere( ['or' , ['transfer.id_user' => $this->id_user ] , ['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->andFilterWhere(['like' , 'LOWER(customer.name)' , strtolower( $this->customer ) ]);
    	 
    	$query->andWhere(['transfer.status' => Transfer::STATUS_PAID]);
    	 
    	$this->restrictStartDate($query);
    }
    
    
    function restrictStartDate($query){
    	$needRestriction = false;
    	if ( $this->mode == 'admin'){
    		$needRestriction  = !RoleDefinition::isAdmin( ) ;
    	}else{
    		$needRestriction = true;
    	}
    	
    	if ( $needRestriction ){
    		Helper::restrictIfNotAdminTheStartDate($query, $this->timestampStart);
    	}
    	
    }
    
    protected 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->innerJoin("customer","customer.id_customer = transfer.id_customer");
    	$query->groupBy(['ticket_type.id_ticket_type','ticket_type.name']);
    	$this->addQueryFilters($query);
    	
    
    	$this->ticketStats = $query->all();
    }
    
    
    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");
    	$query->innerJoin("ticket_type", "ticket.id_ticket_type = ticket_type.id_ticket_type");
    	$query->innerJoin("customer","customer.id_customer = transfer.id_customer");
    	$this->addQueryFilters($query);
    	$this->ticketMoney = $query->scalar();
    }
    
    
    
    
    
    
    
    protected function readTickets(){
    	$query = (new \yii\db\Query());
    	$query->select([  'paid_by.username as paid_by_name', 'ticket.id_ticket as ticket_id_ticket', 'customer.name as customer_name', 'user.username as user_name',  'account.name as account_name','ticket_type.name as ticket_type_name' ,'ticket.status as ticket_status', '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.id_user = user.id");
    	$query->leftJoin("user as paid_by", "transfer.paid_by = paid_by.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');
    	}
    	
    }
    
    
    
    
}
