<?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  15/05/11, 11:45
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class orders
  @brief manage orders, listing and edit status
*/



error_reporting(E_ALL);

class orders
  extends ModTwo /// new abstract class for nextgen module
    implements
	    InterfaceModule,
	    IntModTwo, /// new interface module for nextgen module
	    InterfacedInnerHtml {

  /**
    @param const
  */
  const FILENAME = FILENAME_ORDERS;

  /**
    @param array list, utilisé dans les gabarits, list des orders
  */
  public static $list=array();
  /**
    @param object $order
  */
  public static $order;
  /**
    @param int Id order
  */
  public static $oID;
  /**
    @param bool $update autorise mise a jour status
  */
  public static $update;
  /**
    @param array $orders_status_array
  */
  public static $orders_status_array=array();
  /**
    @param array $orders_statuses
  */
  public static $orders_statuses=array();
  /**
    @param object $oInfo
  */
  public static $oInfo;
  /**
    @param object $export
  */
  public static $export;



  /**
    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' );
    self::$oID=(isset($_REQUEST['oID'])? $_REQUEST['oID'] : '' );


// var_dump(self::$action);
    self::$export= new export(__CLASS__);

    /**
      @remarks define var execution  sql in GetDBValue()
    */
    self::$InitInfo['adjust']=array(
			  'languages_id'=>$languages_id,
			  'page'=>1,
			  'rowbyp'=>10,
			  'sOrder'=>'',
			  'sWhere'=>'',
			  );



    /**
      @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.
			      (isset(parent::$action)?'&action='.parent::$action : '' ).
			      (isset(self::$oID)?'&oID='.self::$oID : '' )
			    );

    //! detail item in ajax
    define('AJAXSTATMENTDETAIL', 'mod=page&type='.self::$code);


    /**
      @remarks this define col theader title, and ajust html code
	Just for Edit listing
    */
    self::$InitInfo['theader']['listing']=array(
      0 =>array('width'=>'2%', 'class'=>'tcenter', 'txt'=>'&nbsp;' ),
      1 =>array('width'=>'2%', 'class'=>'tcenter', 'txt'=>'&nbsp;' ),
      2 =>array('width'=>'8%', 'class'=>'tcenter', 'txt'=>__('table heading order id') ),
      3 =>array('width'=>'40%','class'=>'tcenter', 'txt'=>__('table heading customers')),
      4 =>array('width'=>'150px','class'=>'tcenter', 'txt'=>__('table heading order total')),
      5 =>array('width'=>'10%', 'txt'=>__('table heading date purchased')),
      6 =>array('width'=>'8%', 'txt'=>__('table heading status')),
      7 =>array('width'=>'10%', 'txt'=>__('table heading status')),
      8 =>array('width'=>'10%','class'=>'row_action', 'txt'=>__('table heading action')),
    );

    self::$InitInfo['tfooter']['listing']=array(
      0 =>array('width'=>'2%', 'class'=>'tcenter', 'txt'=>tep_draw_hidden_field('xx','xxx','','class="search_init" ') ),
      1 =>array('width'=>'2%', 'class'=>'tcenter', 'txt'=>tep_draw_hidden_field('xxx','xxx','','class="search_init" ') ),
      2 =>array('width'=>'8%', 'class'=>'tcenter', 'txt'=>tep_draw_input_field('o.orders_id','orders_id',__('table heading order id'),'style="width:98%" class="search_init"') ),
      3 =>array('width'=>'40%','class'=>'tcenter', 'txt'=>tep_draw_input_field('o.customers_name','customers_name',__('table heading customers'),'style="width:98%" class="search_init"') ),
      4 =>array('width'=>'150px','class'=>'tcenter', 'txt'=>tep_draw_input_field('ot.text','text',__('table heading order total'),'style="width:98%" class="search_init"') ),
      5 =>array('width'=>'10%', 'txt'=>tep_draw_input_field('o.date_purchased','date_purchased',__('table heading date purchased'),'style="width:98%" class="search_init"')),
      6 =>array('width'=>'8%', 'txt'=>tep_draw_input_field('o.payment_method','payment_method',__('table heading status'),'style="width:98%" class="search_init"')),
      7 =>array('width'=>'10%', 'txt'=>tep_draw_input_field('s.status_name','status_name',__('table heading status'),'style="width:98%" class="search_init"')),
      8 =>array('width'=>'10%','class'=>'row_action', 'txt'=>'&nbsp;'),
    );

    /**
      @remarks this define col in table, and if is possible sort
	Just for Edit listing
    */
    self::$InitInfo['modele']['listing']=array(
	0 =>false,
	1 =>false,
	'orders_id'=>true,
	'customers_id'=>true,
	'order_total'=>true,
	'date_purchased'=>true,
	'payment_method'=>true,
	'orders_status_name'=>true,
	'action' =>false
    );



    /**
      @remarks this define menu master module in page
    */
//     if(self::$action =='' || self::$action =='listing')
//     self::$InitInfo['MenuModule'][]=array(
// 					'type'=>'getLink',
// 					'format'=>'button_nav',
// 					'image'=>'',
// 					'cssclass'=>'',
// 					'title'=>__('image inventaire add'),
// 					'url'=>tep_href_link(self::FILENAME,  'action=new'),
// 					);




    $DB=Database::getInstance();
    self::$orders_statuses=array();
    $orders_status_query = $DB->query("select status_id, status_name from " . TABLE_STATUS . " where status_type='orders' and language_id = '" . (int)$languages_id . "'");
    while ($orders_status = $orders_status_query->fetchAssoc()) {
      self::$orders_statuses[] = array('id' => $orders_status['status_id'], 'text' => $orders_status['status_name']);
      self::$orders_status_array[$orders_status['status_id']] = $orders_status['status_name'];
    }


    return true;
  }


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

    self::$action=$actions;

    switch (self::$action) {
    case 'multiconfirm':
        $res=array();
        /**
          @remarks Action mutliple
        */




        $status = tep_db_prepare_input(@$_POST['status_multi']);
// 	$modeexport = tep_db_prepare_input(@$_POST['modeexport']);
        $notify_comments = (isset($_POST['notify_comments'])) ? tep_db_prepare_input($_POST['notify_comments']) : '';
        $notify =(isset($_POST['notify'])) ? tep_db_prepare_input($_POST['notify']): '';
        $comments= (isset($_POST['comments'])) ? tep_db_prepare_input($_POST['comments']) :'';
        if(isset($_POST['action_multi']) && is_array($_POST['action_multi']) ) {

	    if(isset($_POST['status_multi'])){
	      foreach($_POST['action_multi'] as $oID )
		if (up_status_order($oID, array('status'=>$status,'comments'=>'', 'notify'=>$notify, 'notify_comments'=>$notify_comments , 'comments'=> $comments)  ) ) $res[]=true;
		else $res[]=false;
	    }


	    if(isset($_POST['modeexport'])){

	      $modeexport=tep_db_prepare_input($_POST['modeexport']);
	      $encodage=tep_db_prepare_input($_POST['encodage']);
	      $export_type=tep_db_prepare_input($_POST['export_type']);
	      $od=array();

	      self::$export->pre_export(array( 'mode' => $modeexport, 'encodage'=>$encodage, 'export_type'=>$export_type, 'page_admin'=>$page_module));

	      foreach($_POST['action_multi'] as $oID ){

		$order = new order((int)$oID);
		$qer=tep_db_query("SELECT countries_iso_code_2 FROM  " . TABLE_COUNTRIES . " WHERE countries_name='".$order->customer['country']."' ");
		$c=tep_db_fetch_array($qer);

		$od[]=array('IDExpedition'=>$oID,
			    'IDCustomer'=>$order->customer['id'],
			    'Namecustomer'=>self::$export->decodage($order->customer['name']),
			    'Compagnycustomer'=>self::$export->decodage($order->customer['company']),
			    'Streetadress'=>self::$export->decodage($order->delivery['street_address']),
			    'Streetadress2'=>self::$export->decodage($order->delivery['suburb']) ,
			    'Cityshipping'=>self::$export->decodage($order->delivery['city']),
			    'Stateshipping'=>self::$export->decodage($order->customer['state']) ,
			    'telephone'=>self::$export->decodage($order->customer['telephone']),
			    'postcode'=>self::$export->decodage($order->delivery['postcode']),
			    'codecountryiso'=>$c['countries_iso_code_2'],
			    'weight'=>round($order->info['total_weight'],3),
			    'Contreremb'=>'');
	      }

	      print self::$export->op_export($od);
	    }
        }

        if (in_array(false,$res))  $messageStack->add_session(__('success order updated'), 'success');
        else  $messageStack->add_session(__('warning order not updated'), 'warning');

        tep_redirect(tep_href_link(self::FILENAME));
      break;
      case 'update_order':
	$oID=(int)$_GET['oID'];
        if (up_status_order($oID, $_POST) )  $messageStack->add_session(__('success order updated'), 'success');
        else  $messageStack->add_session(__('warning order not updated'), 'warning');

        tep_redirect(tep_href_link(self::FILENAME,  'oID='.$oID.'&action=edit'));
      break;

      case 'deleteconfirm':
	$oID=(int)$_GET['oID'];
        delete_order($oID);
        tep_redirect(tep_href_link(self::FILENAME));
      break;

   }

    return self::$action;
  }

  public function get_header(){
    if (self::$action == 'edit'): ?>
    <script type="text/javascript"><!--
    function disabled(inputs){$(inputs).css.display='none';}
    function activ(inputs){$(inputs).css.display='inline';}
    $(function() {disabled('#cont_comments');});
    //--></script>
    <?php endif;
  }

  /**
    @fn Inventaire::GetDBValue();
    @brief return DB value adapted for current action
      Use self::action for determine switch
    @return
  */
  public static function GetDBValue(){
    global $languages_id;
    $arg=func_get_arg();

    $DB=Database::getInstance();
    $res=array();

// var_dump(self::$action);
    switch (self::$action) {
      case 'export';
      break;


      case 'listing';
	/**
	  @remarks retrun object load one inventaire
	*/
	global $query_numrows;
	$adjust=new objectInfo(self::$InitInfo['adjust']);


	if(tep_not_null($adjust->sWhere)){
	  $adjust->sWhere=str_replace(array('orders_id',
				    'order_total',
				    'customers_id',
				    'orders_status_name'),
			      array('o.orders_id',
				    ' ot.text',
				    'o.customers_name',
				    's.status_name'),
		  $adjust->sWhere);
	}

	$query_raw = "select distinct o.orders_id,o.orders_prefix, o.customers_id, o.customers_name, o.payment_method, o.date_purchased, o.last_modified, o.currency, o.currency_value, s.status_name as orders_status_name, s.status_color as orders_status_color, ot.text as order_total from " . TABLE_ORDERS . " o left join " . TABLE_ORDERS_TOTAL . " ot on (o.orders_id = ot.orders_id), " . TABLE_STATUS . " s where o.orders_status = s.status_id  and s.status_type='orders' and s.language_id = '" . (int)$adjust->languages_id . "' and ot.class = 'ot_total' ".$adjust->sWhere." order by  ".((!empty($adjust->sOrder)) ? $adjust->sOrder : 'o.orders_id DESC');

	$_split = new splitPageResults($adjust->page, $adjust->rowbyp,  $query_raw, $query_numrows);
	$_query = $DB->query($query_raw);

	$res=self::FormatDBValue($_query);

	return $res;
      break;

      case 'delete';
      default:

// 	$ID = tep_db_prepare_input($ID);
	$orders_query_raw = "select distinct o.orders_id,o.orders_prefix,  o.customers_id,o.customers_name,  o.payment_method, o.date_purchased, o.last_modified, o.currency, o.currency_value, s.status_name as orders_status_name, s.status_color as orders_status_color,ot.text as order_total from " . TABLE_ORDERS . " o left join " . TABLE_ORDERS_TOTAL . " ot on (o.orders_id = ot.orders_id), " . TABLE_STATUS . " s where o.orders_status = s.status_id and s.status_type='orders'  and s.language_id = '" . (int)$languages_id . "' and ot.class = 'ot_total' and o.orders_id='".self::$oID."' ";

	$currency_query = $DB->query($orders_query_raw);

	return new objectInfo($currency_query->fetchAssoc() );

    }
  }




  public function display_view(){
    switch (self::$action) {
      case 'delete':
	if(self::test_oID((int)self::$oID)) {
	  self::$oInfo=self::GetDBValue();
	  return MGabCont::CallGab(parent::$action,__FUNCTION__,__CLASS__); //tep_get_include_contents(self::$code.'.delete');
	}
      break;
      case 'multi':
	return MGabCont::CallGab(parent::$action,__FUNCTION__,__CLASS__); //tep_get_include_contents(self::$code.'.multi');
      break;
      case 'edit':
	if(self::test_oID((int)self::$oID)) {
	  self::$order= new order(self::$oID);
	  return MGabCont::CallGab(parent::$action,__FUNCTION__,__CLASS__); //tep_get_include_contents(self::$code.'.edit');
	}
      break;
      default:
	self::load_db_values();
	/// use master gabarit
	MGabCont::SetCurrentName(__CLASS__);
	return MGabCont::CallGab('listing',__FUNCTION__,self::MASTER);
    }
  }



/** Iterne public module */



  public static function load_status_history($oID){
//     self::init();
    $list=array();
    $DB=Database::getInstance();
    $orders_history_query = $DB->query("select orders_status_id, date_added, customer_notified, comments from " . TABLE_ORDERS_STATUS_HISTORY . " where orders_id = '" . tep_db_input($oID) . "' order by date_added");
    if ($orders_history_query->__get('numRows')) {
      while ($orders_history = $orders_history_query->fetchAssoc()) {
	self::$update=(DEFAULT_ORDERS_STATUS_COMPLETED== $orders_history['orders_status_id'])? false : true;

	$li['date_added']=tep_datetime_short($orders_history['date_added']);
	$li['customer_notified']=(($orders_history['customer_notified'] == '1')? tep_image(DIR_WS_ICONS . 'tick.gif', ICON_TICK) :tep_image(DIR_WS_ICONS . 'cross.gif', ICON_CROSS) ) ;
	$li['orders_status']=self::$orders_status_array[$orders_history['orders_status_id']];
	$li['comments']=nl2br(tep_db_output($orders_history['comments'])) ;
	$list[]=$li;
// 	echo '<tr>' . "\n" .
// 	    '<td colspan="5">' . __('text no order history') . '</td>' . "\n" .
// 	    '</tr>' . "\n";
      }
      return $list;
    }
    return false;
  }





  /**
    @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($orders){
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  '' ,
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME, 'oID=' . $orders['oID'] . '&amp;action=edit') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME, 'oID=' . $orders['oID'] . '&amp;action=delete') ,'' )
		);
  }

  /**
    @brief load listing array, for use format retrun by JSON
  */
  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){

    /// @remarks force load conf
    self::GetConf();

    $res=array();

    /**
      @remarks adjust param for sql requete
    */
    self::$InitInfo['adjust']['page']=$page;
    self::$InitInfo['adjust']['rowbyp']=$rowbyp;
    self::$InitInfo['adjust']['sOrder']=$sOrder;
    self::$InitInfo['adjust']['sWhere']=$sWhere;
    self::$InitInfo['adjust']['options']=$options;

    $res = self::load_db_values();

    return  self::$list=self::CheckResult($res);
  }


  /**
    @brief Redefine Parent method
  */
  public static function DTFootTable($mutli=false){
    /**
      @remarks mutli action specific line
    */
    if($mutli) {
      $col=count(self::DTheaderTable());
      return array(
		  0 => self::$InitInfo['tfooter']['listing'] ,
		  1 =>array( array('colspan'=>$col, 'class'=>'tleft', 'txt'=>'<span class="fleft">'.__('action multiple') . ' ' . tep_draw_pull_down_menu('status_multi', array_merge(array(array('id' => '', 'text' => __('text action multiple orders'))), orders::$orders_statuses) ) . __('export: ') . tep_draw_pull_down_menu('modeexport', orders::$export->mode ).'</span> <span class="fleft" style="margin-left:50px;"> '. tep_image_submit('button_confirm.gif', IMAGE_CONFIRM, '' ).'</span>' ) )
	      ) ;
    }
    else
    /**
      @remarks No tfoot specific,use equal theader
    */
      return array( 0 =>self::DTheaderTable());
  }

  /**
    @brief format db value for display page
    @param $_query ressource db sql
    @return array
  */
  private static function FormatDBValue($_query){
    $DB=Database::getInstance();
    $res=array();

    switch (parent::$action) {
      case 'listing':
	while ($orders = $_query->fetchAssoc()) {
	    $ord['oID']=$orders['orders_id'];
	    $ord['orders_id']=$orders['orders_prefix'].$orders['orders_id'];
	    $ord['customers_id']=tep_customers_row_action($orders['customers_id'], array('origin'=>self::FILENAME));
	    $ord['order_total']=strip_tags($orders['order_total']);
	    $ord['date_purchased']=tep_datetime_short($orders['date_purchased']);
	    $ord['payment_method']=$orders['payment_method'];
	    $ord['orders_status_name']='<span style="display:inline-block; width:100%;padding:3px 0;background:'.$orders['orders_status_color'].'" >'.$orders['orders_status_name'].'</span>';
	    $ord[0]=$orders['orders_id'];
	    $ord[1]=tep_draw_checkbox_field('action_multi['.$orders['orders_id'].']','action_mutli_'.$orders['orders_id'],$orders['orders_id']);
	    $ord['action']=self::get_item_action($ord);
	    $res[]=$ord;
	}
      break;
    }

    return $res;
  }


 /** static InterfacedInnerHtml */

  public static function detail_row_page($id){
    self::$list=self::load_status_history($id);
    return tep_get_include_contents(__CLASS__.'.inline');
  }


/** Interne module  */
  private static function test_oID($oID){
    global $messageStack;
    $_oID = tep_db_prepare_input($oID);
    $DB=Database::getInstance();

    $orders_query = $DB->query("select orders_id from " . TABLE_ORDERS . " where orders_id = '" . (int)$_oID . "'");
    $order_exists = true;
    if (!$orders_query->__get('numRows')) {
      $order_exists = false;
      $messageStack->add(sprintf(__('error order does not exist'), $_oID), 'error');
    }


    return $order_exists;
  }


  /**
    @brief return Filename
  */
  public static function GetFILENAME(){
    return self::FILENAME;
  }

  /**
    @depend InterfaceModule
  */
  function check() { return false; }
  function install() { return false; }
  function remove() { return false;  }
  function keys() { return false; }
}

?>