﻿<?php

require_once (sPrintF ('%s/components/com_mailjet/lib/lib/mailjet-api-strategy.php', JPATH_ADMINISTRATOR));

/**
 * @author Mailjet SAS
 *
 * @copyright  Copyright (C) 2014 Mailjet SAS.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */
// No direct access to this file

// Check to ensure this file is within the rest of the framework
defined('JPATH_BASE') or die();
jimport('joomla.form.formfield');
JFormHelper::loadFieldClass('list');
jimport('joomla.html.html');

$lang = JFactory::getLanguage();
$extension = 'mod_mailjet';
$base_dir = JPATH_SITE;
$language_tag =  $lang->getTag();
$reload = true;
$lang->load($extension, $base_dir, $language_tag, $reload);

class JFormFieldMailjetcombo extends JFormFieldList
{

    protected $type = 'mailjetcombo';

    protected function getOptions()
    {
    	// Get the parameters
        $params = $this->getParams();
		
		// Get the list of contact lists
		$mj = new Mailjet_Api($params['username'], $params['password']);
		$response = $mj->getContactLists(array());
		
		// Set the array for the view
		$ret = array(JText::_("COM_MAILJET_NO_LISTS"));
		if(!isset($response->Status) || (isset($response->Status) && $response->Status != 'ERROR')) 
		{
			if(is_array($response) && count($response) > 0) 
			{
				$ret = array();
				foreach($response as $list) {
	                $ret[$list['value']] = sprintf('%s (%s subscribers)', $list['label'], $list['subscribers']);
	            }
			}
		}
        return $ret;
    }

    private function getParams ()
    {
        //Below are some comments containing error messages to improve usability
        $this->_dbData = sPrintF ('%s/components/%s/lib/db/data', JPATH_ADMINISTRATOR, 'com_mailjet');

        if(file_exists($this->_dbData)){
            $pre_data = null;
            $content = trim(file_get_contents($this->_dbData));
            
            if ($content)
                $pre_data = json_decode($content);

            /*if(!$pre_data->apiKey || !$pre_data->apiSecret){
                JError::raiseWarning( 100, JText::_("COM_MAILJET_INCOMPLETE_INFO") );
            }*/

            $data ['username'] = $pre_data->apiKey;
            $data ['password'] = $pre_data->apiSecret;

            return $data;
        }
        /*else{
            JError::raiseWarning( 100, JText::_("COM_MAILJET_NO_DATAFILE") );
        }*/
    