<?php

namespace backend\controllers;

use common\models\Log;
use common\models\Transfer;
use Yii;
use common\models\Ticket;
use backend\models\TicketSearch;
use yii\helpers\ArrayHelper;
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 common\models\User;
use common\models\Customer;
use common\models\Card;
use backend\models\TicketSearchStatisitcs;
use backend\models\TicketSearchCustomer;
use common\components\TicketSale;
use common\models\Contract;
use common\components\giro\GiroDETSTATetel;
use common\components\DetStatTetelProcessor;
use yii\helpers\VarDumper;
use backend\models\TicketUpdate;
use yii\helpers\Url;
use common\components\Helper;

/**
 * TicketController implements the CRUD actions for Ticket model.
 */
class TicketController extends \backend\controllers\BackendController {
	public function behaviors() {
		return [ 
				'access' => [ 
						'class' => \yii\filters\AccessControl::className (),
						'rules' => [
								// allow authenticated users
								[ 
										'actions' => [ 
												'create',
												'index',
												'view',
												'update',
												'index-customer',
												'statistics' ,
												'test'
										],
										'allow' => true,
										'roles' => [ 
												'admin',
												'employee',
												'reception' 
										] 
								] 
						]
						// everything else is denied
						 
				] 
		];
	}
	
	/**
	 * Lists all Ticket models.
	 * 
	 * @return mixed
	 */
	public function actionIndex() {
		$searchModel = new TicketSearch ();
		$dataProvider = $searchModel->search ( Yii::$app->request->queryParams );
		if ( $searchModel->output != 'pdf'  && $searchModel->output != 'xls' ){
			$searchModel->searchTotals ();
			$searchModel->users = User::read ();
			$searchModel->accounts = Account::read ();
			$searchModel->ticketTypes = TicketType::read ();
		}

		if ( $searchModel->output == 'pdf' ){
			return $this->downloadIndexPdf($searchModel,$dataProvider);
		}else if ( $searchModel->output == 'xls'){
			return $this->downloadIndexXls($searchModel,$dataProvider);
		}
		
		return $this->render ( 'index', [ 
				'searchModel' => $searchModel,
				'dataProvider' => $dataProvider 
		] );
	}

	/**
	 * @param $searchModel \backend\models\TicketSearch
	 * @param $dataProvider \yii\data\ActiveDataProvider
	 */
	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);
        $ticketType = TicketType::findOne($searchModel->id_ticket_type);
        $account = Account::findOne($searchModel->id_account);
		$cardNumber = !empty($searchModel->card_number) ? $searchModel->card_number : "Mind";
        $ticketStatus = !empty($searchModel->status) ? Ticket::toStatusName($searchModel->status) : "Mind";
        $customerIdCustomer = !empty($searchModel->id_customer) ? $searchModel->id_customer : "Mind";
        $customerName = !empty($searchModel->customer_name) ? $searchModel->customer_name : "Mind";
        $start = isset($searchModel->start) ? $formatter->asDateTime($searchModel->timestampStart) : '';
        $end = isset($searchModel->end) ? $formatter->asDateTime($searchModel->timestampEnd) : '';
        $ticketIdTicket = !empty($searchModel->id_ticket ) ? $searchModel->id_ticket : 'Mind';

        $allDateConditionOn = $searchModel->isAllDateConditionOn();
        $ticketIntervalIsValid =  ( $allDateConditionOn ||  "1" == $searchModel->valid_in_interval )? "Igen" : "";
        $ticketIntervalIsCreated =( $allDateConditionOn ||  "1" == $searchModel->created_in_interval) ? "Igen" : "";
        $ticketIntervalIsExpire = ( $allDateConditionOn || "1" == $searchModel->expire_in_interval) ? "Igen" : "";
        $ticketIntervalIsPaid = ( $allDateConditionOn || "1" == $searchModel->paid_in_interval) ? "Igen" : "";

        $sheet->setCellValue('A'.$row, 'Felhasználó');
        $sheet->setCellValue('B'.$row, isset($user) ? $user->username : 'Mind');
        $sheet->setCellValue('C'.$row, 'Bérlet típus');
        $sheet->setCellValue('D'.$row, isset($ticketType) ? $ticketType->name : 'Mind');
        $sheet->setCellValue('E'.$row, 'Kassza');
        $sheet->setCellValue('F'.$row, isset($account) ? $account->name : 'Mind');

        $row++;
        $sheet->setCellValue('A'.$row, 'Bérlet státusz');
        $sheet->setCellValue('B'.$row, $ticketStatus);

        $sheet->setCellValue('C'.$row, 'Vendég azonosító');
        $sheet->setCellValue('D'.$row, $customerIdCustomer);

        $sheet->setCellValue('E'.$row, 'Vendég neve');
        $sheet->setCellValue('F'.$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);
        $sheet->setCellValue('E'.$row, 'Bérlet azonosító');
        $sheet->setCellValue('F'.$row, $ticketIdTicket);
		$sheet->setCellValue('G'.$row, 'Kártya szám');
        $sheet->setCellValue('H'.$row, $cardNumber);

        $row++;
        $sheet->setCellValue('A'.$row, 'Érvényes az időszakban');
        $sheet->setCellValue('B'.$row, $ticketIntervalIsValid);
        $sheet->setCellValue('C'.$row, 'Kiadva az időszakban');
        $sheet->setCellValue('D'.$row, $ticketIntervalIsCreated);
        $sheet->setCellValue('E'.$row, 'Lejár az időszakban');
        $sheet->setCellValue('F'.$row, $ticketIntervalIsExpire);
        $sheet->setCellValue('G'.$row, 'Fizetve az időszakban');
        $sheet->setCellValue('H'.$row, $ticketIntervalIsPaid);

        $row++;
		 $sheet->setCellValue('A'.$row, 'B. Azonosító')
		 ->setCellValue('B'.$row, 'Vendég')
		 ->setCellValue('C'.$row, 'Kártya')
		 ->setCellValue('D'.$row, 'Érvényes -tól')
		 ->setCellValue('E'.$row, 'Érvényes -ig')
		 ->setCellValue('F'.$row, 'Létrehozva')
		 ->setCellValue('G'.$row, 'Bérlet típus')
		 ->setCellValue('H'.$row, 'Felhasználó')
		 ->setCellValue('I'.$row, 'Kassza')
		 ->setCellValue('J'.$row, 'Státusz')
         ->setCellValue('K'.$row, 'Belépések száma')
         ->setCellValue('L'.$row, 'Maximum belépések száma')
         ->setCellValue('M'.$row, 'Nála fizették')
         ->setCellValue('N'.$row, 'Fizetési mód')
         ->setCellValue('O'.$row, 'Összeg')
         ->setCellValue('P'.$row, 'Fizetés státusza')
         ->setCellValue('Q'.$row, 'Vendég azonosító')
        ;


		foreach ( $dataProvider->getModels() as $model ) {
			$row ++;
			$sheet
                ->setCellValue('A'.$row, $model['ticket_id_ticket'])
				->setCellValue('B'.$row,  $model['customer_name'])
				->setCellValue('C'.$row,  $model['card_number'])
				->setCellValue('D'.$row,  $formatter->asDate($model['ticket_start']))
				->setCellValue('E'.$row,  $formatter->asDate($model['ticket_end']))
				->setCellValue('F'.$row,  $formatter->asDateTime($model['ticket_created_at']))
				->setCellValue('G'.$row,  $model['ticket_type_name'])
				->setCellValue('H'.$row,  $model['user_username'])
				->setCellValue('I'.$row,  $model['account_name'])
				->setCellValue('J'.$row,  Ticket::toStatusName( $model['ticket_status']))
                ->setCellValue('K'.$row,  $model['ticket_usage_count'])
                ->setCellValue('L'.$row,  $model['ticket_max_usage_count'])
                ->setCellValue('M'.$row,  $model['paid_by_username'])
                ->setCellValue('N'.$row,  Transfer::toPaymentMethodName( $model['transfer_payment_method']))
                ->setCellValue('O'.$row,  $model['ticket_price_brutto'])
                ->setCellValue('P'.$row,  Transfer::toStatusName( $model['transfer_status']))
                ->setCellValue('Q'.$row,  $model['customer_id_customer'])
            ;
		}

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

	private function downloadIndexPdf($searchModel,$dataProvider){
		set_time_limit(0);
        $formatter = \Yii::$app->formatter;
        $admin = User::findOne(\Yii::$app->user->id);
        $exported_at =  $formatter->asDatetime(new \DateTime());

        $user = User::findOne($searchModel->id_user);
        $ticketType = TicketType::findOne($searchModel->id_ticket_type);
        $account = Account::findOne($searchModel->id_account);
        $ticketStatus = !empty($searchModel->status) ? Ticket::toStatusName($searchModel->status) : "Mind";
        $customerIdCustomer = !empty($searchModel->id_customer) ? $searchModel->id_customer : "Mind";
        $customerName = !empty($searchModel->customer_name) ? $searchModel->customer_name : "Mind";
        $start = isset($searchModel->start) ? $formatter->asDateTime($searchModel->timestampStart) : '';
        $end = isset($searchModel->end) ? $formatter->asDateTime($searchModel->timestampEnd) : '';
        $ticketIdTicket = !empty($searchModel->id_ticket ) ? $searchModel->id_ticket : 'Mind';

        $allDateConditionOn = $searchModel->isAllDateConditionOn();
        $ticketIntervalIsValid =  ( $allDateConditionOn ||  "1" == $searchModel->valid_in_interval )? "Igen" : "";
        $ticketIntervalIsCreated =( $allDateConditionOn ||  "1" == $searchModel->created_in_interval) ? "Igen" : "";
        $ticketIntervalIsExpire = ( $allDateConditionOn || "1" == $searchModel->expire_in_interval) ? "Igen" : "";
        $ticketIntervalIsPaid = ( $allDateConditionOn || "1" == $searchModel->paid_in_interval) ? "Igen" : "";

        $username = isset($user) ? $user->username : 'Mind';
        $ticketTypeName = isset($ticketType) ? $ticketType->name : 'Mind';
        $accountName =  isset($account) ? $account->name : 'Mind';
        $cardNumber = !empty($searchModel->card_number) ? $searchModel->card_number : "Mind";

        $filters = [
            'admin' => $admin->username,
            'exported_at' => $exported_at,
            'ticketStatus' =>$ticketStatus,
            'customerIdCustomer' => $customerIdCustomer,
            'customerName' => $customerName,
            'start' => $start,
            'end' => $end,
            'ticketIdTicket' => $ticketIdTicket,
            'ticketIntervalIsValid' => $ticketIntervalIsValid,
            'ticketIntervalIsCreated' => $ticketIntervalIsCreated,
            'ticketIntervalIsExpire' => $ticketIntervalIsExpire,
            'ticketIntervalIsPaid' => $ticketIntervalIsPaid,
            'username' => $username,
            'ticketTypeName' => $ticketTypeName,
            'accountName' => $accountName,
            'cardNumber' => $cardNumber
        ];

        $fileName = "berletek";
        $fileName .= "_" . date ( "Ymd_His" );
        $fileName .= ".pdf";
 		$mpdf = new \mPDF ( 'utf-8', 'A4' );

			$mpdf->useSubstitutions = false;
			$mpdf->simpleTables = true;
            $mpdf->SetHeader( \Yii::$app->params[ "company_name" ] . " - Bérletek - Létrehozva: "  .$admin->username . ", ".\Yii::$app->formatter->asDatetime(time()) );
			$mpdf->setFooter ( '{PAGENO} / {nb}' );

			$stylesheet = file_get_contents( \Yii::getAlias('@backend/web/css/ticket-index-pdf.css')); // external css
			$mpdf->WriteHTML($stylesheet,1);

			$mpdf->WriteHTML ( $this->renderPartial ( '_index_pdf.php', [
				'model' => $searchModel,
				'dataProvider' => $dataProvider,
                'filters' => $filters
			] ) );
			$mpdf->Output ( $fileName, 'D' );
			exit ();
/*
		return $this->render ( '_index_pdf', [
			'searchModel' => $searchModel,
			'dataProvider' => $dataProvider
		] );
*/
	}
	
	/**
	 * Lists all Ticket models.
	 * 
	 * @return mixed
	 */
	public function actionStatistics() {
		$searchModel = new TicketSearchStatisitcs();
		$searchModel->search ( Yii::$app->request->queryParams );
		$searchModel->searchTotals ();
		
		$searchModel->users = User::read ();
		$searchModel->accounts = Account::read ();
		$searchModel->ticketTypes = TicketType::read ();
		
		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 = "";
			$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 ( 'statistics_pdf', [ 
					'searchModel' => $searchModel 
			] ) );
			$mpdf->Output ( $fn, 'D' );
			exit ();
		} else {
			
			return $this->render ( 'statistics', [ 
					'searchModel' => $searchModel 
			] );
		}
	}

	/**
	 * Lists all Ticket models.
	 *
	 * @param $id
	 * @return mixed
	 * @throws NotFoundHttpException
	 */
	public function actionIndexCustomer($id) {
		$customer = Customer::findOne ( $id );
		$card = Card::findOne ( $id );
		
		if ($customer == null) {
			throw new NotFoundHttpException ( 'The requested page does not exist.' );
		}
		
		$searchModel = new TicketSearchCustomer(['customer' => $customer]);
		$searchModel->id_card = $customer->id_customer_card;
		$dataProvider = $searchModel->search ( Yii::$app->request->queryParams );
		//$searchModel->searchTotals ();
		
		$searchModel->users = User::read ();
		$searchModel->accounts = Account::read ();
		$searchModel->ticketTypes = TicketType::read ();
		
		Url::remember(Url::current(),"ticket_index_customer");
		
		return $this->render ( 'index_customer', [ 
				'searchModel' => $searchModel,
				'dataProvider' => $dataProvider,
				'customer' => $customer,
				'card' => $card 
		] );
	}
	
	/**
	 * Displays a single Ticket model.
	 * 
	 * @param integer $id        	
	 * @return mixed
	 */
	public function actionView($id) {
		return $this->render ( 'view', [ 
				'model' => $this->findModel ( $id ) 
		] );
	}
	
	/**
	 * Creates a new Ticket model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 * 
	 * @return mixed
	 */
	public function actionCreate() {
		$model = new Ticket ();
		
		$discounts = Discount::read ();
		$ticketTypes = TicketType::read ();
		$accounts = Account::readAccounts ();
		
		if ($model->load ( Yii::$app->request->post () ) && $model->save ()) {
			return $this->redirect ( [ 
					'view',
					'id' => $model->id_ticket 
			] );
		} else {
			return $this->render ( 'create', [ 
					'model' => $model,
					'discounts' => $discounts,
					'ticketTypes' => $ticketTypes,
					'accounts' => $accounts 
			] );
		}
	}
	
	/**
	 * Updates an existing Ticket model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * 
	 * @param integer $id        	
	 * @return mixed
	 */
	public function actionUpdate($id) {
		$model = TicketUpdate::findOne( $id );
		
		
		$model->startDate = substr( $model->start ,0 ,10 );
		$model->endDate = substr( $model->end ,0 ,10 );
		
		$model->startDate = \Yii::$app->formatter->asDate($model->startDate);
		$model->endDate = \Yii::$app->formatter->asDate($model->endDate);
		

		
		
		
		if ($model->load ( Yii::$app->request->post () ) && $model->save ()) {


            Log::log([
                'type' =>Log::$TYPE_TICKET_UPDATED_BY_ADMIN,
                'id_ticket' => $model->id_ticket,
                'message' => 'Bérlet módosítva'
            ]);

			Helper::flash("success", "Bérlet sikeresen módosítva");
			
			$url = Url::previous("ticket_index_customer");
			
			if ( isset($url) ){
				return $this->redirect($url);
			}
			return $this->redirect ( [ 
					'view',
					'id' => $model->id_ticket 
			] );
		} else {
			return $this->render ( 'update', [ 
					'model' => $model 
			] );
		}
		
		
	}
	
	/**
	 * Deletes an existing Ticket model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * 
	 * @param integer $id        	
	 * @return mixed
	 */
	public function actionDelete($id) {
		$this->findModel ( $id )->delete ();
		
		return $this->redirect ( [ 
				'index' 
		] );
	}
	
	public function actionTest(){
		
// 		$this->doTestTicketSale();

		$this->doTestDetstaProcess();
		
		return $this->render('test');
		
	}
	
	protected function doTestDetstaProcess(){
		$contract = Contract::findOne(19);
		$megbizas = $contract->requests[0];
		
		$tetel = new GiroDETSTATetel();
		$tetel->visszajelzesInformacio = "02";
		
		$tp = new DetStatTetelProcessor([
			'megbizas' => $megbizas,
			'tetel' => $tetel
		]);
		
		$tp->run();
		
	}
	
	protected function doTestTicketSale(){
		$ticketType = TicketType::findOne(1);
		$customer = Customer::findOne(1);
		$account = Account::findOne(1);
		$card = $customer->card;
		$discount = null;
		$contract = Contract::findOne(19);
		$megbizas = $contract->requests[0];
		
		
		
		$ticketSale = new TicketSale(
				[
						'ticketType'=>  $ticketType,
						'customer'=>  $customer,
						'account'=>  $account,
						'card'=>  $card,
						'discount'=>  $discount,
						'contract'=>  $contract,
						'ticketInstallmentRequest' => $megbizas
				]
				);
		
		$ticketSale->doSale();
	}
	
	/**
	 * 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.' );
		}
	}
}
