<?php
namespace backend\controllers;

use common\models\DoorLog;
use Yii;
use common\models\Transfer;
use backend\models\TransferSearch;
use yii\db\Expression;
use yii\db\Query;
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->downloadPaymentLaterPDF($dataProvider);
	 	}else if ( $searchModel->output =='xls'){
	 		$this->downloadPaymentLaterXLS($searchModel, $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 getEnterCount($start,$end,$idCustomer){



		$query = new Query();

		$query->select([
			'card.number as card_number',
			'card.id_card as card_id_card',
			'count(*) as enter',
			new Expression('EXTRACT( YEAR_MONTH FROM door_log.created_at) as ym'),
			new Expression('EXTRACT( YEAR FROM door_log.created_at ) as year'),
			new Expression('EXTRACT( MONTH FROM door_log.created_at ) as month  ')

		]);

		$query->from('door_log');
		$query->innerJoin('card','card.id_card = door_log.id_card');
		$query->andWhere(['in','door_log.direction',[3,7]]);
		$query->groupBy([
			'card.number',
			'card.id_card',
			'ym',
			'year',
			'month'
		]);

		$query->andWhere(['door_log.id_customer' => $idCustomer]);


		$query->andWhere([ '>=','door_log.created_at',$start]);
		$query->andWhere([ '<','door_log.created_at',$end]);

		$customerStatistic = $query->one();

		$moveInCount = $customerStatistic['enter'];

		return $moveInCount;
	}



	/**
	 * @param \backend\models\TransferLaterSearch $searchModel
	 * @param \yii\data\ActiveDataProvider $dataProvider
	 */
	protected function downloadPaymentLaterXLS( $searchModel, $dataProvider) {

		$fn = "kesobbi_utalasok.xls";

		$objPHPExcel = new \PHPExcel ();
		$sheet = $objPHPExcel->setActiveSheetIndex ( 0 );
		$formatter = \Yii::$app->formatter;



		$row = 1;
		$sheet->setCellValue('A'.$row, 'Csoportos beszedés');

		$row++;
		$sheet->setCellValue('A'.$row, 'Időszak kezdete');
		$sheet->setCellValue('B'.$row, $searchModel->start);
		$sheet->setCellValue('C'.$row, 'Időszak vége');
		$sheet->setCellValue('D'.$row, $searchModel->end);
        $row++;
		$sheet->setCellValue('A'.$row, 'Belépési Időszak kezdete');
		$sheet->setCellValue('B'.$row, $searchModel->enterStart);
		$sheet->setCellValue('C'.$row, 'Belépési Időszak vége');
		$sheet->setCellValue('D'.$row, $searchModel->enterEnd);
		$row++;
		$sheet->setCellValue('A'.$row, 'Bérlettípus');
		$sheet->setCellValue('B'.$row,  $searchModel->id_ticket_type);
		$sheet->setCellValue('C'.$row, 'Felhasználó');
		$sheet->setCellValue('D'.$row, $searchModel->id_user);

		$row++;
		$sheet->setCellValue('A'.$row, 'Kártyaszám')
			->setCellValue('B'.$row, 'Vendég')
			->setCellValue('C'.$row, 'Kiadva')
			->setCellValue('D'.$row, 'Bérlet típus')
			->setCellValue('E'.$row, 'Összeg')
			->setCellValue('F'.$row, 'Megjegyzés')
			->setCellValue('G'.$row, 'Belépések az időszakban');
		;

		foreach ( $dataProvider->getModels() as $model ) {
			$row ++;

			$sheet
				->setCellValue('A'.$row, $model['card_number'])
				->setCellValue('B'.$row,  $model['customer_name'])
				->setCellValue('C'.$row,  $model['transfer_created_at'])
				->setCellValue('D'.$row,  ($model['ticket_type_name']))
				->setCellValue('E'.$row,  $model['transfer_money'])
				->setCellValue('F'.$row,  $model['ticket_comment'])
				->setCellValue('G'.$row,   $model['enter'])
//				->setCellValue('F'.$row,  $processedTime)
//				->setCellValue('G'.$row,  $status)
			;
		}

		$styleArray = array (
			'font' => array (
				'bold' => true
			)
		);

		$sheet->getStyle ( 'A1' )->applyFromArray ( $styleArray );

		foreach ( range ( 'A', 'G' ) as $columnID ) {
			$sheet->getColumnDimension ( $columnID )->setAutoSize ( true );
			$sheet->getStyle ( $columnID . '5' )->applyFromArray ( $styleArray );
		}

		foreach ( ['A','C'] as $columnID ) {
			$sheet->getColumnDimension ( $columnID )->setAutoSize ( true );
			$sheet->getStyle ( $columnID . '2' )->applyFromArray ( $styleArray );
			$sheet->getStyle ( $columnID . '3' )->applyFromArray ( $styleArray );
			$sheet->getStyle ( $columnID . '4' )->applyFromArray ( $styleArray );
		}


		$fileName = $fn;

		// Redirect output to a client’s web browser (Excel5)
		header ( 'Content-Type: application/vnd.ms-excel' );
		header ( 'Content-Disposition: attachment;filename="' . $fileName . '"' );
		header ( 'Cache-Control: max-age=0' );
		// If you're serving to IE 9, then the following may be needed
		header ( 'Cache-Control: max-age=1' );
		// If you're serving to IE over SSL, then the following may be needed
		header ( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' ); // Date in the past
		header ( 'Last-Modified: ' . gmdate ( 'D, d M Y H:i:s' ) . ' GMT' ); // always modified
		header ( 'Cache-Control: cache, must-revalidate' ); // HTTP/1.1
		header ( 'Pragma: public' ); // HTTP/1.0
		$objWriter = \PHPExcel_IOFactory::createWriter ( $objPHPExcel, 'Excel5' );
		$objWriter->save ( 'php://output' );


		exit ();

	}
	 
	 protected function downloadPaymentLaterPDF($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();

		 if ( $searchModel->output === 'xls'){
            set_time_limit(0);
			return $this->downloadIndexXls($searchModel,$dataProvider);
		 }
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        	'accounts' => $accounts,
        	'users' => $users,
        ]);
        
    }

    /**
     * @param $searchModel \backend\models\TicketSearch
     * @param $dataProvider \yii\data\ActiveDataProvider
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \yii\base\InvalidConfigException
     */
    private function downloadIndexXls($searchModel, $dataProvider){

        $objPHPExcel = new \PHPExcel ();
        $sheet = $objPHPExcel->setActiveSheetIndex ( 0 );
        $formatter = \Yii::$app->formatter;

        $admin = User::findOne(\Yii::$app->user->id);

        $row = 1;

        $sheet->setCellValue('A'.$row, 'Exportálta');
        $sheet->setCellValue('B'.$row, $admin->username);
        $sheet->setCellValue('C'.$row, 'Exportálás ideje');
        $sheet->setCellValue('D'.$row, $formatter->asDatetime(new \DateTime()));

        $row++;
        $user = User::findOne($searchModel->id_user);
        $userName = isset($user) ? $user->username : 'Mind';
        $account = Account::findOne($searchModel->id_account);
        $accountName = isset($account) ? $account->name : 'Mind' ;
        $statusName = !empty($searchModel->status) ? Transfer::toStatusName($searchModel->status) : 'Mind';
        $start = isset($searchModel->start) ? $formatter->asDateTime($searchModel->timestampStart) : '';
        $end = isset($searchModel->end) ? $formatter->asDateTime($searchModel->timestampEnd) : '';
        $paymentMethodName = !empty($searchModel->payment_method ) ? Transfer::toPaymentMethodName($searchModel->payment_method) : '';
        $customerName = !empty($searchModel->customer_name) ? $searchModel->customer_name : "Mind";
        $cardNumber = !empty($searchModel->card_number) ? $searchModel->card_number : "Mind";
        $transferName = !empty($searchModel->transfer_name) ? $searchModel->transfer_name : "Mind";


        $sheet->setCellValue('A'.$row, 'Felhasználó');
        $sheet->setCellValue('B'.$row, $userName );
        $sheet->setCellValue('C'.$row, 'Kassza');
        $sheet->setCellValue('D'.$row, $accountName);
        $sheet->setCellValue('E'.$row, 'Státusz');
        $sheet->setCellValue('F'.$row, $statusName);

        $row++;
        $sheet->setCellValue('A'.$row, 'Fizetési mód');
        $sheet->setCellValue('B'.$row, $paymentMethodName );
        $sheet->setCellValue('C'.$row, 'Vendég neve');
        $sheet->setCellValue('D'.$row, $customerName);
        $row++;
        $sheet->setCellValue('A'.$row, 'Időszak kezdete');
        $sheet->setCellValue('B'.$row, $start);
        $sheet->setCellValue('C'.$row, 'Időszak vége');
        $sheet->setCellValue('D'.$row, $end);
        $row++;
        $sheet->setCellValue('E'.$row, 'Megnevezés');
        $sheet->setCellValue('F'.$row, $transferName);
        $sheet->setCellValue('G'.$row, 'Kártya szám');
        $sheet->setCellValue('H'.$row, $cardNumber);

        $row++;
        $sheet->setCellValue('A'.$row, 'T. Azonosító')
            ->setCellValue('B'.$row, 'Típus')
            ->setCellValue('C'.$row, 'Megnevezés')
            ->setCellValue('D'.$row, 'Kiadta')
            ->setCellValue('E'.$row, 'Fizette')
            ->setCellValue('F'.$row, 'Vendég')
            ->setCellValue('G'.$row, 'Kassza')
            ->setCellValue('H'.$row, 'Egységár')
            ->setCellValue('I'.$row, 'Mennyiség')
            ->setCellValue('J'.$row, 'Összeg')
            ->setCellValue('K'.$row, 'Státusz')
            ->setCellValue('L'.$row, 'Fizetési mód')
            ->setCellValue('M'.$row, 'Kiadva')
            ->setCellValue('N'.$row, 'Fizetve')
            ->setCellValue('O'.$row, 'Érv. -tól')
            ->setCellValue('P'.$row, 'Érv. -ig')
        ;


        foreach ( $dataProvider->getModels() as $model ) {
            $row ++;
            $sheet
                ->setCellValue('A'.$row, $model['transfer_id_transfer'])
                ->setCellValue('B'.$row,  $model['transfer_type'])
                ->setCellValue('C'.$row,  $model['transfer_name'])
                ->setCellValue('D'.$row,  ($model['user_username']))
                ->setCellValue('E'.$row,  ($model['paid_by_username']))
                ->setCellValue('F'.$row,  ($model['customer_name']))
                ->setCellValue('G'.$row,  $model['account_name'])
                ->setCellValue('H'.$row,  $model['transfer_item_price'])
                ->setCellValue('I'.$row,  $model['transfer_count'])
                ->setCellValue('J'.$row,  $model['transfer_money'])
                ->setCellValue('K'.$row,  $model['transfer_status'])
                ->setCellValue('L'.$row,  $model['transfer_payment_method'])
                ->setCellValue('M'.$row,  $model['transfer_created_at'])
                ->setCellValue('N'.$row,  $model['transfer_paid_at'])
                ->setCellValue('O'.$row,  $model['ticket_start'])
                ->setCellValue('P'.$row,  $model['ticket_end'])
                ->setCellValue('Q'.$row,  $model['all_comment'])
            ;
        }

        $styleArray = array (
            'font' => array (
                'bold' => true
            )
        );

        foreach ( range ( 'A', 'Q' ) as $columnID ) {
            $sheet->getColumnDimension ( $columnID )->setAutoSize ( true );
            $sheet->getStyle ( $columnID . '6' )->applyFromArray ( $styleArray );
        }

        foreach ( ['A','C','E' ,'G']as $columnID ) {
            for ($i = 1 ; $i < 6; $i++){
                $sheet->getStyle ( $columnID . $i )->applyFromArray ( $styleArray );
            }
        }

        $fileName = "berletek";
        $fileName .= "_" . date ( "Ymd_His" );
        $fileName .= ".xls";

        // Redirect output to a client’s web browser (Excel5)
        header ( 'Content-Type: application/vnd.ms-excel' );
        header ( 'Content-Disposition: attachment;filename="' . $fileName . '"' );
        header ( 'Cache-Control: max-age=0' );
        // If you're serving to IE 9, then the following may be needed
        header ( 'Cache-Control: max-age=1' );
        // If you're serving to IE over SSL, then the following may be needed
        header ( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' ); // Date in the past
        header ( 'Last-Modified: ' . gmdate ( 'D, d M Y H:i:s' ) . ' GMT' ); // always modified
        header ( 'Cache-Control: cache, must-revalidate' ); // HTTP/1.1
        header ( 'Pragma: public' ); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter ( $objPHPExcel, 'Excel5' );
        $objWriter->save ( 'php://output' );
        exit ();
    }


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