<?php

namespace frontend\models;

use common\models\DoorLog;
use common\models\Log;
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.
 *
 * @property \common\models\Card $card
 * @property \common\models\Key $key
 *
 */
class TowelForm extends Model
{

	public $count;
	public $number;
    public $direction;

	public $card;
    public $customer;
    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        	[['count'], 'integer', 'min' => 1, 'max' => 10 ],
        	[['number','direction'], 'safe' ],
            [['count', 'number'], 'required'],
        	[['number'],'validateCard'   ],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
        ];
    }

	public function validateCard($a,$params){

		$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 ){
			$this->customer = $this->card->customer;
		}

        if ( !isset($this->customer)){
            $this->addError($a,"A megadott vendég nem található");
        }

	}



    private function updateTowelCount(){
        $count = $this->count;
        if ( isset($this->direction) && $this->direction == 'in'){
            $count = $this->customer->towel_count - $count;
            $log_type = Log::$TYPE_TOWEL_IN;
        }else{
            $count = $this->customer->towel_count + $count;
            $log_type = Log::$TYPE_TOWEL_OUT;
        }

       $count = max(0, $count );

       $this->customer->towel_count = $count;
       $result =  $this->customer->save(false);
        if ( $result ){
            Log::log([
                'type' => $log_type,
                'message' => '' .$this->customer->towel_count,
                'id_customer' => $this->customer->id_customer
            ]);
        }
        return $result;
    }

    public function save(){
        if ( $this->validate()){
            return $this->updateTowelCount();
        }
        return false;
    }

}
