<?php

namespace frontend\controllers;

use Yii;
use common\models\Contract;
use frontend\models\ContractSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Card;
use common\models\TicketInstallmentRequest;
use common\models\Ticket;
use common\models\Transfer;
use common\models\Account;
use common\components\Helper;
use common\models\Sale;
use common\models\Product;
use common\models\ShoppingCart;
use common\models\Customer;
use frontend\models\ContractForm;

/**
 * ContractController implements the CRUD actions for Contract model.
 */
class ContractController extends Controller {
	public function behaviors() {
		return [ 
				'verbs' => [ 
						'class' => VerbFilter::className (),
						'actions' => [ 
								'delete' => [ 
										'post' 
								],
								'payout' => [ 
										'post' 
								],
								'cancel' => [ 
										'post' 
								] 
						] 
				] 
		];
	}
	
	/**
	 * Lists all Contract models.
	 *
	 * @return mixed
	 */
	public function actionIndex($id_card) {
		$card = Card::findOne ( $id_card );
		
		if (! isset ( $card ))
			throw new NotFoundHttpException ( 'A bérlet nem található' );
		
		$searchModel = new ContractSearch ();
		$searchModel->card = $card;
		$searchModel->customer = $card->customer;
		$dataProvider = $searchModel->search ( Yii::$app->request->queryParams );
		
		return $this->render ( 'index', [ 
				'searchModel' => $searchModel,
				'dataProvider' => $dataProvider 
		] );
	}
	
	/**
	 * Displays a single Contract model.
	 *
	 * @param integer $id        	
	 * @return mixed
	 */
	public function actionView($id) {
		$model = $this->findModel ( $id );
		$customer = $model->customer;
		$card = $customer->card;
		
		$installments = TicketInstallmentRequest::find ()->andWhere ( [ 
				'id_contract' => $model->id_contract 
		] )->orderBy ( [ 
				'ticket_installment_request.priority' => SORT_ASC 
		] )->all ();
		
		return $this->render ( 'view', [ 
				'model' => $model,
				'intstallments' => $installments,
				'card' => $card 
		] );
	}
	
	/**
	 * Creates a new Contract model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 *
	 * @return mixed
	 */
	public function actionCreate() {
		$model = new Contract ();
		
		if ($model->load ( Yii::$app->request->post () ) && $model->save ()) {
			return $this->redirect ( [ 
					'view',
					'id' => $model->id_contract 
			] );
		} else {
			return $this->render ( 'create', [ 
					'model' => $model 
			] );
		}
	}
	
	/**
	 * Updates an existing Contract 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_contract 
			] );
		} else {
			return $this->render ( 'update', [ 
					'model' => $model 
			] );
		}
	}
	
	/**
	 * Deletes an existing Contract 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' 
		] );
	}
	
	/**
	 * EGY RÉSZLET KIFIZETÉSE
	 */
	public function actionPayout($id) {
		$part = TicketInstallmentRequest::findOne ( $id );
		$contract = $part->contract;
		$customer = $contract->customer;
		$card = $customer->card;
		
		$connection = \Yii::$app->db;
		$transaction = $connection->beginTransaction ();
		try {
			
			$result = Transfer::sellContractTicket ( $contract, $part, Account::readDefaultObject (), Transfer::STATUS_NOT_PAID, Transfer::PAYMENT_METHOD_CASH, true );
			$transfer = $result [0];
			$ticket = $result [1];
			if ($part->status != TicketInstallmentRequest::$STATUS_REJECTED) {
				$contract->part_required = $contract->part_required + 1;
			}
			
			$contract->part_paid = $contract->part_paid + 1;
			
			if ($contract->part_paid >= $contract->part_required) {
				$contract->status = Contract::$STATUS_PAID;
			} else {
				$contract->status = Contract::$STATUS_NOT_PAID;
			}
			
			$contract->save ( false );
			
			$part->status = TicketInstallmentRequest::$STATUS_ACCEPTED_MANUAL;
			$part->id_transfer = $transfer->id_transfer;
			$part->request_processed_at = Helper::getDateTimeString ();
			$part->id_ticket = $ticket->id_ticket;
			
			$part->save ( false );
			$transaction->commit ();
			\Yii::$app->session->setFlash ( 'success', "Részlet a bevásárló kosárba helyezve!" );
		} catch ( Exception $e ) {
			$transaction->rollback ();
			Yii::error ( "Nem sikerült a kifizetés." );
		}
		
		return $this->redirect ( [ 
				'view',
				'id' => $contract->id_contract 
		] );
	}
	
	/**
	 * EGY RÉSZLET KIFIZETÉSE
	 */
	public function actionCancel($id,$flag) {
		$contract = $this->findModel ( $id );
		
		if ( $flag != Contract::$FLAG_CANCELED && $flag != Contract::$FLAG_CANCELED_2){
			\Yii::error("A felmondási státusz nem található! ($flag)");
			throw new NotFoundHttpException("Az oldal nem található!");
			
		}
		
		$customer = $contract->customer;
		$card = $customer->card;
		
		if ($contract->canCancel ()) {
			$connection = \Yii::$app->db;
			$transaction = $connection->beginTransaction ();
			try {
				
				$contract->flag = $flag;
				$contract->save ();
				$requests = $contract->requests;
				$buntetes = 0;
				
				foreach ( $requests as $request ) {
					/** @var common\models\TicketInstallmentRequest $request*/
					if ($request->isStatusAccepted ()) {
						$buntetes = $buntetes + 1;
					} else {
						$request->status = TicketInstallmentRequest::$STATUS_CANCELED;
						$request->save ( false );
					}
				}
				
				$productBuntetes = Product::find ()->andWhere ( [ 
						'product_number' => Product::$BUNTETES 
				] )->one ();
				
				if (isset ( $productBuntetes )) {
					if ($buntetes > 0) {
						
						$sale = new Sale ();
						$sale->id_account = Account::readDefault ();
						$sale->id_product = $productBuntetes->id_product;
						$sale->status = Sale::STATUS_NOT_PAID;
						$sale->type = Sale::TYPE_PRODUCT;
						$sale->item_price = $productBuntetes->sale_price;
						$sale->count = $buntetes;
						$sale->money = $buntetes * $sale->item_price;
						$sale->id_user = \Yii::$app->user->id;
						
						$sale->save ( false );
						
						$transfer = Transfer::createProductTransfer ( $sale, Account::readDefaultObject (), null, null, $sale->count, $productBuntetes, Transfer::STATUS_NOT_PAID, $customer );
						$transfer->payment_method = Transfer::PAYMENT_METHOD_CASH;
						
						$transfer->id_user = Yii::$app->user->id;
						
						$transfer->save ( false );
						
						$cart = new ShoppingCart ();
						$cart->id_customer = $customer->id_customer;
						$cart->id_transfer = $transfer->id_transfer;
						$cart->save ( false );
					}
				}
				
				$transaction->commit ();
				\Yii::$app->session->setFlash ( 'success', "Szerződés felbontva!" );
				
				return $this->redirect ( [ 
						'product/sale',
						'number' => $card->number 
				] );
			} catch ( Exception $e ) {
				$transaction->rollback ();
				Yii::error ( "Szerződés felbontása nem sikerült!" );
			}
		} else {
			\Yii::$app->session->setFlash ( 'danger', "Szerződést nem lehet felbontani!" );
		}
		
		return $this->redirect ( [ 
				'view',
				'id' => $contract->id_contract 
		] );
	}
	public function actionMake($id) {
		$customer = Customer::findOne ( $id );
		
		if (! isset ( $customer )) {
			throw new Exception ( "Az oldal nem található" );
		}
		
		
		$model = new ContractForm ( [ 
				'customer' => $customer ,
				'idUser' => \Yii::$app->user->id,
				'idAccount' => Account::readDefault ()
		] );
		
		$model->started_at = date(date('Y.m.d'));
		
		
		$model->fillOut ();
		
		if ($model->load ( Yii::$app->request->post () ) && $model->validate ()) {
			
			$connection = \Yii::$app->db;
			$transaction = $connection->beginTransaction ();
			try {
				
				$model->make ();
				$transaction->commit();
				return $this->redirect ( [ 
						'contract/view',
						'id' => $model->contract->id_contract
				] );
			} catch ( \Exception $e ) {
				$transaction->rollBack();
				\Yii::$app->session->setFlash('danger', $e->getMessage());
			}
		}
		
		return $this->render ( '_make_contract', [ 
				'model' => $model 
		] );
	}
	
	public function actionContract($id){
		$model = $this->findModel($id);
		 
		//$mpdf=new \mPDF('utf-8', 'A4');
		$mpdf=new \mPDF('utf-8','A4','','','15','15','26','18','3');
		
		$mpdf->SetHTMLHeader("<div style='height: 80px; text-align: right;  ' ><img    height='80px' src='" . \Yii::getAlias("@webroot") . DIRECTORY_SEPARATOR. "images" . DIRECTORY_SEPARATOR . "cutler_contract_pdf_header.jpg'></div>");
		$mpdf->setFooter('{PAGENO} / {nb}');
		$mpdf->WriteHTML($this->renderPartial('_contract', [
				'model' => $model,
		]));
		
		$fileName = "szerzodes";
		$fileName .=  "." . $model->customer->name;
		$fileName .=  "." .\Yii::$app->formatter->asDate( $model->created_at, "Y");
		$fileName .=".pdf";
		$mpdf->Output($fileName, 'D');//download file
// 		$mpdf->Output('szerzodes.pdf', 'I');//open in new tab
		exit;
	}
	
	/**
	 * Finds the Contract model based on its primary key value.
	 * If the model is not found, a 404 HTTP exception will be thrown.
	 *
	 * @param integer $id        	
	 * @return Contract the loaded model
	 * @throws NotFoundHttpException if the model cannot be found
	 */
	protected function findModel($id) {
		if (($model = Contract::findOne ( $id )) !== null) {
			return $model;
		} else {
			throw new NotFoundHttpException ( 'The requested page does not exist.' );
		}
	}
}
