<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Ticket;
use common\components\Helper;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\db\Query;
use common\models\Transfer;
use yii\helpers\VarDumper;

/**
 * TicketSearch represents the model behind the search form about `common\models\Ticket`.
 * @property commom\models\Customer $customer
 */
class TicketSearchCustomer extends Ticket
{
	
	public $timestampStart;
	public $timestampEnd;
	
	public $users;
	public $accounts;
	public $ticketTypes;
	
	public $valid_in_interval;
	public $created_in_interval;
	public $expire_in_interval;
	
	public $statistics;
	public $statisticsTotal;
	
	public $customer; //constructor param
	
 
	
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[  'id_ticket', 'id_user', 'id_ticket_type', 'id_account','status' ], 'integer'],
            [[ 'start', ], 'date'  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd'  ],
        	[[ 'end' , ], 'date'    , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd' ],
       		[['valid_in_interval','created_in_interval','expire_in_interval'],'boolean'] ,
        		
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }
    
    public function attributeLabels(){
    	return ArrayHelper::merge(parent::attributeLabels(), [
			'start' => Yii::t('backend/ticket','Start of interval'),
			'end' => Yii::t('backend/ticket','End of interval'),
			'valid_in_interval' => Yii::t('backend/ticket','Valid in interval'),
			'created_in_interval' => Yii::t('backend/ticket','Created in interval'),
			'expire_in_interval' => Yii::t('backend/ticket','Expire in interval'),
    	]);
    }

    public function afterValidate(){
        
    	if ( !isset($this->timestampStart)) {
        	$this->timestampStart ='1900-01-01';
        }
        
        if ( !isset($this->timestampEnd)) {
        	$this->timestampEnd ='3000-01-01';
        }
    	
    }
    
    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query =  new Query();
        
        $query->select([
        	'ticket.id_ticket as ticket_id_ticket',
        	'account.name as account_name',
        	'card.number as card_number',
        	'ticket_type.name as ticket_type_name',
        	'ticket.start as ticket_start',
        	'ticket.end as ticket_end',
        	'ticket.max_usage_count as ticket_max_usage_count',
        	'ticket.usage_count as ticket_usage_count',
        	'user.username as user_username',
        	'paid_by.username as paid_by_username',
        	'ticket.status as ticket_status',
        	'ticket.price_brutto as ticket_price_brutto',
        		
        ]);
        $query->from('ticket');
        $query->innerJoin('ticket_type', 'ticket_type.id_ticket_type = ticket.id_ticket_type');
        $query->innerJoin('transfer', 'transfer.id_object = ticket.id_ticket and transfer.type = ' . Transfer::TYPE_TICKET);
        $query->innerJoin('account', 'account.id_account = ticket.id_account');
        $query->innerJoin('user', 'user.id =  transfer.id_user');
        $query->leftJoin('user as paid_by', 'paid_by.id =  transfer.paid_by');
        $query->leftJoin('card', 'ticket.id_card =  card.id_card');
        $query->leftJoin('customer', 'customer.id_customer=  transfer.id_customer');
       

        Helper::queryAccountConstraint($query, 'ticket.id_account');
        
        
        
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        	'sort' =>[
// 				'defaultOrder' => ['end' => SORT_DESC],
        		'attributes' => [
        					
//         		'end',
        		'ticket_id_ticket' => [
   					'asc' => ['ticket.id_ticket' => SORT_ASC ],
        			'desc' => ['ticket.id_ticket' => SORT_DESC],
        		],
        		'ticket_start' => [
   					'asc' => ['ticket.start' => SORT_ASC ],
        			'desc' => ['ticket.start' => SORT_DESC],
        		],
        		'ticket_end' => [
   					'asc' => ['ticket.end' => SORT_ASC ],
        			'desc' => ['ticket.end' => SORT_DESC],
        		],
        		'user_username' => [
   					'asc' => ['user.username' => SORT_ASC ],
        			'desc' => ['user.username' => SORT_DESC],
        		],
        		'paid_by_username' => [
   					'asc' => ['paid_by.username' => SORT_ASC ],
        			'desc' => ['paid_by.username' => SORT_DESC],
        		],
        		'ticket_type_name' => [
   					'asc' => ['ticket_type.name' => SORT_ASC ],
        			'desc' => ['ticket_type.name' => SORT_DESC],
        		],
        		'account_name' => [
   					'asc' => ['account.name' => SORT_ASC ],
        			'desc' => ['account.name' => SORT_DESC],
        		],
        		'ticket_status' => [
   					'asc' => ['ticket.status' => SORT_ASC ],
        			'desc' => ['ticket.status' => SORT_DESC],
        		],
        		'ticket_price_brutto' => [
   					'asc' => ['ticket.price_brutto' => SORT_ASC ],
        			'desc' => ['ticket.price_brutto' => SORT_DESC],
        		],
//         		'id_card' => [
//    					'asc' => ['card.number' => SORT_ASC ],
//         			'desc' => ['card.number' => SORT_DESC],
//         		],
        			
        				
        		]
     	   ]
        ]);

        $this->load($params);

        
        if (!$this->validate()) {
            return $query;
        }
        

        $query->andWhere( ['transfer.id_customer' => $this->customer->id_customer ]);
        
        $query->andFilterWhere([
            'ticket.id_user' => $this->id_user,
            'ticket.id_ticket_type' => $this->id_ticket_type,
            'ticket.id_account' => $this->id_account,
        	'ticket.id_card' => $this->id_card,
        	'ticket.id_ticket' => $this->id_ticket,
        	'ticket.status' => $this->status
        ]);

       // $query->andWhere(['customer.id_customer' => $this->customer->id_customer]);
        
        
        $all = (!($this->valid_in_interval)  && !($this->expire_in_interval) && !($this->created_in_interval) )
        		||
        		($this->valid_in_interval == true && $this->expire_in_interval == true && $this->created_in_interval);
        
       $dateConditions = [];
       $start = $this->timestampStart;
       $end = $this->timestampEnd;
       
        if( $all || $this->created_in_interval ){
        	$dateConditions[] = Helper::queryInIntervalRule('ticket.created_at', $start, $end);
        }
        		
        if ( $all || $this->valid_in_interval ){
        	$dateConditions[] = Helper::queryValidRule('ticket.start', 'ticket.end', $start, $end);
        }
        
        if ( $all || $this->expire_in_interval ){
        	$dateConditions[] =  Helper::queryExpireRule('ticket.start', 'ticket.end', $start, $end);
        }
        
        if ( count($dateConditions) == 1 ){
        	$query->andWhere($dateConditions[0]);
        }else if ( count($dateConditions) > 1 ){
        	$cond = ['or'];
        	foreach ($dateConditions as $c){
        		$cond[] = $c;
        	}
        	$query->andWhere($cond);
        }

        return $dataProvider;
    }
    
    
    
    public function searchTotals(){
    	$query = Ticket::mkStatisticQuery($this->timestampStart, $this->timestampEnd);
    	$query->andWhere(["transfer.id_customer" => $this->id ]);
    	$this->statistics = $query->all();
    	
    	$this->statisticsTotal =[
			'valid' => 0,
			'created' => 0,
			'created_at_money' => 0,
			'expired' => 0,
    	];
    	
   		$this->statisticsTotal['valid'] = array_sum(array_column($this->statistics, 'valid'));
   		$this->statisticsTotal['created'] = array_sum(array_column($this->statistics, 'created'));
   		$this->statisticsTotal['created_money'] = array_sum(array_column($this->statistics, 'created_money'));
   		$this->statisticsTotal['expired'] = array_sum(array_column($this->statistics, 'expired'));
    }
    
    
    public static function mkSearchCondition( $timestampStart, $timestampEnd,  $id_user,$id_ticket_tpye,$id_account,$valid_in_interval ,$expire_in_interval,$created_in_interval ){
    	$query = Ticket::find();
    	
    	Helper::queryAccountConstraint($query, 'ticket.id_account');
    	
    	$query->with('ticketType' );
    	$query->with('user');
    	$query->with('customer');
    	
    	$query->andFilterWhere([
    			'id_user' => $id_user,
    			'id_ticket_type' => $id_ticket_type,
    			'id_account' => $id_account,
    			]);
    	
    	$all = (!($valid_in_interval)  && !($expire_in_interval) && !($created_in_interval) )
    	||
    	($valid_in_interval == true && $expire_in_interval == true && $created_in_interval);
    	
    	$dateConditions = [];
    	$start = $timestampStart;
    	$end = $timestampEnd;
    	 
    	if( $all || $created_in_interval ){
    		$dateConditions[] = Helper::queryInIntervalRule('ticket.created_at', $start, $end);
    	}
    	
    	if ( $all || $valid_in_interval ){
    		$dateConditions[] = Helper::queryValidRule('ticket.start', 'ticket.end', $start, $end);
    	}
    	
    	if ( $all || $expire_in_interval ){
    		$dateConditions[] =  Helper::queryExpireRule('ticket.start', 'ticket.end', $start, $end);
    	}
    	
    	if ( count($dateConditions) == 1 ){
    		$query->andWhere($dateConditions[0]);
    	}else if ( count($dateConditions) > 1 ){
    		$cond = ['or'];
    		foreach ($dateConditions as $c){
    			$cond[] = $c;
    		}
    		$query->andWhere($cond);
    	}
    }
    
}
