<?php

namespace backend\controllers;

use Yii;
use common\models\CardPackage;
use backend\models\CardPackageSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\components\Helper;
use common\components\FreeUniqueCardNumberGenerator;
use common\models\Card;
use common\models\CardCardPackageAssignment;
use yii\data\ActiveDataProvider;
use backend\models\CardPackageImportForm;
use common\components\XLSUtil;
use yii\web\UploadedFile;
use common\components\Upload;

/**
 * CardPackageController implements the CRUD actions for CardPackage model.
 */
class CardPackageController extends  \backend\controllers\BackendController {
	
	
	public function behaviors()
	{
		return [
				'access' => [
						'class' => \yii\filters\AccessControl::className(),
						'rules' => [
								// allow authenticated users
								[
										'actions' => ['create','index','view','import','download'],
										'allow' => true,
										'roles' => ['admin','employee','reception'],
								],
								// everything else is denied
						],
				],
		];
	}
	/**
	 * Lists all CardPackage models.
	 *
	 * @return mixed
	 */
	public function actionIndex() {
		$searchModel = new CardPackageSearch ();
		$dataProvider = $searchModel->search ( Yii::$app->request->queryParams );
		
		return $this->render ( 'index', [ 
				'searchModel' => $searchModel,
				'dataProvider' => $dataProvider 
		] );
	}
	
	/**
	 * Displays a single CardPackage model.
	 *
	 * @param integer $id        	
	 * @return mixed
	 */
	public function actionView($id) {
		$model = $this->findModel ( $id );
		
		$query = Card::find ();
		$query->innerJoin ( "card_card_package_assignment", "card_card_package_assignment.id_card = card.id_card " );
		$query->andWhere ( [ 
				'card_card_package_assignment.id_card_package' => $id 
		] );
		
		$dataProvider = new ActiveDataProvider ( [ 
				'query' => $query 
		] );
		
		return $this->render ( 'view', [ 
				'model' => $model,
				'dataProvider' => $dataProvider 
		] );
	}
	public function actionDownload($id) {
		$model = $this->findModel ( $id );
		
		$model->updateCounters ( [ 
				'printed' => 1 
		] );
		
		$query = Card::find ();
		$query->innerJoin ( "card_card_package_assignment", "card_card_package_assignment.id_card = card.id_card " );
		$query->andWhere ( [ 
				'card_card_package_assignment.id_card_package' => $id 
		] );
		
		$cards = $query->all ();
		
		$numbers = [ ];
		foreach ( $cards as $card ) {
			$numbers [] = $card->number;
		}
		
		$this->generateXLS ( $model, $numbers );
	}
	
	/**
	 * Creates a new CardPackage model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 *
	 * @return mixed
	 */
	public function actionCreate() {
		$model = new CardPackage ();
		$model->id_user = \Yii::$app->user->id;
		$model->printed = 0;
		
		if ($model->load ( Yii::$app->request->post () ) && $model->validate ()) {
			$conn = \Yii::$app->db;
			$tx = $conn->beginTransaction ();
			
			$model->save ( false );
			
			$count = $model->count;
			
			$numGen = new FreeUniqueCardNumberGenerator ( [ 
					'count' => $model->count,
					'prefix' => '10' 
			] );
			
			$numGen->generate ();
			
			$numbers = $numGen->cache;
			
			try {
				foreach ( $numbers as $number ) {
					
					$card = new Card ();
					$card->number = $number;
					$card->type = Card::TYPE_RFID;
					$card->status = Card::STATUS_ACTIVE;
					$card->save ( false );
					
					$cardAssignment = new CardCardPackageAssignment ();
					$cardAssignment->id_card = $card->id_card;
					$cardAssignment->id_card_package = $model->id_card_package;
					$cardAssignment->save ( false );
				}
				$tx->commit ();
				
				return $this->redirect ( [ 
						'index' 
				] );
			} catch ( \Exception $e ) {
				$tx->rollBack ();
			}
			
			return $this->render ( 'create', [ 
					'model' => $model 
			] );
		} else {
			return $this->render ( 'create', [ 
					'model' => $model 
			] );
		}
	}
	protected function generateXLS($model, $numbers) {
		$objPHPExcel = new \PHPExcel ();
		
		$sheet = $objPHPExcel->setActiveSheetIndex ( 0 );
		
		// $row = 1;
		// $sheet->setCellValue('A'.$row, "Termék név")
		// ->setCellValue('B'.$row, "Eladási ár")
		// ->setCellValue('C'.$row, "Kassza")
		// ->setCellValue('D'.$row, "Eladott mennyiség")
		// ->setCellValue('E'.$row, "Eladás összege");
		$row = 0;
		
		foreach ( $numbers as $number ) {
			$row ++;
			$sheet->setCellValue ( 'A' . $row, $number );
		}
		
		$fileName = "kartya_csomag";
		$fileName .= "_" . $model->id_card_package;
		$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 ();
	}
	public function actionImport() {
		$model = new CardPackageImportForm ();
		
		if (Yii::$app->request->isPost) {
			$model->file = UploadedFile::getInstance ( $model, 'file' );
			
		
			
			if ($model->validate ()) {
				
				
				// print_r($model->file);
				// $model->message = "ok";
				$file = $model->file->tempName;
				$xlsUtil = new XLSUtil ();
				$xlsUtil->loadFromFileName ( $file );
				$array = $xlsUtil->toArray ();
				
// 				print_r($array);
// 				print_r( array_column($array, 2));

// 				foreach ($array as $item ){
// 					echo $item[2];
// 				}
				
				foreach ( $array as $row ) {
					try {
						$tx = \Yii::$app->db->beginTransaction ();
						
						$card = Card::find ()->andWhere ( [ 
								'number' =>   $row [0]  
						] )->one ();
						
						if ( isset( $card )) {
							$card->rfid_key = Helper::fixAsciiChars( $row [2 ] );
							$card->save(false);
						}else{
							throw new \Exception("Card not found");
						}
						
						
						$tx->commit ();
						
						$model->done = $model->done + 1;
					} catch ( \Exception $e ) {
						$tx->rollBack ();
						$model->failed = $model->failed + 1;
						\Yii::error ( "Failed to import card rfid: " . print_r ( $row, true ) );
					}
				}
				
				\Yii::$app->session->setFlash ( 'success', "Az importálás eredménye: sikeres:" . $model->done . "; Sikertelen: " . $model->failed );
				
				\Yii::info('Importálás: sikeres: ' .$model->done . " , sikertelen: " . $model->failed);
				return $this->redirect ( [ 
						'card-package/import' 
				] );
			}
		}
		
		return $this->render ( "import", [ 
				'model' => $model 
		] );
	}
	
	/**
	 * Updates an existing CardPackage 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_card_package 
			] );
		} else {
			return $this->render ( 'update', [ 
					'model' => $model 
			] );
		}
	}
	
	/**
	 * Deletes an existing CardPackage 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' 
		] );
	}
	
	/**
	 * Finds the CardPackage model based on its primary key value.
	 * If the model is not found, a 404 HTTP exception will be thrown.
	 *
	 * @param integer $id        	
	 * @return CardPackage the loaded model
	 * @throws NotFoundHttpException if the model cannot be found
	 */
	protected function findModel($id) {
		if (($model = CardPackage::findOne ( $id )) !== null) {
			return $model;
		} else {
			throw new NotFoundHttpException ( 'The requested page does not exist.' );
		}
	}
}
