<?php

namespace frontend\controllers;

use Yii;
use common\models\Transfer;
use frontend\models\TransferSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use frontend\models\TransferMoneyMovementSearch;
use common\models\Account;
use frontend\models\TransferListSearch;
use common\models\ShoppingCart;
use common\models\UserSoldItem;
use common\models\TransferSaleSearch;
use common\models\User;
use common\models\ProductCategory;
use common\models\Product;
use common\models\TransferTicketSearch;
use common\models\TicketType;
use frontend\models\UserCartForm;
use common\models\Customer;
use frontend\models\CustomerCartForm;
use common\models\Card;
use common\components\Helper;
use yii\base\Exception;
use common\components\TransferPayout;

/**
 * TransferController implements the CRUD actions for Transfer model.
 */
class TransferController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                    'payout' => ['post'],
                ],
            ],
        		'access' => [
        				'class' => \yii\filters\AccessControl::className(),
        				'rules' => [
        						// allow authenticated users
        						[
//         								'actions' => [ 'index','view','summary','list',"sale","sale-pdf" ],
        								'allow' => true,
        								'roles' => ['admin','employee','reception'],
        						],
        						// everything else is denied
        				],
        		],
        ];
    }

    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionMoneyMovementIndex()
    {
        $searchModel = new TransferMoneyMovementSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('money_movement/money_movement_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TransferSearch();
        $searchModel->accounts = Account::read();
        $searchModel->load(Yii::$app->request->queryParams);
        
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        $searchModel->totalsTransfers(Yii::$app->request->queryParams);
        
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
        
    }
    
    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionList()
    {
    	$searchModel = new TransferListSearch();
    	$searchModel->accounts = Account::read();
    	$searchModel->load(Yii::$app->request->queryParams);
    
    	$searchModel->search(Yii::$app->request->queryParams);
    
    
    	return $this->render('list', [
    			'searchModel' => $searchModel,
    	]);
    
    }

    /**
     * Displays a single Transfer model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    
    /**
     * Creates a new Transfer model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionMoneyMovementCreate()
    {
        $model = new Transfer();
		
        $model->type = Transfer::TYPE_MONEY_MOVEMENT_OUT;
        $model->direction = Transfer::DIRECTION_OUT;
        
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id_transfer]);
        } else {
            return $this->render('money_movement/create_money_movement', [
                'model' => $model,
            ]);
        }
    }


    /**
     * Finds the Transfer model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Transfer the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Transfer::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    
    /**
     * Updates an existing Transfer model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id_transfer]);
        } else {
            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 actionPayout($id)
    {
    	$transfer = $this->findModel($id);
    	$connection = \Yii::$app->db;
    	$transaction = $connection->beginTransaction();
    	
    	try {
    		$tp = new TransferPayout( [
    				'idUser' => \Yii::$app->user->id,
    				'idTransfers' => [$transfer->id_transfer ], 
    				'idAccount' => Account::readDefault (),
    		] );
    			
    		$tp->payout ();
    			
    		// UserSoldItem::payout ( $user, $model->transfers );
    		$transaction->commit ();
    		\Yii::$app->session->setFlash ( 'success', 'Tranzakció fizetve: ' . $transfer->count ." db " . $transfer->getObjectName() . " - " . $transfer->money);
    	} catch ( Exception $e ) {
    		$transaction->rollback ();
    		Yii::error ( "faled to save :" . $e->getMessage () );
    	} catch ( \Exception $e ) {
    		$transaction->rollback ();
    		Yii::error ( "faled to save :" . $e->getMessage () );
    	}
    
    	return $this->redirect(Yii::$app->request->referrer);
    }
    
    /**
     * 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)
    {
        $transfer = $this->findModel($id);
        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try {
        	ShoppingCart::deleteAll([  'id_transfer' => $transfer->id_transfer]);
        	UserSoldItem::deleteAll([  'id_transfer' => $transfer->id_transfer]);
        	$transfer->storno();
//        		 if ( $transfer->delete() ){
        	\Yii::$app->session->setFlash( 'success','Tranzakció törölve' );
        	$transaction->commit();
//        		 }else{
//        		 	throw  new \Exception("Failed to save");
//        		 }
       		 
        } catch(Exception $e) {
        	$transaction->rollback();
        	\Yii::$app->session->setFlash( 'danger','Tranzakció törlése nem sikerült' );
        }

        
        return $this->redirect(Yii::$app->request->referrer);
    }
    
    
    protected  function delete($id){
    	$transfer = $this->findModel($id);
    	$connection = \Yii::$app->db;
    	$transaction = $connection->beginTransaction();
    	try {
    		if ( $transfer->delete() ){
    			\Yii::$app->session->setFlash( 'success','Tranzakció törölve' );
    			$transaction->commit();
    		}else{
    			throw  new \Exception("Failed to save");
    		}
    	
    	} catch(Exception $e) {
    		$transaction->rollback();
    		\Yii::$app->session->setFlash( 'danger','Tranzakció törlése nem sikerült' );
    	}
    }
    
    
    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionSale()
    {
    	$searchModel = new TransferSaleSearch();
    	$searchModel->accounts = Account::read();
    	$searchModel->users = User::read();
    	$searchModel->productCategories = ProductCategory::read();
    	$searchModel->productOptions = Product::read();
    
    	$searchModel->search(Yii::$app->request->queryParams);
    
    
    	return $this->render('sale', [
    			'searchModel' => $searchModel,
    	]);
    
    }
    
    public function actionSalePdf(){
    	$searchModel = new TransferSaleSearch();
    	$searchModel->accounts = Account::read();
    	$searchModel->users = User::read();
    	$searchModel->productCategories = ProductCategory::read();
    	$searchModel->productOptions = Product::read();
    	 
    	$searchModel->search(Yii::$app->request->queryParams);
    	 
    	 
    	$mpdf=new \mPDF('utf-8', 'A4-L');
    	$mpdf->WriteHTML($this->renderPartial('_result_sale', [
    			'searchModel' => $searchModel,
    	]));
    	$mpdf->Output('eladasaim.pdf', 'D');
    	exit;
    	 
    }
    

    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionTickets()
    {
    	$searchModel = new TransferTicketSearch();
    	$searchModel->accounts = Account::read();
    	$searchModel->users = User::read();
    	$searchModel->ticketTypes = TicketType::read(null, Account::readDefault());
    
    	$searchModel->search(Yii::$app->request->queryParams);
    
    
    	return $this->render('tickets', [
    			'searchModel' => $searchModel,
    	]);
    
    }
    
    public function actionTicketsPdf(){
    	$searchModel = new TransferTicketSearch();
    	$searchModel->accounts = Account::read();
    	$searchModel->users = User::read();
    	$searchModel->ticketTypes = TicketType::read(null, Account::readDefault());
    
    	$searchModel->search(Yii::$app->request->queryParams);
    
    
    	$mpdf=new \mPDF('utf-8', 'A4-L');
    	$mpdf->WriteHTML($this->renderPartial('_result_ticket', [
    			'searchModel' => $searchModel,
    	]));
    	$mpdf->Output('eladdot_berletek_'. \Yii::$app->formatter->asDatetime(time()).'.pdf', 'D');
    	exit;
    
    }
    
    
    public function actionUserCart(){
    	
    	$defaultAccount = Account::readDefault();
    	
    	if ( !isset($defaultAccount)){
    		return $this->redirect(['account/select']);
    	}
    	
    	$model = new UserCartForm();
    	if ($model->load(Yii::$app->request->post()) && $model->payout()) {
    		return $this->redirect(['user-cart']);
    	}
    	$model->run();
    	return $this->render("usercart",[ 'model' => $model]);
    }
    
    
    public function actionCustomerCart($id_card){
    	
    	$defaultAccount = Account::readDefault();
    	 
    	if ( !isset($defaultAccount)){
    		return $this->redirect(['account/select']);
    	}
    	
    	$customer = null;
    	$card = Card::findOne($id_card);
    	if ($card != null )
    		$customer = $card->customer;
    	
    	
    	if ( !isset($customer) ){
    		throw new NotFoundHttpException ( 'Az oldal nem található' );
    	}
    	
    	$model = new CustomerCartForm();
    	$model->customer = $customer;
    	if ($model->load(Yii::$app->request->post()) && $model->payout()) {
    		return $this->redirect(['customer-cart','id_card' => $model->customer->card->id_card]);
    	}
    	$model->run();
    	return $this->render("customercart",[ 'model' => $model]);
    }
}
