<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use common\models\Card;
use common\models\Customer;
use common\models\Ticket;
use common\models\Account;
use common\models\CardSearch;
use common\models\AccountState;
use common\models\Key;
use common\models\CardKeyAssignment;
use common\models\Contract;
use yii\db\Expression;
use common\components\Helper;
use common\models\DoorLog;

/**
 * ContactForm is the model behind the contact form.
 */
class ReceptionForm extends Model
{
    public $number;
	public $card;
	public $customer;
	public $tickets;
    public $defaultAccount;
    public $cardSearchModel;
    public $lastCassaState;
    public $keys;
    public $contract;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['number'], 'required'],
        ];
    }

    
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'verifyCode' => 'Verification Code',
        ];
    }
    
    public function readCard(){
    	
    	$this->number = Helper::fixAsciiChars( $this->number );
    	
    	$query = Card::find();
    	$query->leftJoin("card_key_assignment", 'card.id_card = card_key_assignment.id_card');
    	$query->leftJoin("key", 'key.id_key = card_key_assignment.id_key');
    	
    	$query->andWhere(['or',  
    			['and',[ 'in','card.number' , [$this->number]],"trim(coalesce(card.number, '')) <>'' " ],  
    			['and', ['in','card.rfid_key' ,[ $this->number] ],"trim(coalesce(card.rfid_key, '')) <>'' "],
    			['and',[ 'in','key.number' , [$this->number]],"trim(coalesce(key.number, '')) <>'' " ],  
    			['and', ['in','key.rfid_key' ,[ $this->number] ],"trim(coalesce(key.rfid_key, '')) <>'' "]
    			
    	]);
    	
    	$this->card = $query->one();
    	
    	if ( $this->card == null ){
    		
    	}
    	
    	if ( $this->card != null ){
    		$this->customer = $this->card->customer;
    		$this->readValidTickets();
    		$this->readAssignedKeys();
    		$this->readContract();
    	}
    	
    	$defaultAccount = Account::readDefault();
    	if ( isset($defaultAccount)){
    		$this->defaultAccount = Account::findOne($defaultAccount);
    	}
    	
    	$this->readLastCassaState();
    	$this->cardSearchModel = new CardSearch();
    	
    }
    
    public function mkDoorLog(){
    	
    	if ( !isset($this->card)){
    		return;
    	}
    	
    	$dlog = new DoorLog();
    	$dlog->id_card = $this->card->id_card;
    	
    	if ( isset($this->customer)){
    		$dlog->id_customer = $this->customer->id_customer;
    	}
    	
    	$key = $this->getFirstKey();
    	
    	if ( isset($key)){
    		$dlog->id_key = $key->id_key;
    	}
    	$dlog->direction = 0;
    	$dlog->type = $this->card->type;
    	$dlog->source_app = DoorLog::$SOURCE_APP_FITNESS_ADMIN;
    	
    	$dlog->id_account = Account::readDefault();
    	
    	$dlog->card_flag = $this->card->flag;
    	
    	$dlog->created_at = date('Y-m-d H:i:s');
    	$dlog->save(false);
    }
    
    public function readAssignedKeys(){
    	$query = Key::find();
    	$query->join( 'INNER JOIN', CardKeyAssignment::tableName() , Key::tableName().".id_key = " . CardKeyAssignment::tableName() . ".id_key");
    	$query->andWhere([  "card_key_assignment.id_card" => $this->card->id_card ]);
    	$this->keys = $query->all();
    	
    }
    
    public function getFirstKey(){
    	$result = null;
    	if ( isset($this->keys) && is_array($this->keys) && count($this->keys) > 0 ){
    		$result = $this->keys[0];
    	}
    	return $result;
    }
    
    public function readLastCassaState(){
    	$a = Account::readDefault();
    	if ( isset($a)){
    		$this->lastCassaState = AccountState::find()->andWhere(['account_state.id_account' => $a])
    		->andWhere(['account_state.id_user' => \Yii::$app->user->id] )
    		->orderBy(['account_state.created_at' => SORT_DESC])
    		->limit(1)
    		->one();
    	}
    }
    
    public function readContract(){
    	if ($this->isCardWithCustomer()){
    		
    		$query = Contract::find();
    		$query->andWhere(['id_customer' => $this->customer->id_customer ]);
    		$query->andWhere([ '>=' ,'expired_at' , new Expression("now()") ]);
    		$query->andWhere(["not in" , 'flag' , [Contract::$FLAG_DELETED ]]);
    		$this->contract = $query->one();
    	}
    	
    }
    
    public function hasCassa(){
    	return isset($this->lastCassaState) ;
    }
    
    public function isCassaOpen(){
    	return ( isset($this->lastCassaState)  && $this->lastCassaState->isTypeOpen());
    }
    public function isCassaClose(){
    	return ( isset($this->lastCassaState)  && $this->lastCassaState->isTypeClose());
    }
    
    public function getDefaultAccountName(){
    	$result = "";
    	if ( $this->defaultAccount ){
    		$result = $this->defaultAccount->name;
    	}
    	return $result;
    }
    
    public function readValidTickets(){
    	$this->tickets = Ticket::readActive($this->card);
    }
    
    /**
     * @return true , if card found without customer
     * */
    public function isFreeCard(){
    	$result = isset($this->card) && !isset($this->customer);
    	return $result;
    }
    /**
     * @return true , if card found with customer
     * */
    public function isCardWithCustomer(){
    	$result = isset($this->card) &&  isset($this->customer);
    	return $result;
    }
    
    /**
     * @return true , if card and customer found with at least one valid tickets
     * */
    public function isCustomerWithTicket(){
    	$result = false;
    	if ( isset($this->card) && isset($this->customer) ){
    		if ( isset($this->tickets) && count($this->tickets) > 0 ){
    			$result = true;
    		}
    	}
    	return $result;
    }
    
    public function  isCardWithKey(){
    	$result = false;
    	
    		if ( $this->isCardWithCustomer() ){
    			\Yii::info("isCardWithKey - customer is with card");
    			$key = $this->getFirstKey();
    			\Yii::info("isCardWithKey - key: " . print_r($key, true));
    			if ( isset($key)){
    				$result = true;
    			}
    		}
    	
    	return $result;
    }
    
    /**
     * @return true, if no card and customer found
     * */
    public function isInvalidNumber(){
    	$result = !isset($this->card)  && !isset($this->customer);
    	return $result;
    }
	
    
    public function getCardNumber(){
    	if ( isset($this->card)){
    		return $this->card->number;
    	}
    	return null;
    }
    
    public function getKeysText(){
    	$keyNumbers = [];
    	$result = "-"; 
    	if ( isset($this->keys)){
    		foreach ($this->keys as $k ){
    			$keyNumbers[] = $k->number;
    		}
    		$result = implode(", ",$keyNumbers);
    	}
    	return $result;
    }
    
}
