<?php

namespace common\models;

use Yii;
use common\components\Helper;

/**
 * This is the model class for table "card".
 *
 * @property integer $id_card
 * @property string $number
 * @property integer $status
 * @property integer $type
 * @property integer $flag
 * @property string $created_at
 * @property string $updated_at
 */
class Card extends \common\models\BaseFitnessActiveRecord
{
	
	const STATUS_DELETED = 0;
	const STATUS_ACTIVE = 10;
	
	const TYPE_RFID = 10;
	const TYPE_QRCODE = 20;
	const TYPE_BARCODE = 30;
	const TYPE_OLD = 40;
	const TYPE_EMPLOYEE = 50;
	
	
	public static $FLAG_TICKET = 0;
	public static $FLAG_STATUS = 1;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'card';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['number', 'type','status'], 'required'],
            [['status', 'type'], 'integer'],
            [['number'], 'string', 'max' => 20],
            [['rfid_key'], 'string', 'max' => 25],
            [['number'], 'unique' ],
        	[['rfid_key','number'] , 'validateAscii']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_card' => Yii::t('common/card', 'Id Card'),
            'number' => Yii::t('common/card', 'Number'),
            'rfid_key' => Yii::t('common/card', 'RFID key'),
            'status' => Yii::t('common/card', 'Status'),
            'type' => Yii::t('common/card', 'Type'),
            'created_at' => Yii::t('common/card', 'Created At'),
            'updated_at' => Yii::t('common/card', 'Updated At'),
        ];
    }
    
    
    public function validateAscii($attribute,$params){
    	if ( !$this->hasErrors($this->$attribute)){
    		$this->$attribute = Helper::fixAsciiChars($this->$attribute);
    		Yii::info(" $attribute converted to: " . $this->$attribute);
    	}
    }
    
    static function statuses() {
    	return [
    			self::STATUS_ACTIVE => Yii::t('common/card', 'Active'),
    			self::STATUS_DELETED => Yii::t('common/card', 'Inactive'),
    	];
    }
    
    public function getStatusHuman(){
    	$result = null;
    	$s = self::statuses($this->status);
    	if ( array_key_exists($this->status, $s)){
    		$result = $s[$this->status];
    	}
    	return $result;
    }
    public static function toStatusName($status , $def = ""){
    	return Helper::getArrayValue(self::statuses(), $status, $def);
    }
    public static function toTypeName($type , $def = ""){
    	return Helper::getArrayValue(self::types(), $type, $def);
    }
    
    static function types() {
    	return [
    			self::TYPE_RFID => Yii::t('common/card', 'RFID'),
    			self::TYPE_QRCODE => Yii::t('common/card', 'QRCODE'),
    			self::TYPE_BARCODE => Yii::t('common/card', 'BARCODE'),
    			self::TYPE_OLD => Yii::t('common/card', 'OLD'),
    			self::TYPE_EMPLOYEE => Yii::t('common/card', 'Munkatárs'),
    	];
    }
    
    public function getTypeHuman(){
    	$result = null;
    	$s = self::types($this->type);
    	if ( array_key_exists($this->type, $s)){
    		$result = $s[$this->type];
    	}
    	return $result;
    }
    
    public function isInactive(){
    	return $this->status == self::STATUS_DELETED;
    }
    
    public static function readCard($number,$free = null){
    	$card = null;
    	$query = Card::find()
    			->leftJoin(Customer::tableName(), 'card.id_card = customer.id_customer_card ' );
//     			->andWhere(['number'=>$number ]);
    	
    	Card::addCardNumberCondition($query, $number);
    			
    			
    	if ( isset($free) ){
    		if ( $free == true){
    			$query->andWhere('customer.id_customer  is null');
    		}else{
    			$query->andWhere('customer.id_customer  is not null');
    		}
    	}
    	
    	$cards = $query->all();
    	
    	if ( count($cards) == 1){
    		$card = $cards[0];
    	}
    	return $card;
    }
    
    
    public function getCustomer(){
    	return $this->hasOne(Customer::className(), ['id_customer_card' => 'id_card']);
    }
    
    public function getCustomerName(){
    	$name = null;
    	$customer = $this->customer;
    	if ( $this->customer != null){
    		$name = $this->customer->name;
    	}
    	return $name;
    }
    
    public static function addCardNumberCondition($query,$number, $field_number = "card.number",$field_rfid_key = "card.rfid_key"){
    	$query->andWhere(['or',
    			['and',[ 'in',$field_number , [$number]],"trim(coalesce(card.number, '')) <>'' " ],
    			['and', ['in',$field_rfid_key ,[ $number ] ],"trim(coalesce(card.rfid_key, '')) <>'' "],
    	
    	]);
    }
    
    public static function updateCardFlagTicket($id){
    	if ( !isset($id)){
    		return ;
    	}
    	$db = \Yii::$app->db;
    	$command = $db->createCommand(Ticket::$SQL_UPDATE_CARD,[':id' => $id]);
    	$command->execute();
    }
    
    public  function beforeSave($insert) {
    	if (parent::beforeSave($insert)){
	    	$this->flag = Helper::setBit($this->flag, Card::$FLAG_STATUS, ( $this->status != Card::STATUS_ACTIVE));
	    	return true;
    	}
    	return false;
    }
    
    
    public function getFlagText(){
    	return Helper::getArrayValue(DoorLog::getCardFlagTexts(), $this->flag, "Ismeretlen");
    }
    
}
