<?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 newslettersModeles
*/


class newslettersModeles
  implements ExtModPage, InterfacedTJsonS, InterfaceModule {

  const FILENAME ='newslettersModeles.php';
  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 $uhtml_received_count;
  public static $uhtml_want_count;

  /**
    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 'setflag':
	if ( ($_GET['flag'] == '0') || ($_GET['flag'] == '1') ) {
	  $newsletter_id = tep_db_prepare_input($_GET['nID']);

	  if (!empty($newsletter_id))
	    $DB->query("update " . TABLE_NEWSLETTERS_MODELES . " set status = '" .(int) $_GET['flag'] . "' where nmodele_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;

	if ($newsletter_error == false) {
	  $sql_data_array = array('languages_id' => 1,
				  'nmodele_content' => $content,
				  'title' => $title,
				  );

	  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_MODELES, $sql_data_array);
	    $newsletter_id = $res->__get('insertId');
	  }
	  elseif (self::$action == 'update') {
	    $sql_data_array['last_update'] = 'now()';
	    tep_db_perform(TABLE_NEWSLETTERS_MODELES, $sql_data_array, 'update', "nmodele_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_MODELES . " where nmodele_id = '" . (int)$newsletter_id . "'");

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


      case 'edit':
      case 'new':

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

	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;

    }

    return self::$action;
  }

  public function get_header(){
  }


  public static function load_db_values($ID){
    $DB=Database::getInstance();
    $query_raw ="select nmodele_id, languages_id,status, title, nmodele_content  from " . TABLE_NEWSLETTERS_MODELES . " where nmodele_id = '" . $ID . "'";
    $_query = $DB->query($query_raw);

    return new objectInfo($_query->fetchAssoc() );
  }


  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);
	}
	$action='edit';
      break;
      case 'preview':
	self::$nID=(int)$_GET['nID'];
	self::$nInfo=self::load_db_values(self::$nID);
      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($array){
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		 '',
		  sprintf(CsrtAction::getLink('row_action_right', ICON_PREVIEW, 'preview'), '',  tep_href_link(self::FILENAME,  'nID=' . $array['nmodele_id']. '&amp;action=preview') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME,  'nID=' . $array['nmodele_id']. '&amp;action=edit') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME,  'nID=' . $array['nmodele_id'] . '&amp;action=delete') ,'' )
	      );
  }


  private static function get_item_status($newslettersModeles){
    if ($newslettersModeles['status'] == '1')
      return  tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . '&nbsp;<a href="' . tep_href_link(self::FILENAME, 'action=setflag&amp;flag=0&amp;nID=' .$newslettersModeles['nmodele_id']) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT) . '</a>';
    else
      return '<a href="' . tep_href_link(self::FILENAME,  'action=setflag&amp;flag=1&amp;nID=' . $newslettersModeles['nmodele_id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT) . '</a>&nbsp;' . tep_image(DIR_WS_ICONS . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED);

  }



  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,
		  'nmodele_id' =>true,
                  'title'=>true,
                  'status'=>true,
                  'action'=>false,
                );
  }

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

    $DB=Database::getInstance();

    $query_raw ="select nmodele_id, languages_id,status,title,  nmodele_content from " . TABLE_NEWSLETTERS_MODELES . "  ".$sWhere." ORDER BY ".((!empty($sOrder)) ? $sOrder : " date_added DESC ");
    $split = new splitPageResults($page, $rowbyp, $query_raw, $query_numrows);

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

    while ($item = $query->fetchAssoc() ) {
      $item[0]=$item['nmodele_id'];
      $item['action']=self::get_item_action($item);
      $item['status']=self::get_item_status($item);
//       $item['locked']=self::get_item_locked($item);
      $item['nmodele_content']=$item['nmodele_content'];
      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);
    self::load_module();
    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_newslettersModeles(){
    $file_extension = '.php';
    $directory_array = array();
    if ($dir = dir(DIR_WS_MODULES . 'newslettersModeles/')) {
      while ($file = $dir->read()) {
        if (!is_dir(DIR_WS_MODULES . 'newslettersModeles/' . $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;
  }

  /**
    Chargeur de module
  */
  private static function load_module(){
    global $language;
    include(DIR_WS_LANGUAGES . $language . '/modules/newslettersModeles/' . self::$nInfo->module . '.txt');
    if(!class_exists(self::$nInfo->module))include(DIR_WS_MODULES . 'newslettersModeles/' . self::$nInfo->module . '.php');
    $module_name = self::$nInfo->module;
    self::$module = new $module_name(self::$nID,self::$nInfo->title, self::$nInfo->content);

    self::$uhtml_received_count = self::$module->count_sended;
    self::$uhtml_want_count = self::$module->count;
  }


  /**
    @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
  }

  /**
    Nombre d'envoi a effectué
  */
  public function count_send(){
    $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'];
  }

  /**
    Nombre d'envoi deja effetué
    @a int nmodele_id
  */
  public static function count_sended_ok($nmodele_id, $code){
    $DB=Database::getInstance();
    $mail_query = $DB->query($sql="SELECT COUNT(*) AS count FROM ".TABLE_NEWSLETTERS_MODELES_SENT." WHERE nmodele_id = '" . $nmodele_id. "' AND module_type='".$code."' ");
    $mail = $mail_query->fetchAssoc();
    return $mail['count'];
  }
}

?>