<?php

namespace console\controllers;

use common\models\Card;
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;
use yii\helpers\Html;
use common\models\Subscriber;

class TicketController extends Controller {

	public function actionIndex() {
		$connection = \Yii::$app->db;

        $command = $connection->createCommand ( Card::$SQL_CLEARS_STATUS_DOOR );
		$result = $command->execute ();
		\Yii::info ( "Tickets updated flag door: " . $result );

        $command = $connection->createCommand ( Ticket::$SQL_UPDATE );
		$result = $command->execute ();
		\Yii::info ( "Tickets updated: " . $result );


        $command = $connection->createCommand ( Card::$SQL_FIX_KEY_STATUS );
		$result = $command->execute ();
	}
	
	 /**
	 * 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.id_customer as customer_id_customer',
					'customer.newsletter_token as customer_newsletter_token',
					'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' , new Expression('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'];

				if ( !empty($recepientEmail)){
				
					$model = new WarnMailModel(
							[
									'day' => $dayCount,
									'company' => Helper::getCompanyName(),
									'ticketTypeName' => $recepient['ticket_type_name'],
									'ticketTypePriceBrutto' => $recepient['ticket_type_price_brutto'],
									'customerName' => $recepient['customer_name'],
									'idCustomer' => $recepient['customer_id_customer'],
									'newsletterToken' => $recepient['customer_newsletter_token'],
							]	
						);
						
						$message = \Yii::$app->mailer->compose ( 'warn_expire', [ 
								'model' => $model,
						] );
						
						$message
						->setFrom ( [ "noreply@fitnessadmin.hu" =>  Helper::getCompanyName()  ] )
						->setTo ( $recepientEmail )
						->setSubject ( "Értesítés - " . Helper::getCompanyName()." - Bérleted ".$dayCount." nap múlva lejár" )
						->send ();
						
						Log::logC([
								'type' => Log::$TYPE_TICKET_EXPIRE_SENT,
								'message' => "Bérlet lejár üzenet: " . $recepient['customer_name']."  [id_customer=". $recepient['customer_id_customer'] ."]",
								'id_customer' => $recepient['customer_id_customer']
						]);
				}
			}
		}
	}
	
	
	
	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);
		
		if ( \Yii::$app->params['newsletter_enabled'] != true ){
			return;
		}
		
		
		$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");
		}
		
		 $subscribers = Subscriber::find()->andWhere(['status' => 1])->all();
		
		 
		
		\Yii::info("Hírlevél küldése " .count($subscribers) . " előfizetőnek!" );
		
		$i = 0;
		
		foreach ($newsletters as $newsletter ){
			$i = 0;
			Log::logC([
					'type' => Log::$TYPE_NEWSLETTER_SEND_START,
					'message' => "Hírlevél küldés indítása[id_newsletter=" . $newsletter->id_newsletter ."]"
			]);
			foreach ($subscribers as $subscriber ){
				 
				try{
					$log = "Sending Newsletter";
					$log .="[id_newsletter=".$newsletter->id_newsletter ."]";
					$log .="[subscriber_email=" . $subscriber->email . "]";
					$log .="[subscriber_id=" . $subscriber->id_subscriber . "]";
					\Yii::info($log);
					$message = \Yii::$app->mailer->compose (  );
					
					$replacePairs = [
						'{vendeg_neve}' => $subscriber->name
					];
					
					$mailBody = $newsletter->body;
					$mailBody = strtr($mailBody, $replacePairs );
					
					$mailBody .="<hr>";
					$mailBody .="Leiratkozás hírlevélről:";
					$mailBody .= Html::a("Leiratkozom",Helper::getWebUrl() ."/frontend/web/index.php?r=site/newsletter-unsubscribe&id=".$subscriber->id_subscriber."&token=". $subscriber->token );
					
					$mailSubject = $newsletter->subject;
					$mailSubject = strtr($mailSubject, $replacePairs );
					
					$message
					->setFrom ( [ \Yii::$app->params['newsletter_from']  => Helper::getCompanyName() ])
					->setTo ( [ 
							$subscriber->email => $subscriber->name
					])
					->setHtmlBody( $mailBody )
					->setSubject ( $mailSubject	 )
					->send ();
					
					Log::logC([
						'type' => Log::$TYPE_NEWSLETTER_SENT,
						'message' => "Hírlevél küldés[id_newsletter=" . $newsletter->id_newsletter ."][id_subscriber=" . $subscriber->id_subscriber ."]"
					]);
					
				}catch (\Exception $ex){
					\Yii::error("Nem sikerült hírlevelet kikülden: Hírlevél azonosító=" .$newsletter->id_newsletter. ";Előfizető azonosító ". $subscriber->id_subscriber )	;			
				}
				
				$i++;
			}
			$newsletter->sent = Newsletter::$SENT_TRUE; 
			$newsletter->sent_at = Helper::getDateTimeString();
			$newsletter->save(false);
			
			Log::logC([
					'type' => Log::$TYPE_NEWSLETTER_SEND_END,
					'message' => "Hírlevél küldés befejezése[id_newsletter=" . $newsletter->id_newsletter ."]"
			]);
			
// 			Log::log([
// 					'type' =>Log::$TYPE_LOGIN,
// 					'message' => $message
// 			]);
		}
		
	}
	
	
}