<?php

namespace frontend\controllers;

use Yii;
use common\models\Key;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\base\Object;
use yii\db\Query;
use yii\helpers\Json;
use frontend\models\KeySearch;
use frontend\models\ReceptionForm;
use frontend\models\KeyToggleForm;
use common\models\Customer;
use common\models\Card;
use common\models\CardKeyAssignment;

/**
 * KeyController implements the CRUD actions for Key model.
 */
class KeyController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Key models.
     * @return mixed
     */
    public function actionIndex( $id_card )
    {
    	$card = Card::findOne($id_card);
    	if ( !isset( $card ) ){
    		throw  new NotFoundHttpException("Vendég nem található");
    	}
    	
    	$searchModel = new KeySearch();
    	$searchModel->card = $card;
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
    	return $this->render('index', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    	]);
    }
    
    /**
     * Deletes an existing CardKeyAssignment model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id_key)
    {
    	$key = Key::findOne($id_key);
    	if ( !isset($key)){
    		throw new NotFoundHttpException("Kulcs nem található");
    	}
    	
    	
    	CardKeyAssignment::deleteAll(['id_key' => $key->id_key]);
    
    	\Yii::$app->session->setFlash('success','Kulcs visszaadva');
    
    	return $this->redirect(['customer/reception' ]);
    }
    
    
    /**
     * Lists all Key models.
     * @return mixed
     */
    public function actionToggle($number = null)
    {
    	// $this->findByNumber($number);
    	$receptionForm = new ReceptionForm();
    	$receptionForm->number = $number;
    	$receptionForm->readCard ();
    	
    	$customer = $receptionForm->customer;
    	$card = $receptionForm->card;
    	
    	
    	$model = new KeyToggleForm();
    	$model->card = $receptionForm->card;
    	$model->customer = $receptionForm->customer;
    	
    	if ( $model->load ( Yii::$app->request->post () )) {
			$model->toggleKey();    		
    	}
    	
    	if ( isset( $model->keyCard ) ){
    		return $this->redirect(['product/sale', 'number' => $model->keyCard->number ]);
    	}
    	
    	 
    	
    	return $this->redirect(['customer/reception', 'number' => $number ]);
    	
    }

    
}
