<?php
namespace backend\controllers;

use Yii;
use common\models\Transfer;
use backend\models\TransferSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Account;
use common\models\User;
use backend\models\TransferSummarySearch;
use backend\models\TransferListSearch;
use backend\models\TransferSaleSearch;
use common\models\ProductCategory;
use common\models\Product;
use backend\models\TransferListUserGroupedSearch;
use backend\models\TransferLaterSearch;
use yii\helpers\Url;
use common\components\Helper;

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

	 public function actionPaymentLater(){
	 	$searchModel = new TransferLaterSearch();
	 	
	 	
	 	if ( \Yii::$app->request->isPost){
	 		$searchModel->load(Yii::$app->request->post());
		 	if (  $searchModel->doPayout()) {
	    		return $this->redirect(['transfer/payment-later' ]);
	    	}
	 	}
	 	
	 	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
	 	

	 	
	 	if ( $searchModel->output =='pdf'){
	 		$this->downloadPaymentLater($dataProvider);
	 	}
	 	
	 	$accounts = Account::read();
	 	$users = User::read();
	 	
	 	Url::remember("payment_later",Url::current());
	 	
	 	return $this->render('payment_later', [
	 			'searchModel' => $searchModel,
	 			'dataProvider' => $dataProvider,
	 			'accounts' => $accounts,
	 			'users' => $users,
	 	]);
	 }
	 
	 protected function downloadPaymentLater($dataProvider) {
	 
	 	// 		$mpdf = new \mPDF ( 'utf-8', 'A4' );
	 	$mpdf = new \mPDF ( 'utf-8', 'A4-L' );
	 	$fn = "utolagos_fizetesek.pdf";
	 		
	 	$mpdf->useSubstitutions = false;
	 	$mpdf->simpleTables = true;
	 	$mpdf->SetHeader ( "" );
	 	$mpdf->setFooter ( '{PAGENO} / {nb}' );
	 
	 	 
	 		
	 	$stylesheet = file_get_contents ( \Yii::getAlias ( '@vendor' . '/bower/bootstrap/dist/css/bootstrap.css' ) ); // external css
	 	$mpdf->WriteHTML ( $stylesheet, 1 );
	 		
	 	$mpdf->WriteHTML ( $this->renderPartial ( '_pdf_payment_later.php', [
	 			'dataProvider' => $dataProvider
	 	] ) );
	 	$mpdf->Output ( $fn, 'D' );
	 	exit ();
	 
	 }
	    
    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TransferSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        $accounts = Account::read();
        
        $searchModel->totalsTransfers();
       	
        $users = User::read();

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

    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionList()
    {
    	$searchModel = new TransferListSearch();
    	$searchModel->accounts = Account::read();
    	$searchModel->users = User::read();
    
    	$searchModel->search(Yii::$app->request->queryParams);
    
    
    	if ( $searchModel->output == 'pdf'){
    		$user = User::findOne(\Yii::$app->user->id);
    		$mpdf=new \mPDF('utf-8', 'A4-L');
    		$fn = "";
    		$ov = '_total_content_pdf';
    		$dt= "_letrehozva_".date("Ymd_His"). "_" . $user->username; 
    		$interval="";
    		$account = "";
    		$currentUser= "";
    		if ( isset($searchModel->currentAccount) ){
    			$account =( "_kassza_".$searchModel->currentAccount->name);
    		}
    		
    		if ( isset($searchModel->currentUser) ){
    			$currentUser = ( "_felhasznalo_".$searchModel->currentUser->username);
    		}
    		if ( isset($searchModel->timestampStart) ){
    			$interval .="_tol_". \Yii::$app->formatter->asDatetime($searchModel->timestampStart,'yyyyMMdd_HHmm');
    		}
    		if ( isset($searchModel->timestampEnd) ){
    			$interval .="_ig_". \Yii::$app->formatter->asDatetime($searchModel->timestampEnd,'yyyyMMdd_HHmm');
    		}
    		if ( $searchModel->outputView == 'easy'){
    			$ov = '_total_easy';
    			$fn="napi_bevetelek_egyszeru";
    		}else if ( $searchModel->outputView == 'medium'){
    			$ov = '_total_medium';
    			$fn="napi_bevetelek_kozepes";
    		}else if ( $searchModel->outputView == 'detailed'){
    			$ov = '_total_detailed';
    			$fn="napi_bevetelek_reszletes";
    		}else{
    			$ov = '_total_content_pdf';
    			$fn="napi_bevetelek.teljes";
    		}
    		$fn = $fn. $interval . $dt  .$account .$currentUser. ".pdf";
    		
    		$mpdf->useSubstitutions=false;
    		$mpdf->simpleTables = true;
    		$mpdf->SetHeader( \Yii::$app->params[ "company_name" ] . " - Létrehozva: "  .$user->username . ", ".\Yii::$app->formatter->asDatetime(time()) );
    		$mpdf->setFooter('{PAGENO} / {nb}');
    		
    		$stylesheet = file_get_contents( \Yii::getAlias('@vendor'.'/bower/bootstrap/dist/css/bootstrap.css')); // external css
    		$mpdf->WriteHTML($stylesheet,1);
    		
    		$mpdf->WriteHTML($this->renderPartial($ov, [
    				'searchModel' => $searchModel,
    		]));
    		$mpdf->Output($fn, 'D');
    		  exit;
    	}else{
	    	return $this->render('list', [
	    			'searchModel' => $searchModel,
	    	]);
    	}
    
    }
    
    
    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionListUserGrouped()
    {
    	$searchModel = new TransferListUserGroupedSearch();
    	$searchModel->accounts = Account::read();
    	$searchModel->users = User::read();
    
    	$searchModel->search(Yii::$app->request->queryParams);
    
    
    	return $this->render('list_user_grouped', [
    			'searchModel' => $searchModel,
    	]);
    
    }
    
    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionSale()
    {
    	$searchModel = new TransferSaleSearch();
    	$searchModel->mode = 'admin';
    	$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->mode = 'admin';
    	$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');
 		$stylesheet = file_get_contents( \Yii::getAlias('@vendor'.'/bower/bootstrap/dist/css/bootstrap.css')); // external css
 		$mpdf->WriteHTML($stylesheet,1);
        $mpdf->WriteHTML($this->renderPartial('_result_sale', [
    			'searchModel' => $searchModel,
    	]));
        $mpdf->Output('MyPDF.pdf', 'D');
        exit;
    	
    }
    
    /**
     * Lists all Transfer models.
     * @return mixed
     */
    public function actionSummary()
    {
    	$searchModel = new TransferSummarySearch();
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
    	$accounts = Account::read();
    
    	$users = User::read();
    
    	return $this->render('summary', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    			'accounts' => $accounts,
    			'users' => $users,
    	]);
    }
    
    /**
     * Displays a single Transfer model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
    
    
    public function actionUnstorno($id)
    {
    	$model = $this->findModel($id);
    	
    	$model->unstorono();
    	
    	Helper::flash("success", "Bérlet visszaállítva");
    	
    	return $this->redirect( ['view' ,'id' => $model->id_transfer]);
    }


    /**
     * 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,
            ]);
        }
    }

     */

    /**
     * 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.');
        }
    }
}
