<?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
  @Portioncode  products class for ACA v2 (Advanced Categories Admin) by Rigadin2, www.osc-help.net
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  07/02/11, 08:55
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class customers

*/

class customers
    implements ExtModPage, InterfaceModule, InterfacedTJsonS,InterfacedInnerHtml{

  const FILENAME = FILENAME_CUSTOMERS;
  /**
    @p string $code
  */
  public static $code;
  /**
    @p string $action
  */
  public static $action;
  /**
    @p array $actions
  */
  public static $actions;
  /**
    @p array $modules
  */
  public static $list=array();
  /**
    @p array $modules
  */
  public static $modules;
  /**
    @p array $languages
  */
  public static $languages;
  /**
    @p objet $cInfo
  */
  public static $cInfo;
  /**
    @p array $newsletter_array
  */
  public static $newsletter_array;
  /**
    @p bool $processed
  */
  public static $processed;
 /**
    @p array $DiversInfo transport var
  */
  public static $DiversInfo;

  /**
    @p obj $box
  */
  public static $box;
  /**
    @p bool $error
  */
  public static $error=false;
  /**
    @p int Id customers
  */
  public static $cID;

  public function  __construct(){
    self::init();
  }

  private static function init(){
    self::$code=__CLASS__;

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

    self::$modules=new accountACA;
    self::$modules->set_image_handler();

    self::$languages = tep_get_languages();

    self::$newsletter_array=array(array('id' => '1', 'text' => __('entry newsletter yes')),
				  array('id' => '0', 'text' => __('entry newsletter no'))
				  );

  }

/** public  ExtModPage */





  /**
   * \fn check_action($actionss)
   * \brief execut action
   * @param $actionss string
   */
  public function check_action($actionss){
    global $languages_id, $messageStack, $language;

    self::$action=$actionss;
    $DB=Database::getInstance();
    $_return=array();

    if(isset($_GET['cID'])) self::$cID= (int)$_GET['cID'];
    elseif(isset($_POST['customers_id'])) self::$cID= (int)$_POST['customers_id'];

//     self::load_db_values((int)self::$cID);

    self::$actions['action'] = self::$action;
    self::$actions['display_file']='';
    self::$actions['action_class']=(isset($_GET['action_class']))? $_GET['action_class'] : '';
    self::$actions['action_method']=(isset($_GET['action_method']))? $_GET['action_method'] : '';

  // Ask categories modules if want to change the action
    self::$actions = self::$modules->check_action(self::$actions);
    self::$action = self::$actions['action'];




    if ( empty(self::$actions['action_class']) ) {

      switch (self::$action) {

	case 'setflag':
	  if ( ($_GET['flag'] == '0') || ($_GET['flag'] == '1') ) {
	    $newsletter_id = tep_db_prepare_input($_GET['cID']);

	    if (!empty($newsletter_id))
	      $DB->query("update " . TABLE_CUSTOMERS . " set customers_status = '" .(int) $_GET['flag'] . "' where customers_id = '" . (int)$newsletter_id . "'");
	  }

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

	case 'insert':

          if( ($result=$this->userCreate($_POST)) !=false ){
	    $myarray = array(
			    'email_use_html'=>_cst_bool('EMAIL_USE_HTML'),
			    'links'=>HTTP_SERVER ,
			    'firstname'=>$result['customers_firstname'],
			    'lastname'=>$result['customers_lastname'],
			    'email_address'=>$result['customers_email_address'],
			    'Password'=>$result['customers_password'],
			    'message'=>''
			    );
	    $message_final=tep_post_prepare_email('add_customer.tpl',$language,$myarray);
	    tep_mail($result['customers_firstname'] . ' ' . $result['customers_lastname'], $result['customers_email_address'],__('email text subject'), $message_final);


	    if(isset($_POST['up_and_close']) ) tep_redirect(tep_href_link(self::FILENAME));
	    else tep_redirect(tep_href_link(self::FILENAME, 'cID=' .$result['customers_id'].'&action=edit'));


	  } else /*if (self::$error == true) */{
	    $_POST['customers_gender']='m';
	    $cInfo = new objectInfo($_POST);
	    $dest_form='insert';
	  }

	break;
	case 'update':
	  $customers_id = tep_db_prepare_input(self::$cID);
	  $customers_firstname = tep_db_prepare_input($_POST['customers_firstname']);
	  $customers_lastname = tep_db_prepare_input($_POST['customers_lastname']);
	  $customers_email_address = tep_db_prepare_input($_POST['customers_email_address']);
	  $customers_telephone = tep_db_prepare_input($_POST['customers_telephone']);
	  $customers_fax = tep_db_prepare_input($_POST['customers_fax']);
	  $customers_newsletter = tep_db_prepare_input($_POST['customers_newsletter']);
	  $customers_group_ra = (int)tep_db_prepare_input($_POST['customers_group_ra']);
	  $customers_gender = (isset($_POST['customers_gender'])) ? tep_db_prepare_input($_POST['customers_gender']) : 1 ;
	  if (_cst_bool('ACCOUNT_DOB')) $customers_dob = tep_db_prepare_input($_POST['customers_dob']);

	  $global_product_notifications = tep_db_prepare_input($_POST['global_product_notifications']);

	  try{
	    if (strlen($customers_firstname) < ENTRY_FIRST_NAME_MIN_LENGTH) throw new Exception(__("Le nombre de caractéres ne suffit pour le nom, min:").ENTRY_FIRST_NAME_MIN_LENGTH);
	    if (strlen($customers_lastname) < ENTRY_LAST_NAME_MIN_LENGTH) throw new Exception(__("Le nombre de caractéres ne suffit pour le nom, min:").ENTRY_LAST_NAME_MIN_LENGTH);
	    if (_cst_bool('ACCOUNT_DOB'))
	      if (!checkdate(substr(tep_date_raw($customers_dob), 5, 2), substr(tep_date_raw($customers_dob), 8, 2), substr(tep_date_raw($customers_dob), 0, 4))) throw new Exception(__("Le format de la date de naissance n'est pas correct"));
	    if (strlen($customers_email_address) < ENTRY_EMAIL_ADDRESS_MIN_LENGTH) throw new Exception(__("L'adresse email es trop courte, min:").ENTRY_EMAIL_ADDRESS_MIN_LENGTH);
	    if (!self::tep_validate_email($customers_email_address))throw new Exception(__("L'adresse email n'est pas correct"));
	    if (strlen($customers_telephone) < ENTRY_TELEPHONE_MIN_LENGTH)throw new Exception(__("Le numero de téléphone est trop court"));


	  }catch(Exception $e){
	    $messageStack->add($e->getMessage(), 'error');
	    self::$error=true;
	  }

	  if (self::$error == false) {

	    $sql_data_array = array('customers_firstname' => $customers_firstname,
				    'customers_lastname' => $customers_lastname,
				    'customers_email_address' => $customers_email_address,
				    'customers_telephone' => $customers_telephone,
				    'customers_fax' => $customers_fax,
				    'customers_newsletter' => $customers_newsletter,
				    'customers_group_ra' => $customers_group_ra,
				    'customers_shopping_points' => ((isset($_POST['customers_shopping_points'])) ? (int)tep_db_prepare_input($_POST['customers_shopping_points']) : 0) );

	    if (_cst_bool('ACCOUNT_GENDER')) $sql_data_array['customers_gender'] = $customers_gender;
	    if (_cst_bool('ACCOUNT_DOB')) $sql_data_array['customers_dob'] = tep_date_raw($customers_dob);


	    self::$modules->load_post_values($_POST);
	    $sql_data_array = array_merge($sql_data_array, self::$modules->update_table_prim());

	    tep_db_perform(TABLE_CUSTOMERS, $sql_data_array, 'update', "customers_id = '" . (int)$customers_id . "'");


	    self::$modules->load_post_values($_POST);
	    $sql_data_array = array_merge($sql_data_array, self::$modules->update_table_second());

	    $DB->query("update " . TABLE_CUSTOMERS_INFO . " set global_product_notifications = '".$global_product_notifications."' where customers_info_id = '" . (int)$customers_id . "'");


	    self::$modules->after_update((int)$customers_id);

	  if(isset($_POST['up_and_close']) ) tep_redirect(tep_href_link(self::FILENAME));
	  else tep_redirect(tep_href_link(self::FILENAME, 'cID=' .$customers_id.'&action=edit'));


	  } else if (self::$error == true) {
	    $cInfo = new objectInfo($_POST);
	    self::$processed = true;
	    $dest_form='update';
	  }

	break;
	case 'deleteconfirm':
	  $customers_id = tep_db_prepare_input(self::$cID);

	  $this->userDelete($customers_id);

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

	case 'new':
	  $dest_form='insert';
	  $array=array(
	    'customers_gender'=>'',
	    'customers_firstname'=>'',
	    'customers_lastname'=>'',
	    'customers_email_address'=>'',
	    'customers_telephone'=>'',
	    'customers_fax'=>'',
	    'customers_newsletter'=>'',
	    'global_product_notifications'=>'',
	    'customers_group_ra'=> '',
	    'customers_default_address_id'=>'',
	    'customers_dob'=>'',
	    'customers_group_id'=>0,
	    'customers_shopping_points'=>0);
	  self::$cInfo = new objectInfo($array);
	break;
	case 'noedit':
	  self::$processed=true;
	break;
      }

    } else {
      /*
	       A module has asked to privately take care of this action, check if class and method exist and run it.
      */
			if (!empty(self::$actions['action_method']) && method_exists(self::$modules->modules[self::$actions['action_class']],self::$actions['action_method'] )){
			  $metho=self::$actions['action_method'];
			  self::$box = new box;
			  self::$box=self::$modules->modules[self::$actions['action_class']]->$metho(self::$box,(int)$_GET['pID']);
			}
    }

    return $_return;
  }


  public function get_header(){
    if (in_array(self::$action,array('edit','update','new','insert'))) {  ?>
    <script type="text/javascript"><!--

    function check_form() {
      var error = 0;
      var error_message = "<?php echo JS_ERROR; ?>";

      var customers_firstname = document.customers.customers_firstname.value;
      var customers_lastname = document.customers.customers_lastname.value;
    <?php if (_cst_bool('ACCOUNT_DOB')) echo 'var customers_dob = document.customers.customers_dob.value;' . "\n"; ?>
      var customers_email_address = document.customers.customers_email_address.value;
      var customers_telephone = document.customers.customers_telephone.value;

    <?php if (_cst_bool('ACCOUNT_GENDER')) { ?>
      if (document.customers.customers_gender[0].checked || document.customers.customers_gender[1].checked) {
      } else {
	error_message = error_message + "<?php echo addslashes(__('js gender')); ?>";
	error = 1;
      }
    <?php } ?>

      if (customers_firstname == "" || customers_firstname.length < <?php echo ENTRY_FIRST_NAME_MIN_LENGTH; ?>) {
	error_message = error_message + "<?php echo sprintf(addslashes(__('js first name')), ENTRY_FIRST_NAME_MIN_LENGTH) ; ?>";
	error = 1;
      }

      if (customers_lastname == "" || customers_lastname.length < <?php echo ENTRY_LAST_NAME_MIN_LENGTH; ?>) {
	error_message = error_message + "<?php echo sprintf(addslashes(__('js last name')), ENTRY_LAST_NAME_MIN_LENGTH); ?>";
	error = 1;
      }

    <?php if (_cst_bool('ACCOUNT_DOB')) { ?>
      if (customers_dob == "" || customers_dob.length < <?php echo ENTRY_DOB_MIN_LENGTH; ?>) {
	error_message = error_message + "<?php echo sprintf(addslashes(__('js dob')), ENTRY_DOB_MIN_LENGTH); ?>";
	error = 1;
      }
    <?php } ?>

      if (customers_email_address == "" || customers_email_address.length < <?php echo ENTRY_EMAIL_ADDRESS_MIN_LENGTH; ?>) {
	error_message = error_message + "<?php echo sprintf(addslashes(__('js email address')), ENTRY_EMAIL_ADDRESS_MIN_LENGTH); ?>";
	error = 1;
      }


      if (customers_telephone == "" || customers_telephone.length < <?php echo ENTRY_TELEPHONE_MIN_LENGTH; ?>) {
	error_message = error_message + "<?php echo JS_TELEPHONE; ?>";
	error = 1;
      }

      if (error == 1) {
	alert(error_message);
	return false;
      } else {
	return true;
      }
    }
    // -->
    </script>
    <?php }

  }


  public static function load_db_values($ID){
    global $languages_id;

    $DB=Database::getInstance();

    // base customers
    $query_raw = "select c.customers_id, c.customers_lastname, c.customers_gender, c.customers_dob, c.customers_newsletter,c.customers_firstname,c.customers_default_address_id, c.customers_email_address,c.customers_group_ra, c.customers_telephone, c.customers_fax, a.entry_country_id,c.customers_group_id,c.customers_language , cg.customers_group_name, c.customers_shopping_points, c.customers_discount  from " . TABLE_CUSTOMERS . " c left join " . TABLE_ADDRESS_BOOK . " a on c.customers_id = a.customers_id and c.customers_default_address_id = a.address_book_id  left join " . TABLE_CUSTOMERS_GROUPS . " cg on c.customers_group_id = cg.customers_group_id  WHERE c.customers_id='".$ID."'" ;
    $pq=$DB->query($query_raw);
    if(!$pq->__get('numRows')) return false;
    $customers = $pq->fetchAssoc();
    $pq->__destruct();

    // info detal customers
    $customers['countries_name']=tep_get_country_name($customers['entry_country_id']);
    $info_query = $DB->query("select customers_info_date_account_created as date_account_created, customers_info_date_account_last_modified as date_account_last_modified,  customers_info_date_of_last_logon as date_last_logon, customers_info_number_of_logons as number_of_logons , global_product_notifications from " . TABLE_CUSTOMERS_INFO . " where customers_info_id = '" . $customers['customers_id'] . "'");
    $class_s='';
    $info = $info_query->fetchAssoc();
    // nbre commande
    $info_query = $DB->query("select orders_id  from " . TABLE_ORDERS. " where customers_id = '" . $customers['customers_id'] . "'");
    $det=$info_query->fetchAllAssoc();
    $info['orders'] =count($det);
    $info['orders_detail']=$det;
    self::$cInfo=new objectInfo(array_merge((array)$customers,(array)$info));
  }

  /**
  */
  public function display_view() {
    $action=self::$action;

    switch(self::$action){
      case 'confirm':
	self::load_db_values(self::$cID);
	 $action='delete';
      break;
      case 'update':
      case 'noedit':
      case 'edit':
	self::load_db_values(self::$cID);
      case 'insert':
      case 'new':
	 $action='edit';
      break;
      default:

	if(!empty(self::$actions['action_method']) )
	   $action='aca_actions';
	else {
	  $action='listing';
	  self::tep_get_list();
	}
    }
    /// use master gabarit
    return MGabCont::CallGab($action,__FUNCTION__,__CLASS__);
  }

/** public static InterfacedTJsonS */

  /**
    @fn get_item_action($orders)
    @brief fonction qui construit l'affichage de la colonne action
      La mise en forme est contenu dans les ressource xml du template en cours
    @param $orders array
    @return string
  */
  private static function get_item_action($customers){
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  self::$modules->display_ColumnRowAction($customers['customers_id']) ,
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'noedit'), '',  tep_href_link(self::FILENAME,'cID=' . $customers['customers_id'].'&amp;action=noedit'  ),'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME,'cID=' . $customers['customers_id'].'&amp;action=edit'  ),'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME, 'cID=' . $customers['customers_id'].'&amp;action=confirm' ) ,'' )
		  );
  }

  private static function get_status_da($customers){
    if ($customers['customers_group_ra'] == '1')
      return  tep_image(DIR_WS_ICONS . 'icon_view_green.gif', IMAGE_ICON_STATUS_GREEN, 10, 10);
    else
      return  tep_image(DIR_WS_ICONS . 'icon_view_red.gif', IMAGE_ICON_STATUS_RED, 10, 10);;

  }

  private static function get_status_c($customers){
    $exclude=array('action','cID','forceajax','type','class','function','funct', 'mod');
    $query_s='action=setflag&amp;cID=' . $customers['customers_id'].'&amp;flag=';

    if ($customers['customers_status'] == '1')
      return  tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . '&nbsp;<a href="' . tep_href_link(self::FILENAME, tep_get_all_get_params($exclude).$query_s.'0' ) . '">' . 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,  tep_get_all_get_params($exclude).$query_s.'1') . '">' . 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(){
    return array(   'null',
		    'customers_id',
		    'customers_lastname',
		    'customers_firstname',
		    'customers_group_name',
		    'customers_shopping_points',
		    'customers_info_date_account_created',
		    'customers_info_date_account_last_modified',
		    'customers_group_ra',
		    'status',
		    'action'
	  );
  }

  public static function tep_get_modele(){
      return array( 0 =>false,
		    'customers_id' =>true,
		    'customers_lastname'=>true,
		    'customers_firstname'=>true,
		    'customers_group_name'=>true,
		    'customers_shopping_points'=>true,
		    'customers_info_date_account_created'=>true,
		    'customers_info_date_of_last_logon'=>true,
		    'customers_group_ra'=>true,
		    'customers_status'=>true,
		    'action'=>false
	      );
  }

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

    new self;

    $DB=Database::getInstance();
    if(tep_not_null($sWhere)){
      $sWhere=str_replace(array('customers_id',
				),
			  array('c.customers_id',
				),
	      $sWhere);
    }
    $query_raw = "select c.customers_id, c.customers_lastname, c.customers_firstname, c.customers_email_address,c.customers_group_ra,  cg.customers_group_name , customers_info_date_account_created , customers_info_date_account_last_modified , customers_info_date_of_last_logon , customers_info_number_of_logons as number_of_logons, customers_shopping_points , customers_status".
		  " from " . TABLE_CUSTOMERS . " c, " . TABLE_CUSTOMERS_INFO . " ci ," . TABLE_CUSTOMERS_GROUPS . " cg ".
		  " WHERE c.customers_id=customers_info_id and c.customers_group_id = cg.customers_group_id " . $sWhere." order by  ".((!empty($sOrder)) ? $sOrder: 'c.customers_lastname, c.customers_firstname  ASC');

    $customers_split = new splitPageResults($page, $rowbyp, $query_raw,$query_numrows);

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

    while ($customers = $pq->fetchAssoc()) {
      $info['customers_info_date_account_created']=tep_date_short($customers['customers_info_date_account_created']);
      $info['customers_info_date_of_last_logon']=tep_date_short($customers['customers_info_date_of_last_logon']);

      $inf=array_merge((array)$customers,(array)$info);
      $inf[0]=$inf['customers_id'];
      $inf['customers_group_ra']=self::get_status_da($inf);
      $inf['customers_status']=self::get_status_c($inf);
      $inf['action']=self::get_item_action($inf);
      self::$list[]=$inf;
    }

    $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){
    self::init();
    self::load_db_values((int)$id);


    $res=tep_db_query($customers_query_raw = "select sum(op.products_quantity * op.final_price) as ordersum from " . TABLE_CUSTOMERS . " c, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS . " o where c.customers_id = o.customers_id and c.customers_id='".(int)$id."' and o.orders_id = op.orders_id group by c.customers_firstname, c.customers_lastname order by ordersum DESC");
    $r=tep_db_fetch_array($res);
    self::$cInfo->orders_sum=$r['ordersum'];
    return tep_get_include_contents(__CLASS__.'.inline');
  }


  /** Interne module */
  public static function tep_view_news_human($value){
    return ($value == '1')? __('entry newsletter yes') :   ('entry newsletter no') ;
  }

  /**
    @param  string $value
  */
  public static function tep_view_gender_human($value){
    $s='';
    if($value=='m') $s= MALE;
    elseif($value=='f') $s= FEMALE;
    elseif($value=='l') $s= MLLE;
    return $s;
  }


  /**
   * \fn  tep_get_grp_name($id)
   * \brief get group name for customer id
   * @param unknown_type $id
   */
  public static function tep_get_grp_name($id){
    $res=tep_db_query("select customers_group_id, customers_group_name from " . TABLE_CUSTOMERS_GROUPS . " ");
    if(tep_db_num_rows($res)>1 && self::$action !='noedit'){
      while($item = tep_db_fetch_array($res))
	       $array[]=array('id'=> $item['customers_group_id'] , 'text'=>$item['customers_group_name']);

      return tep_draw_pull_down_menu('customers_group_id', $array, $id);
    }
    else {
      $query =  tep_db_fetch_array(tep_db_query("select customers_group_name from " . TABLE_CUSTOMERS_GROUPS . " where customers_group_id='".$id."'  "));
      return $query['customers_group_name'];
    }
  }


  /**
   * \fn userTestNotExists($customers_email_address)
   * \brief test user exists
   * @param $customers_email_address
   */
  static public function userTestNotExists($customers_email_address){
    $check_email = tep_db_query("select customers_email_address from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($customers_email_address) . "'  ");
    return (tep_db_num_rows($check_email))? false : true ;
  }


  /**
   * \fn userCreate($_post)
   * \brief creat user
   * @param unknown_type $_post
   */
  public function userCreate($_post){
    global $languages_id,$messageStack;

    $customers_firstname = tep_db_prepare_input($_post['customers_firstname']);
    $customers_lastname = tep_db_prepare_input($_post['customers_lastname']);
    $customers_email_address = tep_db_prepare_input($_post['customers_email_address']);
    $customers_telephone = tep_db_prepare_input($_post['customers_telephone']);
    $customers_fax = tep_db_prepare_input($_post['customers_fax']);
    $customers_newsletter = tep_db_prepare_input($_post['customers_newsletter']);
    $customers_group_ra = (int)tep_db_prepare_input($_post['customers_group_ra']);
    $customers_gender = tep_db_prepare_input($_post['customers_gender']);
    if (_cst_bool('ACCOUNT_DOB')) $customers_dob = tep_db_prepare_input($_post['customers_dob']);
    //$default_address_id = tep_db_prepare_input($_POST['default_address_id']);
    $global_product_notifications = tep_db_prepare_input($_post['global_product_notifications']);

    try{
      /*
      * \brief test user is exists email address in db
      */
      if (!self::userTestNotExists($customers_email_address))throw new Exception(__('entry email address error exists'));

      if (strlen($customers_firstname) < ENTRY_FIRST_NAME_MIN_LENGTH) throw new Exception(__("Le nombre de caractéres ne suffit pour le nom, min:").ENTRY_FIRST_NAME_MIN_LENGTH);
      if (strlen($customers_lastname) < ENTRY_LAST_NAME_MIN_LENGTH) throw new Exception(__("Le nombre de caractéres ne suffit pour le nom, min:").ENTRY_LAST_NAME_MIN_LENGTH);
      if (_cst_bool('ACCOUNT_DOB'))
      if (!checkdate(substr(tep_date_raw($customers_dob), 5, 2), substr(tep_date_raw($customers_dob), 8, 2), substr(tep_date_raw($customers_dob), 0, 4))) throw new Exception(__("Le format de la date de naissance n'est pas correct"));

      if (strlen($customers_email_address) < ENTRY_EMAIL_ADDRESS_MIN_LENGTH) throw new Exception(__("L'adresse email est trop courte, min:").ENTRY_EMAIL_ADDRESS_MIN_LENGTH);
      if (!self::tep_validate_email($customers_email_address))throw new Exception(ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
      if (strlen($customers_telephone) < ENTRY_TELEPHONE_MIN_LENGTH)throw new Exception(__("Le numero de téléphone est trop court"));

      $extra_fields_query = tep_db_query("select ce.fields_id, ce.fields_input_type, ce.fields_required_status, cei.fields_name, ce.fields_status, ce.fields_input_type, ce.fields_size from " . TABLE_EXTRA_FIELDS . " ce, " . TABLE_EXTRA_FIELDS_INFO . " cei where ce.fields_status=1 and ce.fields_required_status=1 and cei.fields_id=ce.fields_id and cei.languages_id =" . $languages_id);
      while($extra_fields = tep_db_fetch_array($extra_fields_query)){
       if(strlen($_post['fields_' . $extra_fields['fields_id']]) < $extra_fields['fields_size'])throw new Exception(sprintf(ENTRY_EXTRA_FIELDS_ERROR,$extra_fields['fields_name'],$extra_fields['fields_size']) );
      }

    }catch(Exception $e){
      $messageStack->add($e->getMessage(), 'error');
      self::$error=true;
    }

    if (self::$error == false) {

      $mdp=self::randomize();

      $sql_data_array = array('customers_firstname' => $customers_firstname,
      'customers_lastname' => $customers_lastname,
      'customers_email_address' => $customers_email_address,
      'customers_telephone' => $customers_telephone,
      'customers_fax' => $customers_fax,
      'customers_password'=>$mdp,
      'customers_newsletter' => $customers_newsletter,
      'customers_group_ra' => $customers_group_ra );

      if (_cst_bool('ACCOUNT_GENDER')) $sql_data_array['customers_gender'] = $customers_gender;
      if (_cst_bool('ACCOUNT_DOB')) $sql_data_array['customers_dob'] = tep_date_raw($customers_dob);

      self::$modules->load_post_values($_post);
      $sql_data_array = array_merge($sql_data_array, self::$modules->insert_table_prim () );

      $_return= $sql_data_array;

      $resobj=tep_db_perform(TABLE_CUSTOMERS, $sql_data_array);

      $lastid=tep_db_insert_id($resobj);

      $sql_data_array = array('customers_info_id' => $lastid,
      'customers_info_date_account_created' => 'now()',
      'global_product_notifications' => $global_product_notifications);

      $_return=array_merge($_return,$sql_data_array);

      tep_db_perform(TABLE_CUSTOMERS_INFO, $sql_data_array);

      self::$modules->load_post_values(array_merge(array('customers_id'=>$lastid),$_post) );
      $sql_data_array = array_merge($sql_data_array, self::$modules->insert_table_second() );

      $_return=array_merge($_return,$sql_data_array,array('customers_id'=>$lastid));

      return $_return;
    }
    else
      return false;

  }

  /**
   * \fn userDelete($customers_id)
   * \brief delete user
   * @param unknown_type $customers_id
   */
  public function userDelete($customers_id){
    tep_db_query("delete from " . TABLE_CUSTOMERS . " where customers_id = '" . (int)$customers_id . "'");
    tep_db_query("delete from " . TABLE_CUSTOMERS_INFO . " where customers_info_id = '" . (int)$customers_id . "'");
    tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET . " where customers_id = '" . (int)$customers_id . "'");
    tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where customers_id = '" . (int)$customers_id . "'");
    tep_db_query("delete from " . TABLE_WHOS_ONLINE . " where customer_id = '" . (int)$customers_id . "'");

    self::$modules->deleteconfirm_account ($customers_id);
  }

/** Private specific module */
  private static function randomize() {
    $salt = "abchefghjkmnpqrstuvwxyz0123456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass='';
    while ($i <= 7) {
			$num = rand() % 33;
			$tmp = substr($salt, $num, 1);
			$pass = $pass . $tmp;
			$i++;
    }
    return $pass;
  }


  /**
   * \brief test forme email
   * @param $email string
   */
  private static function tep_validate_email($email) {
    $valid_address = true;

    $mail_pat = '^(.+)@(.+)$';
    $valid_chars = "[^] \(\)<>@,;:\.\\\"\[]";
    $atom = "$valid_chars+";
    $quoted_user='(\"[^\"]*\")';
    $word = "($atom|$quoted_user)";
    $user_pat = "^$word(\.$word)*$";
    $ip_domain_pat='^\[([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\]$';
    $domain_pat = "^$atom(\.$atom)*$";

    if (preg_match('/'.$mail_pat.'/i', $email, $components)) {
      $user = $components[1];
      $domain = $components[2];
      // validate user
      if (preg_match('/'.$user_pat.'/i', $user)) {
        // validate domain
        if (preg_match('/'.$ip_domain_pat.'/i', $domain, $ip_components)) {
          // this is an IP address
      	  for ($i=1;$i<=4;$i++) {
      	    if ($ip_components[$i] > 255) {
      	      $valid_address = false;
      	      break;
      	    }
          }
        }
        else {
          // Domain is a name, not an IP
          if (preg_match('/'.$domain_pat.'/i', $domain)) {
            /* domain name seems valid, but now make sure that it ends in a valid TLD or ccTLD
               and that there's a hostname preceding the domain or country. */
            $domain_components = explode(".", $domain);
            // Make sure there's a host name preceding the domain.
            if (sizeof($domain_components) < 2) {
              $valid_address = false;
            } else {
              $top_level_domain = strtolower($domain_components[sizeof($domain_components)-1]);
              // Allow all 2-letter TLDs (ccTLDs)
              if (preg_match('/^[a-z][a-z]$/i', $top_level_domain) != 1) {
                $tld_pattern = '';
                // Get authorized TLDs from text file
                $tlds = file(DIR_WS_INCLUDES . 'tld.txt');
                while (list(,$line) = each($tlds)) {
                  // Get rid of comments
                  $words = explode('#', $line);
                  $tld = trim($words[0]);
                  // TLDs should be 3 letters or more
                  if (preg_match('/^[a-z]{3,}$/i', $tld) == 1) {
                    $tld_pattern .= '^' . $tld . '$|';
                  }
                }
                // Remove last '|'
                $tld_pattern = substr($tld_pattern, 0, -1);
                if (preg_match("/$tld_pattern/i", $top_level_domain) == 0) {
                    $valid_address = false;
                }
              }
            }
          }
          else {
      	    $valid_address = false;
      	  }
      	}
      }
      else {
        $valid_address = false;
      }
    }
    else {
      $valid_address = false;
    }
    if ($valid_address && ENTRY_EMAIL_ADDRESS_CHECK == 'true') {
      if (!checkdnsrr($domain, "MX") && !checkdnsrr($domain, "A")) {
        $valid_address = false;
      }
    }
    return $valid_address;
  }





/** Interface module */

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






class accountACA
  extends aca
    implements mod_aca{
    var $modules=array();
    var $account_id;
    var $image_handler;

  /**
    class constructor
  */
  function __construct() {
    global $language, $lang,$oscss;
    $this-> name='account';
    $this-> account_id='';
    $this-> image_handler='';

    foreach(parent::initialise_type('MODULE_ACCOUNT_INSTALLED_BO','account') as $class){
	$cl[$class]=new $class ();
	$list_mod[$class] = $cl[$class]->sort_order;

	asort($list_mod);
	foreach($list_mod as $class=>$s){
	  $this->modules[$class] =$cl[$class];
	}
	unset($cl);unset($list_mod);
    }
  }


  function after_update ($account_id){
    $this->account_id=$account_id;
    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and (method_exists($module,'after_update' )))
	$this->modules[$key]->after_update($this->account_id);
    }
    $languages = tep_get_languages();
    for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
      $language_id = $languages[$i]['id'];
      foreach ($this->modules as $key=>$module) {
	if (($module->enabled) and (method_exists($module,'after_update_lang' )))
	  $this->modules[$key]->after_update_lang($language_id, $this->account_id);
      }
    }
  }

  /**
    Load each module parameters from database
  */
  function load_db_values ($account_id) {
    $this->account_id=$account_id;
    if (is_array($this->modules))
    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and method_exists($module, 'load_db_values' ))  $this->modules[$key]->load_db_values($account_id);
    }
  }

  function load_post_values ($post) {
    // Load each module parameters from the HTTP POST variables
    $post = $this->check_post_array ($post); // Put some non-array variables into array
    $this->account_id = @$_GET['pID']; // Save the product ID

    foreach ($this->modules as $key=>$module) {
      if (($module->enabled) and (method_exists($module, 'load_post_values' )) and (isset($post[$module->code])))
	       $this->modules[$key]->load_post_values($post[$module->code]);

      elseif (($module->enabled) and (method_exists($module, 'load_post_values' )))
        $this->modules[$key]->load_post_values($post);
    }
  }

//   function repost_values (){
//   }


  function display_preview($languages){
    // Collect datas for product preview display
    $contents = array();
    foreach ($this->modules as $key=>$module) {
	      if (($module->enabled) and (method_exists($module, 'display_preview' ))) {
		$this->modules[$key]->display_preview($contents, $languages);
	      }
    }
    return $contents;
  }

//   function display_image_preview (){
//   }

  /**
    Affichage en mode liste, detail, colonne droite
    Ask each product module about what to dispay in the listing left column.
  */
  public function display_right_column ($contents, $account_id) {
    global $language;
    if (is_array($this->modules))
    foreach ($this->modules as $key=>$module)  {
      if ($module->enabled && method_exists($module, 'display_right_column' )) {
	$this->modules[$key]->load_db_values($account_id);
	$contents=$this->modules[$key]->display_right_column($contents, $account_id);
      }
    }
    return $contents;
  }

//   public function display_ColumnRowAction($id){
//     $st='';
//     foreach ($this->modules as $key=>$module)
//       if (($module->enabled) and (method_exists($module,'display_ColumnRowAction' )))
// 	$st .=$this->modules[$key]->display_ColumnRowAction($id);
//     return $st;
//   }

  /**
    Suppression apres confirmation
  */
  /**
   * \fn  deleteconfirm_account ($id)
   * \brief delete account user for id
   *     loop module account
   * @param $id integer account id customer
   * @return no
   */
  public function deleteconfirm_account ($id){
    foreach ($this->modules as $key=>$module)
      if (($module->enabled) and  method_exists($module, 'deleteconfirm_account' ))
	       $this->modules[$key]->deleteconfirm_account($id);
  }


}



?>