<?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\components\Helper;

/**
 * ContactForm is the model behind the contact form.
 * @property \Yii\web\UploadedFile $file
 */
class NewsletterTestForm extends Model{
	
	public $customer_name;
	public $email;
	public $newsletter;//init param
	
	private $_customer;
	
	public function rules(){
		return [
			[['customer_name','email'], 'required'],	
			[['email'], 'email'],	
			[['customer_name'], 'string'],	
			[['customer_name'], 'validateCustomer'],	
		];
	}
	
	public function attributeLabels(){
		return [
			'email' => "E-mail",
			'customer_name' => "Vendég neve"
		];
	}
	
	public function validateCustomer( $attribute, $params ) {

		$customer = Customer::find()->andWhere(['like','name',$this->customer_name])->one();
		if ( !isset($customer)){
			$this->addError($attribute,"Vendég nem található");
		}else{
			$this->_customer = $customer;
		}
		
	}
	
	public function sendEmail(){
		$newsletter = $this->newsletter;
		$message = \Yii::$app->mailer->compose (  );
		
		$replacePairs = [
				'{vendeg_neve}' => $this->_customer->name
		];
		
		$mailBody = $newsletter->body;
		$mailBody = strtr($mailBody, $replacePairs );
		$mailSubject = $newsletter->subject;
		$mailSubject = strtr($mailSubject, $replacePairs );
		
		$message
		->setFrom ( [ \Yii::$app->params['newsletter_from']  => Helper::getCompanyName() ])
		->setTo ( [
				$this->email ])
				->setHtmlBody( $mailBody )
				->setSubject ( $mailSubject	 )
				->send ();
	}
	
}