<?php

namespace Drupal\basket;

class BasketMailCenter{

	protected static $TemplateInfo;
	protected static $getLastOrder;
	protected static $Basket;
	protected static $mailManager;

	function __construct(){
		self::$Basket = \Drupal::service('Basket');
		self::$mailManager = \Drupal::service('plugin.manager.mail');;
	}
	public function send($email, $params){
		$langcode = \Drupal::currentUser()->getPreferredLangcode();
		$params = [
			'subject'		=> $this->getSubject($params),
			'message'		=> $this->getHtml($params)
		];
		self::$mailManager->mail('basket', 'send', trim($email), $langcode, $params, NULL, TRUE);
	}
	public function getSubject($params){
		if(empty($params['template'])) return '';
		$TemplateInfo = $this->getTemplateInfo($params['template']);
		if(!empty($TemplateInfo['subject'])){
			$langPrefix = '';
			if(!empty($TemplateInfo['language'])){
				$langPrefix = '_'.\Drupal::languageManager()->getCurrentLanguage()->getId();
			}
			$settings = self::$Basket->getSettings('templates', $params['template'].$langPrefix);
			if(!empty($settings['config']['subject'])){
				$getLastOrder = $this->getLastOrder($params);
				$subject = [
					'#type'			=> 'inline_template',
					'#template'		=> $settings['config']['subject'],
					'#context'		=> $this->getContext($params['template'], [
						'order'			=> $getLastOrder
					])
				];
				return \Drupal::token()->replace(
					\Drupal::service('renderer')->render($subject), [
						'user'		=> isset($params['uid']) ? \Drupal\user\Entity\User::load($params['uid']) : \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()),
						'node'		=> !empty($params['nid']) ? \Drupal\node\Entity\Node::load($params['nid']) : NULL
					], [
						'clear' 	=> TRUE
					]
				);;
			}
		}
		return 'Subject';
	}
	public function getHtml($params){
		if(empty($params['template'])) return '';
		// ---
		$getLastOrder = $this->getLastOrder($params);
		if(empty($params['nid']) && !empty($getLastOrder->nid)){
			$params['nid'] = $getLastOrder->nid;
		}
		if(empty($params['uid']) && !empty($params['nid'])){
			$order = \Drupal\node\Entity\Node::load($params['nid']);
			if(!empty($order) && !empty($order->get('uid')->target_id)){
				$params['uid'] = $order->get('uid')->target_id;
			}
		}
		// body
		$settings_html = self::$Basket->getSettings('templates', 'notification_html');
		$html = [
			'#type'			=> 'inline_template',
			'#template'		=> $this->getTemplate($settings_html),
			'#context'		=> $this->getContext('notification_html', [
				'order'			=> $getLastOrder
			])
		];
		// content
		$TemplateInfo = $this->getTemplateInfo($params['template']);
		$langPrefix = '';
		if(!empty($TemplateInfo['language'])){
			$langPrefix = '_'.\Drupal::languageManager()->getCurrentLanguage()->getId();
		}
		$settings = self::$Basket->getSettings('templates', $params['template'].$langPrefix);
		$html['#context']['content'] = [
			'#theme'		=> $params['template'],
			'#info'			=> [
				'body'			=> [
					'#type'			=> 'inline_template',
					'#template'		=> $this->getTemplate($settings),
					'#context'		=> $this->getContext($params['template'], [
						'order'			=> $getLastOrder
					]),
					'#params'		=> $params
				]
			]
		];
		$html['#context']['content'] = \Drupal::service('renderer')->render($html['#context']['content']);
		// ---
		$html = str_replace([
			'class="text-align-center"',
			'src="/'
		], [
			'style="text-align:center;"',
			'src="'.$GLOBALS['base_url'].'/'
		], \Drupal::service('renderer')->render($html));
		return \Drupal::token()->replace(
			$html, [
				'user'		=> isset($params['uid']) ? \Drupal\user\Entity\User::load($params['uid']) : \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()),
				'node'		=> !empty($params['nid']) ? \Drupal\node\Entity\Node::load($params['nid']) : NULL
			], [
				'clear' 	=> TRUE
			]
		);
	}
	public function getTemplate($settings){
		$template = '';
		if(!empty($settings['config']['template'])){
			$template = $settings['config']['template'];
			if(is_array($template)){
				$template = [
					'#type' 		=> 'processed_text',
				    '#text' 		=> $template['value'],
				    '#format' 		=> $template['format'],
				];
				$template = \Drupal::service('renderer')->render($template);
			}
		}
		return $template;
	}
	public function getTemplateInfo($templateName){
		if(empty(self::$TemplateInfo[$templateName])){
			self::$TemplateInfo[$templateName] = NULL;
			$ymldata = \Drupal\basket\Admin\Page\Templates::getTemplateYamls();
			if(!empty($ymldata)){
				foreach ($ymldata as $groupInfo){
					if(!empty($groupInfo['templates'])){
                    	foreach ($groupInfo['templates'] as $templateKey => $templateInfo){
                    		if($templateKey == $templateName){
                    			self::$TemplateInfo[$templateName] = $templateInfo;
                    		}
                    	}
                    }
				}
			}
		}
		return self::$TemplateInfo[$templateName];
	}
	public function getContext($templateName, $params){
		$TemplateInfo = $this->getTemplateInfo($templateName);
		$context = [];
		if(empty($TemplateInfo['token_twig'])){
			$TemplateInfo['token_twig'] = [];
		}
		// Alter
		\Drupal::moduleHandler()->alter('basketTemplateTokens', $TemplateInfo['token_twig'], $templateName);
		// ---
		if(!empty($TemplateInfo['token_twig'])){
			foreach ($TemplateInfo['token_twig'] as $keyTwig => $nameTwig){
				$context[$keyTwig] = self::$Basket->Token()->getToken($keyTwig, $params);
			}
		}
		return $context;
	}
	public function getLastOrder($params){
		if(!isset(self::$getLastOrder)){
			$query = \Drupal::database()->select('basket_orders', 'b');
			$query->fields('b');
			if(!empty($params['nid'])){
				$query->condition('b.nid', $params['nid']);
			}
			$query->orderBy('b.id', 'DESC');
			$query->range(0, 1);
			self::$getLastOrder = $query->execute()->fetchObject();
			if(!empty(self::$getLastOrder->currency)){
				self::$getLastOrder->currency = self::$Basket->Currency()->load(self::$getLastOrder->currency);
			}
		}
		return self::$getLastOrder;
	}
}