<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use common\models\CardKeyAssignment;
use common\models\Key;
use yii\helpers\ArrayHelper;
use common\components\Helper;
use common\models\Card;

/**
 * ContactForm is the model behind the contact form.
 */
class KeyToggleForm extends Model
{
    public $key;
    public $card;
    public $customer;
    public $keyModel;
	public $action;
    public $keyCard;
  
    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        	[['key'], 'safe' ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
        ];
    }
    
    public function toggleKey(){
    	$query= Key::find();
    	
    	$this->key = Helper::fixAsciiChars($this->key);
    	
    	$query->andWhere(['or',
    			['and',[ 'in','key.number' , [$this->key]],"trim(coalesce(key.number, '')) <>'' " ],
    			['and', ['in','key.rfid_key' ,[ $this->key ] ],"trim(coalesce(key.rfid_key, '')) <>'' "],
    				
    	]);
    	
    	$this->keyModel = $query->one();
    	
    	if (  isset($this->keyModel) ){
    		$this->keyCard = Card::find()->innerJoin('card_key_assignment','card.id_card = card_key_assignment.id_card')->andWhere('card_key_assignment.id_key = ' .$this->keyModel->id_key)->one();
    		$assignments = CardKeyAssignment::find()->andWhere(['id_key' => $this->keyModel->id_key])->all();
    		if ( count($assignments) > 0){
    			$this->unassign();
    			$this->action = 'unassign';
    		}else{
    			$this->assign();
    		}
    	}else{
    		\Yii::$app->session->setFlash ( 'danger', 'Kulcs nem található!' );
    	}
    }

    public function assign(){
    	if ( isset($this->card) && isset($this->customer) ){
    		$assignments = CardKeyAssignment::find()->andWhere(['id_card' => $this->card->id_card])->all();
    		if ( count($assignments) > 0 ){
    			\Yii::$app->session->setFlash ( 'danger', 'A vendégnél egyszerre csak egy kulcs lehet' );
    		}else{
		    	$assignment  = new CardKeyAssignment();
		    	$assignment->id_card = $this->card->id_card;
		    	$assignment->id_key = $this->keyModel->id_key;
		    	$assignment->id_user = \Yii::$app->user->id;
		    	$assignment->save(false);
		    	\Yii::$app->session->setFlash ( 'success', 'Kulcs kiadva!' );
    		}
    	}else{
    		\Yii::$app->session->setFlash ( 'danger', 'Nincs vendég kiválasztva vagy érvénytelen kártya!' );
    	}
    }
    
    public function unassign(){
    	CardKeyAssignment::deleteAll(['id_key' => $this->keyModel->id_key]);
    	\Yii::$app->session->setFlash ( 'success', 'Kulcs visszaadva!' );
    }
    
}
