<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Renderers;
/**
 *
 * @package JREALTIMEANALYTICS::FRAMEWORK::administrator::components::com_jrealtimeanalytics
 * @subpackage framework
 * @subpackage renderers
 * @author Joomla! Extensions Store
 * @copyright (C) 2013 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 */
defined ( '_JEXEC' ) or die ();
use Joomla\CMS\Language\Text;
use Joomla\CMS\Factory;
use Joomla\CMS\Component\ComponentHelper;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Model\ServerstatsModel;

/**
 *
 * @package JREALTIMEANALYTICS::FRAMEWORK::administrator::components::com_jrealtimeanalytics
 * @subpackage framework
 * @subpackage renderers
 * @since 2.3
 */
class Baseadapter {
	/**
	 * Mailer helper instance
	 *
	 * @access protected
	 * @var Object
	 */
	protected $mailer;
	
	/**
	 * Extension params
	 *
	 * @access protected
	 * @var Object
	 */
	protected $cParams;
	
	/**
	 * Joomla params
	 *
	 * @access protected
	 * @var Object
	 */
	protected $jConfig;
	
	/**
	 * Effettua l'invio della mail di risposta al customer
	 *
	 * @param string $body
	 * @param string $data
	 * @params string $fileName
	 * @params string $mimeType
	 * @access protected
	 * @return boolean
	 */
	protected function sendEmail($data, $fileName, $mimeType, $model = null) {
		// Check for notify email addresses
		$validEmailAddresses = array();
		$emailAddresses = $this->cParams->get('report_addresses', '');
		$emailAddresses = explode(',', $emailAddresses);
		if(!empty($emailAddresses)) {
			foreach ($emailAddresses as $validEmail) {
				if(filter_var(trim($validEmail), FILTER_VALIDATE_EMAIL)) {
					$validEmailAddresses[] = trim($validEmail);
				}
			}
		}
	
		// If valid email addresses detected send the notification
		if(!empty($validEmailAddresses)) {
			// Build e-mail message format
			$this->mailer->setSender(array($this->cParams->get('report_mailfrom', $this->jConfig->get('mailfrom')), 
									 	   $this->cParams->get('report_fromname', $this->jConfig->get('fromname'))));
			$this->mailer->setSubject(Text::_('COM_JREALTIME_REPORT_SUBJECT'));
			$encoding = 'base' . 64;
			$this->mailer->addStringAttachment($data, $fileName, $encoding, $mimeType);
			
			/**
			 * Format a full body for the notification email
			 */
			$bodyText = Text::sprintf('COM_JREALTIME_REPORT_BODY', date('Y-m-d'));
			$aiSummary = $this->generateAIEmailSummary($model);
			if($aiSummary) {
				$bodyText .= '<hr/><h3>' . Text::_('COM_JREALTIME_AI_EMAIL_SECTION_TITLE') . '</h3><div>' . $this->formatAIEmailSummary($aiSummary) . '</div>';
			}
			
			$this->mailer->setBody($bodyText);
			$this->mailer->IsHTML(true);
		
			// Add recipient
			$this->mailer->addRecipient($validEmailAddresses);
		
			// Send the Mail
			$rs	= $this->mailer->sendUsingExceptions();
		
			// Check for an error
			return $rs;
		}
		
		return false;
	}
	
	/**
	 * Generate optional AI analysis to append in scheduled email reports.
	 *
	 * @access protected
	 * @param ServerstatsModel|null $model
	 * @return string
	 */
	protected function generateAIEmailSummary($model = null) {
		if(!(int)$this->cParams->get('ai_analysis_enabled', 0) || !(int)$this->cParams->get('ai_email_report_enabled', 0)) {
			return '';
		}
		
		if($model instanceof ServerstatsModel) {
			$statsData = $model->fetchData();
			if(!is_array($statsData) || empty($statsData)) {
				return '';
			}
			
			$nativeReportContent = $model->buildAINativeReportContent($statsData);
			if(!$nativeReportContent) {
				return '';
			}
			
			$periodLabel = trim((string)$model->getState('fromPeriodOriginal') . ' - ' . (string)$model->getState('toPeriodOriginal'));
			if(!$periodLabel) {
				$periodLabel = 'scheduled-period';
			}
			
			$analysis = $model->generateAIAnalysis($nativeReportContent, $periodLabel, 'email');
			if($analysis && stripos($analysis, $periodLabel) === false) {
				$analysis = 'Analysis period: ' . $periodLabel . "\n\n" . $analysis;
			}
			return $analysis;
		}

		return '';
	}
	
	/**
	 * Format AI summary for HTML emails, converting markdown bold to HTML bold.
	 *
	 * @access protected
	 * @param string $aiSummary
	 * @return string
	 */
	protected function formatAIEmailSummary($aiSummary) {
		$safeText = htmlspecialchars((string)$aiSummary, ENT_QUOTES, 'UTF-8');
		$safeText = preg_replace('/\\*\\*(.+?)\\*\\*/s', '<strong>$1</strong>', $safeText);
		return nl2br($safeText);
	}
	
	/**
	 * Class constructor
	 *
	 * @access public
	 * @param Object $cParams
	 * @param Object $mailer
	 * @return Object&
	 */
	public function __construct($cParams = null, $mailer = null) {
		// Store extension config
		$this->cParams = $cParams;
		if(is_null($cParams)) {
			$this->cParams = ComponentHelper::getParams('com_jrealtimeanalytics');
		}
		
		// Joomla config
		$this->jConfig = Factory::getApplication()->getConfig();
		
		// Mailer object if any
		$this->mailer = $mailer;
	}
}