<?php
namespace common\components\accountstate;


use yii\base\Object;
use common\models\User;
use common\models\Account;
use common\models\AccountState;
use common\components\DailyListing;

/**
 * @property common\models\AccountState $model
 * */
class AccountStateMail extends Object {
	
	
	public $controller;
	public $model;
	public $user;
	public $account;
	public $message;
	public $details;
	
	public function init(){
		
		$this->user = User::findOne($this->model->id_user);
		$this->account = Account::findOne($this->model->id_account);
		
		$this->details = null;
		
		if ($this->model ->isTypeClose ()) {
		
			$prev;
			if ($this->model->type == AccountState::TYPE_CLOSE) {
				if (isset ( $this->model->prev_state )) {
					$prev = AccountState::findOne ( $this->model->prev_state );
				}
				if (isset ( $prev )) {
					$this->model ->start_date = $prev->created_at;
				}
			}
			$this->details = new DailyListing();
			$this->details->loadAccountState ( $this->model );
		
			$this->details->readModeAccountState();
			
// 			$this->details->readTotalEasy ();
// 			$this->details->readTotalDetailed ();
// 			$this->details->readTotalMedium ();
		}
	}

	
	public function sednMail(){
		
		$subject =  $this->model->isTypeOpen()  ? "Kassza nyitás " : "Kassza zárás";
		$subject .= " - " . $this->user->username ." - ". $this->account->name;
			
		$this->message = \Yii::$app->mailer->compose('account_state', [
				'model' => $this->model,
				'details' => $this->details
		]);
		
		$this->attachPdf();
		
		try{
			$this->message->setFrom(\Yii::$app->params['infoEmail'])
			->setTo( \Yii::$app->params['notify_mail'] )
			->setSubject($subject )
			->send();
		}catch (\Exception $e){
			\Yii::error("Nem sikerült elküldeni a kassza müvelet emailt");
		}
		
	}
	
	
	protected function attachPdf(){
		$mpdf=new \mPDF('utf-8', 'A4-L');
		$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->controller->renderPartial("@common/views/account-state/account_state_pdf", [
				'model' => $this->model,
				'details' => $this->details
		]));
		$type = $this->model->isTypeOpen() ? "kassza_nyitas" : "kassza_zaras";
		$dt= "_letrehozva_".date("Ymd_His"). "_" . $this->user->username;
		$fn= $type .$dt.".pdf";
		$content = $mpdf->Output($fn, 'S');
		
		$this->message->attachContent($content, ['fileName' => $fn, 'contentType' => 'application/pdf']);
	}
	
	
	
	
}