<?php

namespace frontend\models;

use common\models\DoorLog;
use common\models\Log;
use /** @noinspection PhpUndefinedClassInspection */
    yii\base\Model;
use common\models\CardKeyAssignment;
use common\models\Key;
use common\components\Helper;
use common\models\Card;

/** @noinspection PhpUndefinedClassInspection */

/**
 * ContactForm is the model behind the contact form.
 *
 * @property \common\models\Card $card
 * @property \common\models\Key $key
 * @property \common\models\Key $keyModel
 * @property \common\models\Card $keyCard
 *
 */
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);
    	// add condition rfid key or number
    	$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();
    	//ha van ilyen kulcs
    	if (  isset($this->keyModel)  ){
    	    //find card - key assignments
            /** @var /common/models/Card keyCard */
    		$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 assignment found - we will unassign it
    		if ( count($assignments) > 0){
    		    if ( isset( $this->keyCard ) ){

                    CardKeyAssignment::deleteAll(['id_key' => $this->keyModel->id_key]);
                    $this->keyCard->setFlagsHasKey(false);
                    $this->keyCard->save(false);
                    /** @noinspection PhpUndefinedClassInspection */
                    \Yii::$app->session->setFlash ( 'success', 'Kulcs visszaadva!' );
                    $this->action = 'unassign';
                    Log::log([
                        'type' =>Log::$TYPE_KEY_ASSIGN,
                        'message' => 'Kulcs visszaadás - Kártya/Kulcs/Vendég:' .$this->keyCard->number ."/" .$this->keyModel->number . "/".$this->keyCard->customer->name,
                        'id_key' => $this->keyModel->id_key,
                        'id_customer' => $this->keyCard->customer->id_customer
                    ]);
                    DoorLog::mkDoorLog(-1,$this->keyCard,$this->keyCard->customer,$this->keyModel );
                }else{
                    /** @noinspection PhpUndefinedClassInspection */
                    \Yii::error("Key for assignment not found");
                    /** @noinspection PhpUndefinedClassInspection */
                    \Yii::$app->session->setFlash ( 'danger', 'Kulcs visszaadás hiba: kulcs nem található!' );
                }
    		}else{
    		    // if there is no assignment - assign it to the customer
    			$this->assign();
    		}
    	}else{
            /** @noinspection PhpUndefinedClassInspection */
            \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 ){
                /** @noinspection PhpUndefinedClassInspection */
                \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;
                /** @noinspection PhpUndefinedClassInspection */
                $assignment->id_user = \Yii::$app->user->id;
		    	$assignment->save(false);
                /** @noinspection PhpUndefinedClassInspection */
                \Yii::$app->session->setFlash ( 'success', 'Kulcs kiadva!' );

				$this->card->setFlagsHasKey(true);
                $this->card->save(false);

                Log::log([
                    'type' =>Log::$TYPE_KEY_ASSIGN,
                    'message' => 'Kulcs kiadás - Kártya/Kulcs/Vendég:' .$this->card->number ."/" .$this->keyModel->number . "/".$this->customer->name,
                    'id_key' => $this->card->id_card,
                    'id_customer' => $this->customer->id_customer
                ]);

                DoorLog::mkDoorLog(-2,$this->card,$this->customer,$this->keyModel );
    		}
    	}else{
            /** @noinspection PhpUndefinedClassInspection */
            \Yii::$app->session->setFlash ( 'danger', 'Nincs vendég kiválasztva vagy érvénytelen kártya!' );
    	}
    }
    

}
