<?php

namespace console\controllers;

use Yii;
use yii\console\Controller;
use common\models\Ticket;
use common\models\Customer;
use yii\db\Query;
use yii\db\Expression;
use common\components\WarnMailModel;
use common\components\Helper;
use common\models\Newsletter;
use common\models\Log;

class TicketController extends Controller {
	public function actionIndex() {
		$connection = \Yii::$app->db;
		$command = $connection->createCommand ( Ticket::$SQL_UPDATE );
		$result = $command->execute ();
		\Yii::info ( "Tickets updated: " . $result );
		echo "Tickets updated: " . $result;
	}
	
	 /**
	 * Automatikus email figyelmeztetés küldése vendégeknek, akiknek a beállított nap(ok) múlva
	 * lejár a bérlete 
	;*
	 */
	public function actionWarnExpire() {
		\Yii::info ( "Bérlet lejár figyelmeztetés küldése" );
		$warnEnabled = \Yii::$app->params ['warn_ticket_expire_enabled'];
		$warnDays = \Yii::$app->params ['warn_ticket_expire_days'];
		
		if (! $warnEnabled) {
			\Yii::info ( "Bérlet lejár figyelmeztetés küldése kikapcsolva" );
			return;
		}
		
		if (! isset ( $warnDays ) || count ( $warnDays ) == 0) {
			\Yii::info ( "Bérlet lejár figyelmeztetés küldése: nincsenek napok beállítva" );
			return;
		}
		
		foreach ( $warnDays as $warnDayConfig ) {
			$dayCount = $warnDayConfig ['day'];
			
			$query = new Query ();
			$query->distinct ( true );
			$query->select ( [ 
					'customer.email as customer_email',
					'customer.name as customer_name',
					'ticket_type.name as ticket_type_name',
					'ticket_type.price_brutto as ticket_type_price_brutto' 
			]
			 );
			$query->from ( 'customer' );
			$query->innerJoin ( "ticket", "customer.id_customer_card = ticket.id_card " );
			$query->innerJoin ( "ticket_type", "ticket.id_ticket_type = ticket_type.id_ticket_type " );
			$query->andWhere ( [ 
					'ticket.status' => Ticket::STATUS_ACTIVE ,
					'customer.warn_mail_ticket_expire_enabled' => Customer::$ENABLED
			] );
			$query->andWhere ( [ 
					'ticket.end' => new Expression ( 'DATE_ADD(CURDATE(),INTERVAL ' . $dayCount . ' DAY)' ) 
			] );
			
			$query->andWhere([
					['<','ticket.usage_count' ,'ticket.max_usage_count']
			]);
			
			$recepients = $query->all ();
			
			\Yii::info ( "Bérlet lejár figyelmeztetés küldése: " . $dayCount . " nap múlva " 
					. count ( $recepients ) . " vendég bérlete jár le."
					);
			
			
			foreach ( $recepients as $recepient ) {
			
			$recepientEmail = $recepient['customer_email'];
				
			$model = new WarnMailModel(
					[
							'day' => $dayCount,
							'company' => Helper::getCompanyName(),
							'ticketTypeName' => $recepient['ticket_type_name'],
							'ticketTypePriceBrutto' => $recepient['ticket_type_price_brutto'],
							'customerName' => $recepient['customer_name']
					]	
				);
				
				$message = \Yii::$app->mailer->compose ( 'warn_expire', [ 
						'model' => $model,
				] );
				
				$message
				->setFrom ( "noreply@fitnessadmin.hu" )
				->setTo ( $recepientEmail )
				->setSubject ( "Értesítés - " . Helper::getCompanyName()." - Bérleted ".$dayCount." nap múlva lejár" )
				->send ();
			}
		}
	}
	
	
	
	public function actionDaily(){
		set_time_limit(0);
		$this->actionWarnExpire();
	}
	
	public function actionWeekly(){
		set_time_limit(0);
		$this->actionNewsletter();
	}
	
	public function actionNewsletter(){
		set_time_limit(0);
		$q1 = Newsletter::find();
		$q1->andWhere(['sent' => Newsletter::$SENT_NOT]);
		$q1->andWhere(['status' => Newsletter::$STATUS_ACTIVE]);
		
		$newsletters = $q1->all();
		
		if ( count($newsletters) == 0 ){
			\Yii::info("Nincs elküldendő hírlevél");
		}
		
		$q2 = new Query();
		$q2->distinct();
		$q2->select(['customer.email as customer_email','customer.name as customer_name']);
		$q2->from("customer");
		$q2->innerJoin("ticket","ticket.id_card = customer.id_customer_card");
// 		$q2->andWhere(['status' =>  Customer::STATUS_ACTIVE ]);
		$q2->andWhere(['newsletter' =>  Customer::$ENABLED ]);
		$q2->andWhere(['>=' ,'ticket.end',new Expression('DATE( DATE_ADD(NOW(),INTERVAL -3 MONTH) )')]);
		
		
		$customers = $q2->all();
		
		\Yii::info("Hírlevél küldése " .count($customers) . " vendégnek!" );
		
		$i = 0;
		
		foreach ($newsletters as $newsletter ){
			$i = 0;
			foreach ($customers as $customer ){
				 
				try{
					$log = "Sending Newsletter";
					$log .="[id_newsletter=".$newsletter->id_newsletter ."]";
					$log .="[customer_email=" . $customer['customer_email'] . "]";
					\Yii::info($log);
					$message = \Yii::$app->mailer->compose (  );
					
					$replacePairs = [
						'{vendeg_neve}' => $customer['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 ( [ 
							$customer['customer_email']
					])
					->setHtmlBody( $mailBody )
					->setSubject ( $mailSubject	 )
					->send ();
					
				}catch (\Exception $ex){
					\Yii::error("Nem sikerült hírlevelet kikülden: Hírlevél azonosító=" .$newsletter->id_newsletter. ";Vendég azonosító ". $customer['customer_name'] )	;			
				}
				
				$i++;
			}
			$newsletter->sent = Newsletter::$SENT_TRUE; 
			$newsletter->sent_at = Helper::getDateTimeString();
			$newsletter->save(false);
			
// 			Log::log([
// 					'type' =>Log::$TYPE_LOGIN,
// 					'message' => $message
// 			]);
		}
		
	}
	
	
}