<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use common\models\Card;
use common\models\Customer;
use common\models\Ticket;
use common\models\Account;
use yii\web\UploadedFile;
use common\models\TicketInstallmentRequest;
use common\models\Ugiro;
use common\components\giro\GiroBeszed;
use yii\helpers\FileHelper;
use yii\helpers\Inflector;
use yii\helpers\BaseInflector;
use common\models\UgiroRequestAssignment;
use yii\db\Query;

/**
 * ContactForm is the model behind the contact form.
 * @property \Yii\web\UploadedFile $file
 */
class GiroKotegForm extends Model{
	
	public $action;
	
	public $requests;
	public $content;
	public $koteg;
	public $success;
	
	public $timestamp_teljesites_datum;
	public $teljesitesi_datum;
	
	public function rules(){
		return [
			[['action'], 'safe']	,
				[[ 'teljesitesi_datum',  ], 'required'],
			[[ 'teljesitesi_datum',  ], 'date', 'format' =>Yii::$app->formatter->dateFormat  , 'timestampAttribute' => 'timestamp_teljesites_datum' ,'timestampAttributeFormat' => 'yyyy-MM-dd' ,'timeZone' => 'UTC' ],
				
			['teljesitesi_datum', "validateRequestCount"],
			['teljesitesi_datum', "validateMaxPlusDay"],
			
		];
	}
	
	public function validateRequestCount($a,$p){
		$this->readRequests();
		if ( count( $this->requests ) == 0 ){
			$this->addError("teljesitesi_datum", "Megbízások száma 0!" );
		}
	}
	
	/*
	 * A teljesítési dátum max 8 nappal lehet a létrehozás dátumán túl
	 * */
	public function validateMaxPlusDay(){
		$date = new \DateTime('now');
		$date->add(new \DateInterval('P8D'));
		$date->setTime(0,0,0);
		
		$td = new \DateTime();
		$td->setTimestamp( strtotime( $this->timestamp_teljesites_datum ) );
		$date->setTime(0,0,0);
		 
		if ( $td > $date){
			$this->addError( "teljesitesi_datum", "Érvénytelen terhelési dátum. A terhelési dátum max +8 nap lehet");
		} 
		
	}
	
	public function createKoteg(){
		$this->readRequests();
		$this->success = true;
		if ( count( $this->requests ) > 0 ){
			$connection = \Yii::$app->db;
			$transaction = $connection->beginTransaction();
			 
			try {
				$this->createUGiroKoteg();
				$this->assignRequestsToUgiro();
				$this->changeRequestsStatusToSent();
				$this->generateFileContent();
				$this->saveFile();
				
				if ($this->success) {
					$transaction->commit();
					\Yii::$app->session->setFlash('success',"Fájl létrehozva");
					return true;
				} else {
					$transaction->rollback();
					throw new NotFoundHttpException( "Hiba történt!");
				}
				
			} catch (\Exception $e) {
				$transaction->rollback();
				throw $e;
			}
		}else{
			\Yii::$app->session->setFlash('danger', "Megbízások száma 0!");
			return false;
		}
	}
	
	public function changeRequestsStatusToSent(){
		foreach ($this->requests as $request){
			$request->status = TicketInstallmentRequest::$STATUS_SENT;
			$this->success  &= $request->save(false);
		}
	}
	
	public function assignRequestsToUgiro(){
		$i = 0;
		foreach ($this->requests as $request){
			$i++;
			$request->number = $i;
			$request->save(false);
			$assignment = new UgiroRequestAssignment();
			$assignment->id_request = $request->id_ticket_installment_request;
			$assignment->id_ugiro = $this->koteg->id_ugiro;
			$this->success  &= $assignment->save(false);
		}
	}
	
	public function createUGiroKoteg(){
		$this->koteg = new Ugiro();
		$this->koteg->status = Ugiro::$STATUS_SENT;
		$this->koteg->id_user = \Yii::$app->user->id;
		
		$this->koteg->datum = date('Ymd');
		$this->koteg->terhelesi_datum = $this->teljesitesi_datum;
		
		$lastNumber = $this->loadLastNumber($this->koteg->datum);
		$nextNumber = $lastNumber+1;
		$this->koteg->number = $nextNumber;
		
		$this->success &= $this->koteg->save(false);
	}
	
	
	public function loadLastNumber($datum){
		$query  = new Query();
		$query->select(['coalesce(max(number),0)']);
		$query->from('ugiro');
		$query->andWhere(["datum" => $datum]);
		return $query->scalar();
	}
	
	public function readRequests(){
		$this->requests = TicketInstallmentRequest::find()->andWhere(['status' => TicketInstallmentRequest::$STATUS_MARKED_TO_SEND])->all();
	}
	
	public function generateFileContent(){
		$terhelesi_datum =\Yii::$app->formatter->asDate($this->timestamp_teljesites_datum, 'php:Ymd');
		$this->content = GiroBeszed::createFileContent($this->koteg->number, $this->koteg->datum, $this->requests,$terhelesi_datum);
	}
	
	public function saveFile( ) {
// 		$data = static::transliterate($this->content);
		$data = $this->content;
		$data = iconv("utf-8","ASCII",$data);
		$path = Ugiro::$PATH_MEGBIZAS . DIRECTORY_SEPARATOR ."giro" . $this->koteg->id_ugiro."_". date('Ymd' ) .".txt";
		$filename =  Yii::getAlias('@backend/web').DIRECTORY_SEPARATOR .$path;
		$dir = Yii::getAlias('@backend/web').DIRECTORY_SEPARATOR .Ugiro::$PATH_MEGBIZAS;
		$this->koteg->path = $path;
		$this->koteg->save(false);
		if(!FileHelper::createDirectory($dir)){
            throw new HttpException(500, 'Cannot create "'.$dir.'". Please check write permissions.');
        }
		$myfile = fopen($filename,'a');
		fwrite($myfile, $data);
		fclose($myfile);
	}
	
	public static function transliterate($string)
	{
			return str_replace(array_keys(BaseInflector::$transliteration), BaseInflector::$transliteration, $string);
	}
	
	/**
	 * @return boolean if intl extension is loaded
	 */
	protected static function hasIntl()
	{
		return extension_loaded('intl');
	}
}