<?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;

/**
 * TicketSearch represents the model behind the search form about `common\models\Ticket`.
 */
class TicketSearch 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;
	
	
    /**
     * @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 = Ticket::find();

        Helper::queryAccountConstraint($query, 'ticket.id_account');
        
        $query->with('ticketType' );
        $query->with('user');
        $query->with('customer');
        
        
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        	'sort' =>[
				'defaultOrder' => ['end' => SORT_DESC],
        		'attributes' => ['end']
     	   ]
        ]);

        $this->load($params);

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

        $query->andFilterWhere([
            'id_user' => $this->id_user,
            'id_ticket_type' => $this->id_ticket_type,
            'id_account' => $this->id_account,
        	'id_card' => $this->id_card,
        	'id_ticket' => $this->id_ticket,
        	'status' => $this->status
        ]);

        
        
        $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,$this->id_card);
    	$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);
    	}
    }
    
}
