<?php

namespace frontend\controllers;

use Yii;
use common\models\Ticket;
use frontend\models\TicketSearch;
use frontend\models\ReceptionForm;
use frontend\models\TicketCreate;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Discount;
use common\models\TicketType;
use common\models\Account;
use yii\base\Object;
use common\models\Transfer;
use common\models\User;
use common\models\ShoppingCart;
use common\models\UserSoldItem;
use frontend\components\FrontendController;
use frontend\components\DefaultAccountBehavior;
use frontend\components\CassaOpenBehavior;
use frontend\models\TicketUpdate;

/**
 * TicketController implements the CRUD actions for Ticket model.
 */
class TicketController extends FrontendController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        		'access' => [
        				'class' => \yii\filters\AccessControl::className(),
        				'only' => ['create', 'index','update' ],
        				'rules' => [
        						// allow authenticated users
        						[
        								'allow' => true,
        								'roles' => ['@'],
        						],
        						// everything else is denied
        				],
        		],
        		'defaultAccount' => [
        				'class' => DefaultAccountBehavior::className(),
        		],
        		'cassaIsOpen' => [
        				'class' => CassaOpenBehavior::className(),
        		],
        ];
    }

    /**
     * Lists all Ticket models.
     * @return mixed
     */
    public function actionIndex($number = null)
    {
    	$receptionForm = $this->mkReceptionForm($number);
    	
    	
    	if ( !isset($receptionForm->card ) ){
    		throw new NotFoundHttpException( Yii::t('frontend/ticket', 'The requested card does not exist.'));
    	}
    	
        $searchModel = new TicketSearch();
        $dataProvider = $searchModel->search( $receptionForm->card, Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        	'receptionForm' => $receptionForm,
        ]);
    }

    /**
     * Creates a new Ticket model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($number = null)
    {
    	
    	$receptionForm =$this->mkReceptionForm($number);
    	
    	if ( !isset($receptionForm->card ) ){
    		throw new NotFoundHttpException( Yii::t('frontend/ticket', 'The requested card does not exist.'));
    	}
    	
    	if ( isset($_POST['payout_customer_cart']) &&  $this->payoutCustomerCart($receptionForm) ){
    		return $this->redirect(['customer/reception'   ]);
    	}else if ( isset($_POST['payout_user_cart']) && $this->payoutUserCart($receptionForm)){
    			return $this->redirect(['customer/reception'   ]);
    	}
    	
    	
        $model = new  TicketCreate();

        $discounts = Discount::readTicketDiscounts();
        
        $ticketTypes = TicketType::read(null, null);
        
        $accounts = Account::readAccounts();
        
        $user = User::findOne( [ 'id' => Yii::$app->user->id ] );
        
		$model->customer = $receptionForm->customer;
        $model->id_user = \Yii::$app->user->id;
        
      
        $model->usage_count = 0;
        $model->id_card = $receptionForm->card->id_card;	
        $model->id_account = Account::readDefault();
        
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	Yii::$app->session->setFlash('success', Yii::t('frontend/ticket', 'Ticket added to customer') );
            return $this->redirect(['product/sale', 'number' => $receptionForm->card->number]);
        } 
        	
        	$model->userCart = Transfer::modelsToArray( Transfer::readUserSoldTransfers($user) );
        	$model->customerCart = Transfer::modelsToArray( Transfer::readCustomerCart( $receptionForm->customer ) );
        	
            return $this->render('create', [
                'model' => $model,
                'discounts' => $discounts,
                'ticketTypes' => $ticketTypes,
                'accounts' => $accounts,
            	'receptionForm' => $receptionForm,
            ]);
    }
    
    public function actionUpdate($id){
    	$model = TicketUpdate::findOne($id);
    	
    	if ( !isset($model)){
    		throw new NotFoundHttpException('The requested page does not exist.');
    	}
    	
    	if ($model->load(Yii::$app->request->post()) && $model->save()) {
    		return $this->redirect(['index', 'number' => $model->card->number]);
    	}
    	
    	return $this->render('update',['model' => $model]);
    	
    }
    
    /**
     * Deletes an existing Transfer model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
    	$ticket = $this->findModel($id);
    	$transfer = Transfer::find()->andWhere(['transfer.type' => Transfer::TYPE_TICKET])
    	->andWhere(['transfer.id_object' => $ticket->id_ticket])
    	->one();
    	$connection = \Yii::$app->db;
    	$transaction = $connection->beginTransaction();
    	try {
    		ShoppingCart::deleteAll([  'id_transfer' => $transfer->id_transfer]);
    		UserSoldItem::deleteAll([  'id_transfer' => $transfer->id_transfer]);
//     		$transfer->status = Transfer::STATUS_STORNO;
//     		$transfer->save(false);
//     		$ticket->status = Ticket::STATUS_DELETED;
//     		$ticket->save(false);
			$transfer->storno();
    		$transaction->commit();
    		\Yii::$app->session->setFlash( 'success','Bérlet törölve' );
    		
    		//     			$transaction->commit();
//     		if ( $transfer->delete() ){
//     			\Yii::$app->session->setFlash( 'success','Bérlet törölve' );
//     			$transaction->commit();
//     		}else{
//     			throw  new \Exception("Failed to save");
//     		}
    
    	} catch(Exception $e) {
    		$transaction->rollback();
    		\Yii::$app->session->setFlash( 'danger','Bérlet törlése nem sikerült' );
    	}
    
    
    	return $this->redirect(Yii::$app->request->referrer);
    }
 
    /**
     * Finds the Ticket model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Ticket the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
    	if (($model = Ticket::findOne($id)) !== null) {
    		return $model;
    	} else {
    		throw new NotFoundHttpException('The requested page does not exist.');
    	}
    }
    
}
