<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2011  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  20/03/11, 20:48
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class newsletters
*/

class newsletters
  implements ExtModPage, InterfacedTJsonS, InterfaceModule {

  const FILENAME =FILENAME_NEWSLETTERS;
  public static $code;

  public static $action;

  public static $list=array();

  /**
    @p int ID newsletter
  */
  public static $nID;
  /**
    @p obj
  */
  public static $nInfo;
  /**
    @p obj module newsletter
  */
  public static $module;

  public static $preview;

  /**
    @var array Tag for replace in email content
  */
  public static $TagReplace=array('user'=>array('[GENDER]','[LASTNAME]','[POSTNAME]','[DATE_CREATED]','[LAST_LOGON]','[FIDELITY_POINTS]'));



  /**
    class constructor
  */
  public function __construct() {
    self::GetConf();
  }

  /**
    @brief Load , adjust and define var environement exe for module
	Is use in module and class abstract for init value config this module
  */
  public static function GetConf(){
    global $languages_id;

    self::$code=__CLASS__;

    self::$action=(isset($_REQUEST['action'])? $_REQUEST['action'] : 'listing' );


    /**
      @remarks not load if not first init
    */
    if(defined('JSONSTATMENT')) return;

    //! active datatable in ajax, precise les GET necessaire
    define('JSONSTATMENT', 'mod=page&type='.self::$code);
    //! detail item in ajax
    define('AJAXSTATMENTDETAIL', 'mod=page&type='.self::$code);
  }


  public function check_action($actions){
    global $messageStack,$oscss;


    self::$action=$actions;
    $DB=Database::getInstance();

    switch (self::$action) {
      case 'lock':
      case 'unlock':
        $newsletter_id = tep_db_prepare_input($_GET['nID']);
        $status = ((self::$action == 'lock') ? '1' : '0');

        $DB->query("update " . TABLE_NEWSLETTERS . " set locked = '" . $status . "' where newsletters_id = '" . (int)$newsletter_id . "'");

        tep_redirect(tep_href_link(self::FILENAME, 'nID=' . $_GET['nID']));
      break;

      case 'insert':
      case 'update':
        if (isset($_POST['newsletter_id'])) $newsletter_id = tep_db_prepare_input($_POST['newsletter_id']);

        $newsletter_module = tep_db_prepare_input($_POST['module']);
        $title = tep_db_prepare_input($_POST['title']);
        $content = tep_db_prepare_input($_POST['content']);

        $newsletter_error = false;
	try {
	  if (empty($title)) throw new Exception (__('error newsletter title'));
	  if (empty($newsletter_module))throw new Exception (__('error newsletter module'));
	} catch (Exception $e) {
	    $messageStack->add($e->getMessage(), 'error');
	    $newsletter_error=true;
	}


	if ($newsletter_error == false) {
	  $sql_data_array = array('title' => $title,
				  'content' => $content,
				  'module' => $newsletter_module,
				  'modele_id' => tep_db_prepare_input($_POST['modele_id'])
				  );

	  if (self::$action == 'insert') {
	    $sql_data_array['date_added'] = 'now()';
	    $sql_data_array['status'] = '0';
	    $sql_data_array['locked'] = '0';

	    $res=tep_db_perform(TABLE_NEWSLETTERS, $sql_data_array);
	    $newsletter_id = $res->__get('insertId');
	  }
	  elseif (self::$action == 'update') {
	    tep_db_perform(TABLE_NEWSLETTERS, $sql_data_array, 'update', "newsletters_id = '" . (int)$newsletter_id . "'");
	  }

          tep_redirect(tep_href_link(self::FILENAME,  'nID=' . $newsletter_id));
	} else {
	  //! init wisywyg
	  $oscss->_add_ext(BO_WISIWYG_SELECTED,'editeur/');
	  echo $oscss->_call(BO_WISIWYG_SELECTED,'_top','content','600','400');
	}
      break;

      case 'deleteconfirm':
        $newsletter_id = tep_db_prepare_input($_GET['nID']);

         $DB->query("delete from " . TABLE_NEWSLETTERS . " where newsletters_id = '" . (int)$newsletter_id . "'");

        tep_redirect(tep_href_link(self::FILENAME));
      break;


      case 'edit':
      case 'new':

	$parameters = array('title' => '',
			    'content' => '',
			    'module' => '',
			    'modele_id' => '');

	self::$nInfo = new objectInfo($parameters);


    //     $nInfo->objectInfo($_POST);

	//! init wisywyg
	$oscss->_add_ext(BO_WISIWYG_SELECTED,'editeur/');
	echo $oscss->_call(BO_WISIWYG_SELECTED,'_top','content','600','400');

    break;
      case 'sendtest':
      break;
      case 'send':
      case 'confirm_send':
        $newsletter_id = tep_db_prepare_input($_GET['nID']);


        $check_query =  $DB->query("select locked from " . TABLE_NEWSLETTERS . " where newsletters_id = '" . (int)$newsletter_id . "'");
        $check = $check_query->fetchAssoc();

        if (!isset($_SESSION['sendtest']) &&  $check['locked'] < 1) {
	switch (self::$action) {
	  case 'send': $error = ERROR_SEND_UNLOCKED_NEWSLETTER;
	  case 'confirm_send': $error = ERROR_SEND_UNLOCKED_NEWSLETTER;
	  default:
	$messageStack->add_session($error, 'error');

	tep_redirect(tep_href_link(self::FILENAME, 'nID=' . $_GET['nID']));
	}

        }

        break;

    }

    //! alert
    if (!_cst_bool('SEND_EMAILS')) $messageStack->add(ERR_TXT_EMAIL_OFF, 'warning');
    if (!_cst_bool('EMAIL_USE_HTML'))  $messageStack->add(ERR_TXT_EMAIL_TXT_STRICT, 'warning');

    return self::$action;
  }

  public function get_header(){
  }


  public static function load_db_values($ID){
    NewslettersChargeur::getInstance($ID);
    return NewslettersChargeur::$CurrentMod;
  }


  public function display_view(){
    global $language;

    $action=self::$action;

    switch (self::$action) {
      case 'delete':
	self::$nID=(int)$_GET['nID'];
      break;
      case 'insert':
      case 'update':
	self::$nID=(int)$_GET['nID'];
	self::$nInfo=new objectInfo($_POST);
	$action='edit';
      break;
      case 'new':
      case 'edit':
	if(isset($_GET['nID'])){
	  self::$nID=(int)$_GET['nID'];
	  self::$nInfo=self::load_db_values(self::$nID);
	  NewslettersChargeur::load_module(self::$nID);
	}
	$action='edit';
      break;
      case 'preview':
	self::$nID=(int)$_GET['nID'];
	self::$nInfo=self::load_db_values(self::$nID);
	NewslettersChargeur::load_module(self::$nID);
	self::$preview=NewslettersChargeur::$module->get_content(NewslettersChargeur::$module->content);
      break;

      case 'confirm_sendtest':
	self::$nID=(int)$_GET['nID'];
	self::$nInfo=self::load_db_values(self::$nID);
	NewslettersChargeur::load_module(self::$nID);

	$action='confirm_send';
      break;

      case 'send':
      case 'confirm':
      case 'sendtest':
      case 'confirm_send':
	self::$nID=(int)$_GET['nID'];
	self::$nInfo=self::load_db_values(self::$nID);
	NewslettersChargeur::load_module(self::$nID);

      break;
//       case 'send':
//       case 'confirm':
//       break;
      default:
	self::tep_get_list();
	$action='listing';
    }


    /// use master gabarit
    return MGabCont::CallGab($action,__FUNCTION__,__CLASS__);
  }


  /** public static InterfacedTJsonS */

  private static function get_item_action($newsletters){
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  ''/*self::$modules->display_ColumnRowAction($products['products_id']) */,
		  sprintf(CsrtAction::getLink('row_action_right', ICON_PREVIEW, 'preview'), 'fancy',  tep_href_link(self::FILENAME, 'nID=' . $newsletters['newsletters_id'] . '&amp;action=preview') ,'' ).
		  (($newsletters['locked'] == 1 && $newsletters['status']!=1)
		    ? sprintf(CsrtAction::getLink('row_action_right', IMAGE_SEND, 'send'), '',  tep_href_link(self::FILENAME, 'nID=' . $newsletters['newsletters_id'] . '&amp;action=send') ,'' )
		    : sprintf(CsrtAction::getLink('row_action_right', __('image send test'), 'sendtest'), '',  tep_href_link(self::FILENAME, 'nID=' . $newsletters['newsletters_id'] . '&amp;action=sendtest') ,'' )
		  ).
		  (($newsletters['locked'] == 0 )
		    ? sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME,  'nID=' . $newsletters['newsletters_id'] . '&amp;action=edit') ,'' )
		    : ''
		  ).
		  (($newsletters['status'] != 2 )
		    ? sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME,  'nID=' . $newsletters['newsletters_id'] . '&amp;action=delete') ,'' )
		    : ''
		  )
	      );

  }

  private static function get_item_locked($newsletters){
    if ($newsletters['locked'] > 0){
      if ($newsletters['status'] ==2 )
	return '<a  class="buttonimg" href="' . tep_href_link(self::FILENAME, 'nID=' . $newsletters['newsletters_id'] . '&amp;action=archive') . '">' . tep_image(DIR_WS_ICONS .'locked.gif', __('txt exec archive')) . '</a>';
      else
	return '<a  class="buttonimg" href="' . tep_href_link(self::FILENAME, 'nID=' . $newsletters['newsletters_id'] . '&amp;action=unlock') . '">' . tep_image(DIR_WS_ICONS .'locked.gif', ICON_LOCKED) . '</a>';
    }
    else
      return '<a  class="buttonimg" href="' . tep_href_link(self::FILENAME, 'nID=' . $newsletters['newsletters_id'] . '&amp;action=lock') . '">' . tep_image(DIR_WS_ICONS .'unlocked.gif', ICON_UNLOCKED) . '</a>';
  }

  private static function get_item_status($newsletters){

    $var=(int)$newsletters['status'] ;
    if ($var == 2)
      return tep_image(DIR_WS_ICONS . 'tick.gif', ICON_TICK);
    elseif ($var == 1)
      return __('reload');
    else
      return tep_image(DIR_WS_ICONS . 'cross.gif', ICON_CROSS);

  }

  private static function emptyResult(){
    $li=array();
    foreach(self::tep_get_modele() as $k=>$v) $li[$k]='&nbsp;';
    return $li;
  }

  public static function tep_get_modele(){
    return array( 0 =>false,
		  'title' =>true,
                  'content'=>true,
                  'module'=>true,
		  'status'=>true,
                  'locked'=>true,
                  'nbr_send'=>true,
                  'action'=>false,
                );
  }

  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){
    global $query_numrows;

    $DB=Database::getInstance();

    $query_raw ="select newsletters_id, title, length(content) as content_length, module, date_added, date_sent, status, locked,nbr_send from " . TABLE_NEWSLETTERS . " ".$sWhere." ORDER BY ".((!empty($sOrder)) ? $sOrder : " date_added DESC ");
    $split = new splitPageResults($page, $rowbyp, $query_raw, $query_numrows);

    $query = $DB->query($query_raw);

    while ($ite = $query->fetchAssoc() ) {
      $item=$ite;
      $item[0]=$ite['newsletters_id'];
      $item['action']=self::get_item_action($ite);
      $item['locked']=self::get_item_locked($ite);
      $item['status']=self::get_item_status($ite);
      $item['content']=$ite['content_length'];
      self::$list[]=$item;
    }

    $li=$res=array();
    foreach(self::$list as $item){
      foreach(self::tep_get_modele() as $k=>$v) $li[$k]=(tep_not_null($item[$k]))?$item[$k]:'&nbsp;';
      $res[]=$li;
    }
    if(count($res)==0) $res[]=self::emptyResult();
    return $res;
  }


 /** static InterfacedInnerHtml */

  public static function detail_row_page($id){
    global $language;
//     self::init();
    self::$nID=(int)$id;
    self::$nInfo=self::load_db_values((int)$id);
    NewslettersChargeur::load_module($nID);

    self::$nInfo->open = 0;
    self::$nInfo->click = 0;
    self::$nInfo->view_online = 0;

    $DB=Database::getInstance();
    $query_raw ="SELECT date_sent, date_opened as open,date_click as click , view_online  FROM  " . TABLE_NEWSLETTERS_SENT . " where newsletters_id = '" . $id . "'";
    $_query = $DB->query($query_raw);
    $res=$_query->fetchAllAssoc();

    foreach($res as $pil){
      self::$nInfo->open += ( ($pil['open']!='0000-00-00 00:00:00') ? 1 : 0);
      self::$nInfo->click += ( ($pil['click']!='0000-00-00 00:00:00') ? 1 : 0);
      self::$nInfo->view_online += ( ((int)$pil['view_online']==1) ? 1 : 0);
    }


    return tep_get_include_contents(__CLASS__.'.inline');
  }


/** Interface module */

  public function check() { return false; }
  public function install() { return false; }
  public function remove() { return false;  }
  public function keys() { return false; }


/** specific modules */

  /**
    List les modules present dans /modules/neswletters/
    @return array
  */
  public static function list_module_newsletters(){
    $file_extension = '.php';
    $directory_array = array();
    if ($dir = dir(DIR_WS_MODULES . 'newsletters/')) {
      while ($file = $dir->read()) {
        if (!is_dir(DIR_WS_MODULES . 'newsletters/' . $file)) {
          if (substr($file, strrpos($file, '.')) == $file_extension) {
            $directory_array[] = $file;
          }
        }
      }
      sort($directory_array);
      $dir->close();
    }

    for ($i=0, $n=sizeof($directory_array); $i<$n; $i++) {
      $modules_array[] = array('id' => substr($directory_array[$i], 0, strrpos($directory_array[$i], '.')), 'text' => substr($directory_array[$i], 0, strrpos($directory_array[$i], '.')));
    }
    return $modules_array;
  }

  /**
    @brief call modele dispo for newsletter
  */
  public static function list_modele_newsletters(){
    $DB=Database::getInstance();
    $array=array(array('id'=>'0', 'text'=>__('not use modele') ) );
    $query_raw ="select nmodele_id, status,title,  nmodele_content from " . TABLE_NEWSLETTERS_MODELES . " WHERE status='1'  ORDER BY  last_update, date_added DESC ";
    $query = $DB->query($query_raw);
    while ($item = $query->fetchAssoc() ) {
      $array[]=array('id'=>$item['nmodele_id'], 'text'=>$item['title'] );
    }

    return $array;
  }






  /**
    @packageoriginal Ultimate Html Email
    @author oscim <mail a@oscim.fr /><web http://www.oscim.fr />
    barre progression d'envoi des email
  */
  public static function draw_progress_bar($percent, $width, $height){
    global $uhtml_received_count, $uhtml_want_count;
    ?>
    <p><span style="font-size:15pt;">Progress - <?php echo $percent; ?>%</span><br />
    <span style="font-size:12pt;"><?php echo $uhtml_received_count; ?> of <?php echo $uhtml_want_count ?> emails are sent.</span></p>
    <div align="left" style="width:<?php echo $width; ?>px; height:<?php echo $height; ?>px; border:2px solid #000000; padding:0px;">
	    <div style="width:<?php echo (int)$percent/100*$width; ?>px; height:<?php echo $height; ?>px; background-color:#79973F;"></div>
    </div>
    <?php
  }



}


/**
  @brief chargeur de module de newlsetters
  @class NewslettersChargeur

*/
class NewslettersChargeur
  {


  /**
    @var int num lot for send email
  */
  public static $nbr_envoi=20;
  /**
    @var array method in module newsletter for call , in sort order
      For add display function in process, add this array
  */
  private static $methodDisplay = array('choose_content','choose_audience','choose_trackeur','confirm');



  /**
    @var current object module
  */
  public static $CurrentMod;
  /**
    @var current object module
  */
  public static $module;
  /**
    @var current instance class
  */
  protected static $_instance;
  /**
    @var
  */
  public static $count_sended;
  /**
    @var
  */
  public static $count;
  /**
    @var array Pile des mail envoyes
  */
  public static $PileSent;
  /**
    @var boolean For test sent email
  */
  public static $modeTest=false;


  protected function __construct($ID) {
    return self::$CurrentMod= new objectInfo(NewslettersUtility::CheckNewsId($ID));
  }

  public static function getInstance($ID) {
    if(self::$_instance == null)  self::$_instance = new self($ID);
    return self::$_instance;
  }


  /**
    @brief db insert user sended
    @param $userid int user id
    @param $newsid int newsletter id
    @param $module string module name
  */
  public static function PushUserSent($userid, $newsid, $module){
    self::$PileSent[]=array('userid'=>$userid,'newsid'=>$newsid,'module'=>$module);
  }

  /**
    @brief db insert user sended
    @param $userid int user id
    @param $newsid int newsletter id
    @param $module string module name
  */
  public static function UpSent(){

    if(self::$modeTest)return true;

    $query="INSERT INTO ".TABLE_NEWSLETTERS_SENT." (customers_id,newsletters_id,module_type, date_sent)  VALUES ";

    foreach(self::$PileSent as $array)
      $query .=" ( ".$array['userid'].",".$array['newsid'].",'".$array['module']."', NOW() ) ,";

    $query =substr($query,0,-1).';';

    $DB=Database::getInstance();
    $DB->query($query);


    $DB->query("update " . TABLE_NEWSLETTERS . " set date_sent = now(), status = '".(( self::$count >= self::$count_sended)? 1 : 2)."', nbr_send = '".(int)(self::$count_sended + count(self::$PileSent) ) ."' where newsletters_id = '" . self::$CurrentMod->newsletters_id . "'");
  }


  /**
    Chargeur de module
  */
  public static function load_module($nID){
    global $language, $lang;

    $file_lg=DIR_WS_LANGUAGES . $language . '/modules/newsletters/' . self::$CurrentMod->module . '.txt';
    if(file_exists($file_lg)) include($file_lg);

    if(!class_exists(self::$CurrentMod->module))include(DIR_WS_MODULES . 'newsletters/' . self::$CurrentMod->module . '.php');

    $module_name = (string)self::$CurrentMod->module;

    self::$module = new $module_name($nID,self::$CurrentMod->title, self::$CurrentMod->content);

    self::$count_sended = self::$module->count_sended_ok();
    self::$count = self::$module->count_send();


    // affichage des replace posisble
    if(isset(self::$module->TagReplace))
	newsletters::$TagReplace= array_merge( newsletters::$TagReplace, self::$module->TagReplace);
  }


  /**
    @brief call method module , while by $methodDisplay
  */
  public static function DisplaySent(){

    foreach(self::$methodDisplay as $method)
      if(method_exists(self::$CurrentMod->module, $method )){

	$name='show_'.$method;
	self::$module->$name=true;
	$result=self::$module->$method();
	if($result !=false) return $result;
      }

//       return __('error no class newsletters found!');
  }

  /**
    @brief call method module or method generic
  */
  public function count_send(){
    $name='CountSend';
    if(method_exists(self::$CurrentMod->module, $name )){
      return self::$module->$name();
    }
    else
      return self::Genericsend();
  }

  /**
    @brief call method module or method generic
  */
  public function count_sended_ok(){

    $name='CountSendOk';
    if(method_exists(self::$CurrentMod->module, $name )){
      return self::$module->$name();
    }
    else
      return self::GenericsendOk();
  }

  /**
    @brief call send method. Mode Test
  */
  public static function ExecSent($emailTest=false){

    if($emailTest!=false && is_string($emailTest)) self::$modeTest=true;

    return self::$module->send(self::$nbr_envoi,$emailTest);
  }



  /**
    @brief Generic Fonction  Nombre d'envoi a effectué
  */
  private static function Genericsend(){
    $DB=Database::getInstance();
    $mail_query = $DB->query("SELECT COUNT(*) as count FROM " . TABLE_CUSTOMERS . " WHERE customers_newsletter = '1'  ");
    $mail = $mail_query->fetchAssoc();
    return $mail['count'];
  }

  /**
    @brief Generic Fonction Nombre d'envoi deja effetué
    @a int newsletters_id
  */
  public static function GenericsendOk(){
    $DB=Database::getInstance();
    $mail_query = $DB->query($sql="SELECT COUNT(*) AS count FROM ".TABLE_NEWSLETTERS_SENT." WHERE newsletters_id = '" . self::$CurrentMod->newsletters_id. "' AND module_type='".self::$CurrentMod->module."' ");
    $mail = $mail_query->fetchAssoc();
    return $mail['count'];
  }
}
?>