<?php
/**
 * Newsletter module - send newsletter using ajax
 * 
 * Send newsletter to the connected user email using ajax. Called from back-office only
 *  
 * @package linea21\modules\newsletter
 * @author $Author$ - Simon Georget <simon@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */


include_once('../config/define.php');

if (!$l21auth->isSuperAdmin()) ReloadIndex('admin');
////////////

include_once(override('../newsletter/'.SQL.'.inc.php'));
include_once('../class/class.newsletter.php');
include_once('../languages/' . U_L . '/lang_newsletter.' . CHARSET . '.php');


if(isset($_REQUEST['id']) && is_numeric($_REQUEST['id']) && isset($_GET['token']) && $_GET['token'] == SECRET_KEY) {

  // this is a test only on one mail 
    if(isset($_REQUEST['user_email']) && is_string($_REQUEST['user_email'])) {
      $emails_batch = array(0 => array('emailcol_id' => $l21auth->GetSessionElement('id'), 'emailcol_email' => $_REQUEST['user_email']));
      $doNotPublish = true; // needed to keep the newsletter with open status
      $newsletters = $sql_object->DBSelect(SQL_getoneCompleteNewsLetter($_REQUEST['id']));
      $newsletters[0]['newsletter_title'] .= ' (' .  _t('newsletter', 'test_add') . ')';
      
      // else this is a real mailing, we send it to everyone ! 
    } else {
        // we get all emails recipients
        $emails_batch = $GLOBALS['sql_object']->DBSelect(SQL_GetEmails4Sending());
        $newsletters = $sql_object->DBSelect(SQL_getoneCompleteNewsLetter($_REQUEST['id']));
    }
  
    // if there is no selected newsletter or no recipients
    if (!is_array($newsletters) || !is_array($emails_batch)) {
        $status = 0;
        $o = _t('newsletter', 'sent_failed');
    
    } else {
	
	  $newsletter_object = new newsletter;
	  $path = $newsletter_object->URI_TEMPLATE;
	
	  // html
	  $template_html = file_get_contents(override($path . '.html'));
	  // text
	  $template_txt = file_get_contents(override($path . '.txt'));
	
	  if(isset($doNotPublish)) logfile(LOG_MAILING, array('[newsletter-start]', '[test]', 'calling ' . __FILE__ ));
	  else logfile(LOG_MAILING, array('[newsletter-start]', 'calling ' . __FILE__ ));
	  require(override("../mail/send_newsletter.php"));
	  logfile(LOG_MAILING, array('[newsletter-stop]'));
	  
	  $status = 1;
	  $o = _t('newsletter', 'sent_successfully');
  }
  
  /* Return json values */
  echo json_encode(array('status'=> $status,'msg'=> $o));
  
} else {
	
	/* Inputs are incorrects */
	echo json_encode(array('status'=> 0,'msg'=> _t('newsletter', 'sent_failed')));
	
}
?>