<?php

/**
 * @package         MailChimp Auto-Subscribe
 * @version         5.0.3 Pro
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2021 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

// No direct access
defined('_JEXEC') or die;

require_once __DIR__ . '/helpers/autosubscribe.php';

/**
 *  MailChimp Auto-Subscribe Class
 */
class plgUserTM_MailChimpUserAutoAdd extends AutoSubscribe
{
	/**
	 *  Service Name
	 *
	 *  @var  string
	 */
	protected $service = 'mailchimp';

	/**
	 *  Subscribe user to MailChimp
	 *
	 *  @return  mixed
	 */
	public function subscribeMailChimp()
	{
		JLoader::register('NR_MailChimp', JPATH_PLUGINS . '/system/nrframework/helpers/wrappers/mailchimp.php');

		// Add to MailChimp
		$api = new NR_MailChimp(['api' => $this->key]);
		$api->subscribe(
			$this->user['email'],
			$this->list, 
			$this->fields,
			true, 
			$this->params->get('doubleoptin', true)
		);
		
		if (!$api->success())
		{
			throw new \Exception($api->getLastError());
		}
		
		return true;
	}

	/**
	 * AJAX Listener
	 *
	 * @return void
	 */
	public function onAjaxTM_MailChimpUserAutoAdd()
	{
		JSession::checkToken('request') or jexit(JText::_('JINVALID_TOKEN'));

		// Only on the back-end
		if ($this->app->isClient('site'))
		{
			return;
		}

		error_reporting(E_ALL & ~E_NOTICE);

		$task = $this->app->input->get('task');
		$task = empty($task) ? 'testConnection' : $task;
		$taskMethod = 'task' . $task;

		if (!method_exists($this, $taskMethod))
		{
			die();
		}

		$this->$taskMethod();
	}

	/**
	 * Execute the Test Connection task
	 *
	 * @return void
	 */
	private function taskTestConnection()
	{
		$data = $this->app->input->get('jform', array(), 'ARRAY');

		if (!is_array($data))
		{
			die('Invalid Data');
		}
		
		// Override plugin saved parameters with the parameters passed via the AJAX request
		$this->params = new Joomla\Registry\Registry($data['params']);
		$this->params->set('doubleoptin', false);
		$this->params->set('forceadd', true);

		// Set a temporary user to be used for the call
		$this->user = [
			'id'     => JFactory::getUser()->id,
			'email'  => 'mas-plugin-test-' . rand(1, 1000) . '@gmail.com',
			'groups' => [2]
		];

		// Cool. Let's try to subscibe the user.
		try
		{
			$this->init();
			$this->fields = $this->getFields();
			$this->subscribeMailChimp();
		} catch (Exception $e)
		{
			die($e->getMessage());
		}

		die(JText::sprintf('MAS_TEST_CONNECTION_SUCCESS', $this->user['email'], $this->list));
	}

	/**
	 * Execute the View Log task file triggered by the View Log File button found on the Advanced tab.
	 */
	private function taskViewLog()
	{
		$logfile = JPath::clean(JFactory::getConfig()->get('log_path') . '/mailchimpAutoSubscribe.php');
		
		header('Content-Type: text/plain');
		
		$content = JFile::exists($logfile) ? JFile::read($logfile) : 'File not found';

		echo $content;

		jexit();
	}
}
