<?php
/**
  @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  22/01/11, 20:24
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
 *\dir includes/modules/account/
 *\file
 *\class address_book
 *\group modules
 *\brief Address book for customers
*/

class address_book
  extends AbstractAccount
    implements InterfaceModule{

  /**
    @var array
  */
  public static $account;
  /**
    @var array
  */
  public static $adress_book;
  /**
    @var numeric
  */
  public static $count;
  /**
    @var string
  */
  public static $display_view_form_title;

  /**
  */
  function __construct(){
    $this->code =__CLASS__;
    $this->type ='account';
    $this->title = __('module aca address book text title');
    $this->description = __('module aca address book text description') ;
    $this->sort_order = (defined('MODULE_ACA_ADDRESS_BOOK_SORT_ORDER')) ? MODULE_ACA_ADDRESS_BOOK_SORT_ORDER : 0;
    $this->enabled = true;


    $this->sql_data_array=array();
    $this->cInfo = new objectInfo(array());

    $page=page::getInstance();
    $page->new_class('javascript');

    /// script validate js
    $page->javascript->add_framework("ext/jquery/jquery.min.js");
    $page->javascript->add_script("ext/jquery/jquery.validate.min.js", array('sort'=>30));

    /// call js view last time
    $file=DIR_WS_INCLUDES.'js/'.__CLASS__.'.js.php';
    if( ($file=page::fix_file($file)) && $file !=false ) $page->javascript->add_script($file, array('sort'=>30));
  }

  public function get_header($action=''){}

  /**
   * \fn check_action($action)
   * \brief Action exe
   * @param $action string la var d'action
   * @p $cID int recupere le Session[]
  */
  public function check_action($action) {

//     if ($action != 'process') return false;
    if (!tep_session_is_registered('customer_id')) return false;

    global $page;
    $customer_id=$page->the_var('customer_id');

    switch ($action) {

      case 'update':
      case 'new':
	/**
	  @brief use class customer class
	*/
	$custo=customer::getInstance();
	/// force retour error sans session
	customer::definePostMess(0);


	if ( ($resul=$custo->CheckDataAddressBook($_POST, 'addressbook')) && $resul !=false && is_array($resul)) {

	if (_cst_bool('CUSTOMER_FORCE_UCWORDS')) {
	  $resul['lastname']=ucwords($resul['lastname']);
	  $resul['firstname']=ucwords($resul['firstname']);
	}
	if (_cst_bool('CUSTOMER_FORCE_STRTOUPPER')) {
	  $resul['lastname']=strtoupper($resul['lastname']);
	}

	if (_cst_bool('CUSTOMER_CITY_FORCE_STRTOUPPER')) {
	  $resul['city']=strtoupper($resul['city']);
	}

          $sql_data_array = array('entry_firstname' => $resul['firstname'],
                                  'entry_lastname' => $resul['lastname'],
                                  'entry_street_address' => $resul['street_address'],
                                  'entry_postcode' => $resul['postcode'],
                                  'entry_city' => $resul['city'],
                                  'entry_country_id' => (int)$resul['country']);

          if (_cst_bool('ACCOUNT_GENDER')) $sql_data_array['entry_gender'] = $resul['gender'];
          if (_cst_bool('ACCOUNT_COMPANY')){
            $sql_data_array['entry_company'] = $resul['company'];
            $sql_data_array['entry_company_tax_id'] = $resul['company_tax_id'];
          }
          if (_cst_bool('ACCOUNT_SUBURB')) $sql_data_array['entry_suburb'] = $resul['suburb'];
          if (_cst_bool('ACCOUNT_STATE')) {
            if (isset($resul['zone_id']) && $resul['zone_id'] > 0) {
              $sql_data_array['entry_zone_id'] = (int)$resul['zone_id'];
              $sql_data_array['entry_state'] = '';
            } else {
              $sql_data_array['entry_zone_id'] = '0';
              $sql_data_array['entry_state'] = $resul['state'];
            }
          }

          if ($action == 'update') {
            tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array, 'update', "address_book_id = '" . (int)$_GET['edit'] . "' and customers_id ='" . (int)$customer_id . "'");
             $new_address_book_id= (int)$_GET['edit'];
          } else {
            $sql_data_array['customers_id'] = (int)$customer_id;
            tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);


            $cs_s=tep_db_query("select address_book_id from " . TABLE_ADDRESS_BOOK . "  where customers_id='".$customer_id."' ORDER BY address_book_id DESC");
            $cs=tep_db_fetch_array($cs_s);
            $new_address_book_id=$cs['address_book_id'];
          }

            if (isset($_POST['primary']) && ($_POST['primary'] == 'on')) {
              $sql_data_array=array();
              $sql_data_array['customers_default_address_id'] = $new_address_book_id;

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


          $page->messageStack->add('addressbook', __('SUCCESS_ADDRESS_BOOK_ENTRY_UPDATED'), 'success');
        }
        break;

        case 'deleteconfirm':
          if(!isset($_GET['delete']) || !is_numeric($_GET['delete'])  ) return false;
/** ADD control addresse defaut */

          tep_db_query("delete from " . TABLE_ADDRESS_BOOK . " where address_book_id = '" . (int)$_GET['delete'] . "' and customers_id = '" . (int)$customer_id . "'");

          $page->messageStack->add_session('addressbook', __('SUCCESS_ADDRESS_BOOK_ENTRY_DELETED'), 'success');
        break;
    }

    return true;
  }

  /**
  */
  public function after_check_action ($action) {
    if($action=='new')  tep_redirect(tep_href_link(FILENAME_ACCOUNT, 'aca_mod='.$this->code.'&amp;aca_type='.$this->type.'&aca_action=display_view', 'SSL'));
  }

  /**
  */
  public function update_table_account () {

    //! This function returns an array with variables to update into TABLE_ADDRESS_BOOK
    $sql_data_array=$this->sql_data_array;
    tep_db_perform(TABLE_ADDRESS_BOOK, $this->cInfo->sql_data_array, 'update', "customers_id = '" . (int)$_GET['cID'] . "' and address_book_id = '" . (int)$this->cInfo->customers_default_address_id . "'");

    return array();
  }

  /**
  */
  public function load_db_values($cID) {
    $cpt=0;
    $addresses_query = tep_db_query("select address_book_id, entry_firstname as firstname, entry_lastname as lastname, entry_company as company,entry_company_tax_id as company_tax_id, entry_street_address as street_address, entry_suburb as suburb, entry_city as city, entry_postcode as postcode, entry_state as state, entry_zone_id as zone_id, entry_country_id as country_id from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$cID . "' order by firstname, lastname");
    while ($addresses = tep_db_fetch_array($addresses_query)){
       $addr[$addresses['address_book_id']]=$addresses;
       $cpt++;
    }

     $this->cInfo->objectInfo(
        array('adress_book'=>$addr,
              'the_count'=>$cpt
        ) );
  }

  public function load_db_address($cID) {
    $entry_query = tep_db_query("select entry_gender, entry_company, entry_firstname, entry_lastname, entry_street_address, entry_suburb, entry_postcode, entry_city, entry_state, entry_zone_id, entry_country_id from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$cID . "' and address_book_id = '" . (int)$_GET['edit'] . "'");

    if (!tep_db_num_rows($entry_query)) {
      $page->messageStack->add_session('addressbook', __('ERROR_NONEXISTING_ADDRESS_BOOK_ENTRY'));

      tep_redirect(tep_href_link(FILENAME_ACCOUNT, 'aca_mod='.$this->code.'&amp;aca_type='.$this->type.'&aca_action=display_view', 'SSL'));
    }
    $this->cInfo->objectInfo(array('entry_adress_book'=>tep_db_fetch_array($entry_query)));
  }



  public function repost_values () {
    // Repost all values that are not arrays
    foreach ($this->pInfo as $key=>$val) {
      if (!is_array($this->pInfo[$key]))  echo "\n".tep_draw_hidden_field($this->code .'['.$key.']', stripslashes($val))."\n";

    }
  }

  /**
    List  des element du block my account
  */
  public function display_view_min_listMyAccount($cID){
    global  $page;

    $v['title']=__("Afficher ou modifier des entrées dans mon carnet d'adresses.");
    $v['href_link']= tep_href_link(FILENAME_ACCOUNT, 'aca_mod='.$this->code.'&amp;aca_type='.$this->type.'&amp;aca_action=display_view', 'SSL');
    return array(new objectInfo($v));
  }

  /**
   * \fn display_view($pID='')
   * \brief Affiche Block edit/modif reviews
   * @param $pID int id products
   * @p $customer_id int current
   */
  public function display_view($pID=''){
    global $page;
    $customer_id=$page->the_var('customer_id');
    $this->load_db_values($customer_id);
    self::$account = $page->_call('customer','the_customer');
    self::$adress_book=$this->cInfo->adress_book;
    self::$count=$this->cInfo->the_count;

    return new objectInfo(array('title'=>__("Carnet d'adresses personnel"),'content'=> tep_output_string_protected(tep_get_include_contents(__CLASS__.'.'.__FUNCTION__),false,true) ) );
  }


  /**
   * \brief select function for display
   */
  public function display_view_form(){
    global $page,$language, $navigation,$entry;

    $customer_id=$page->the_var('customer_id');
    $this->load_db_values($customer_id);
    self::$account = $page->_call('customer','the_customer');

    if (isset($_GET['edit'])) $entry=(!isset($_POST['firstname']))? $this->cInfo->adress_book[$_GET['edit']] : $_POST;
    elseif(isset($_POST['firstname']))$entry= $_POST;

    if (isset($_GET['delete'])) $s= self::form_delete();
    else $s= self::form_edit();

    return new objectInfo(array('title'=>self::$display_view_form_title,'content'=>tep_output_string_protected($s,false,true))) ;
  }

  /**
   * \brief Form delete entry address book
   */
  private static function form_delete(){
    self::$display_view_form_title=__('HEADING_TITLE_DELETE_ENTRY');
    return tep_get_include_contents(__CLASS__.'.'.__FUNCTION__);
  }


  /**
   * \brief Form add/edit entry address book
   */
  private static function form_edit(){
    if (isset($_GET['edit'])) self::$display_view_form_title=__('HEADING_TITLE_MODIFY_ENTRY');
    else  self::$display_view_form_title=__('HEADING_TITLE_ADD_ENTRY');

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

/** implements InterfaceModule depend */
  public function check() {}
  public function install() {}
  public function remove() {}
  public function keys() {}
}

?>