<?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  21/04/11, 09:17
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8

  @class held_orders
*/

require_once(dirname(__FILE__).'/orders.php');

class held_orders
  extends orders
  implements ExtModPage, InterfacedTJsonS, InterfacedInnerHtml {

  const FILENAME = FILENAME_HELD_ORDERS;
  /**
    @param string nom de la class
  */
  public static $code;
  /**
    @param string action retour GET
  */
  public static $action;
  /**
    @param array
  */
  public static $list=array();
  /**
    @param object detail commande , retour object class 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;


  /**
    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 format, precise les GET necessaire
    define('JSONSTATMENT', 'mod=page&type='.self::$code);
    //! detail item in ajax
    define('AJAXSTATMENTDETAIL', 'mod=page&type='.self::$code);

    global $language;
    $oscss=oscss_cstr::getInstance();
    $oscss->pile_file_lang(DIR_FS_ADMIN.DIR_WS_LANGUAGES.$language.'/modules/pages/orders.txt');

  }

  public function check_action($actions){
    global $messageStack;
    self::$action=$actions;
    $DB=Database::getInstance();
    switch (self::$action) {
    case 'multi':
        $res=array();
        /**
          Action mutliple
        */
        $status = tep_db_prepare_input(@$_POST['status_multi']);
        $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 (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 = tep_db_prepare_input($_GET['oID']);
      $status = tep_db_prepare_input($_POST['status']);
      $comments = tep_db_prepare_input($_POST['comments']);

      $order_updated = false;
      $check_status_query = $DB->query("select customers_name, customers_email_address, orders_status, date_purchased, ip_address from " . TABLE_HOLDING_ORDERS . " where orders_id = '" . (int)$oID . "'");
      $check_status = $check_status_query->fetchAssoc();
      if ($check_status['orders_status'] != $status || tep_not_null($comments)) {
        $DB->query("update " . TABLE_HOLDING_ORDERS . " set orders_status = '" . tep_db_input($status) . "', last_modified = now() where orders_id = '" . (int)$oID . "'");

         $customer_notified = '0';
          if (isset($_POST['notify']) && ($_POST['notify'] == 'on')) {
            $notify_comments = '';
            if (isset($_POST['notify_comments']) && ($_POST['notify_comments'] == 'on')) {
              $notify_comments = sprintf(EMAIL_TEXT_COMMENTS_UPDATE, $comments) . "\n\n";
            }

          $myarray = array(
                    'email_use_html'=>(($_POST['p_format'] == 'HTML')?true:false),
                    'mail_sent_to'=>$mail_sent_to,
                    'from'=>$from,
		    '_oID'=>$oID,
		    '_oLinks'=>tep_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $oID, 'SSL') ,
		    'date_purchased'=>tep_date_long($check_status['date_purchased']),
		    'notify_comments'=>$notify_comments,
		    '_ostatus'=>$orders_status_array[$status],
                    'subject'=>$subject,
                    'message'=>$content
                    );

          $message_final=tep_post_prepare_email("held_orders.tpl",$language,$myarray);

          if (  tep_mail($check_status['customers_name'], $check_status['customers_email_address'], EMAIL_TEXT_SUBJECT, $message_final, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS) !=false) $err=true;
          else $err=false;
        }

        if(!$err) $DB->query("insert into " . TABLE_HOLDING_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments) values ('" . (int)$oID . "', '" . tep_db_input($status) . "', now(), '" . $customer_notified . "', '" . tep_db_input($comments)  . "')");

        $order_updated = true;
      }

      if ($order_updated) {
       $messageStack->add_session(SUCCESS_ORDER_UPDATED, 'success');
      } else {
        $messageStack->add_session(WARNING_ORDER_NOT_UPDATED, 'warning');
      }

      tep_redirect(tep_href_link(self::FILENAME, tep_get_all_get_params(array('action')) . 'action=edit'));
    break;

    case 'confirm_order':
      $oID = tep_db_prepare_input($_GET['oID']);

      tep_confirm_held_order($oID);

      $messageStack->add_session(__('success held order updated'), 'success');

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

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

      $DB->query("delete from " . TABLE_HOLDING_ORDERS . " where orders_id = '" . $oID . "'");
      $DB->query("delete from " . TABLE_HOLDING_ORDERS_PRODUCTS . " where orders_id = '" . $oID . "'");
      $DB->query("delete from " . TABLE_HOLDING_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_id = '" . $oID . "'");
      $DB->query("delete from " . TABLE_HOLDING_ORDERS_STATUS_HISTORY . " where orders_id = '" . $oID . "'");
      $DB->query("delete from " . TABLE_HOLDING_ORDERS_TOTAL . " where orders_id = '" . $oID . "'");

      tep_redirect(tep_href_link(self::FILENAME, tep_get_all_get_params(array('oID', 'action'))));
    break;

   }

    return self::$action;
  }

  public function get_header(){ return false;  }

  public static function load_db_values($ID){
    global $languages_id;
    $DB=Database::getInstance();
    $ID = tep_db_prepare_input($ID);
    $orders_query_raw = "select distinct o.orders_id,  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_HOLDING_ORDERS . " o left join " . TABLE_HOLDING_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='".$ID."' ";

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

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

  public function display_view(){
    $action=self::$action;
    switch (self::$action) {
      case 'delete':
	self::$oInfo=self::load_db_values((int)$_GET['oID']);
      break;
      case 'recup_order':
	self::$oInfo=self::load_db_values((int)$_GET['oID']);
      break;
      default:
	self::tep_get_list();
	$action='listing';
    }

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



/** Iterne public module */


 /** static InterfacedTJsonS */


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

  private static function get_item_action($orders){
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  '' ,
		  sprintf(CsrtAction::getLink('row_action_right',  __('image recup help order'), 'recup_order'), '',  tep_href_link(self::FILENAME,  'oID=' . $orders['oID'] . '&amp;action=new_product') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME,  'oID=' . $orders['oID'] . '&amp;action=delete') ,'' )
	      );
  }


  public static function tep_get_modele(){
    return array(  0 =>false,
		  'null' =>false,
		  'orders_id' =>true,
                  'customers_id'=>true,
                  'order_total'=>true,
		  'date_purchased'=>true,
		  'payment_method'=>true,
                  'orders_status_name'=>true,
		  'action' =>false
                );
  }

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

    $DB=Database::getInstance();

    if(tep_not_null($sWhere)){
      $sWhere=str_replace(array('orders_id'),array('o.orders_id'), $sWhere);
    }

    $query_raw = "select distinct o.ip_address, o.orders_id, o.customers_id,o.customers_name, o.customers_id, 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_HOLDING_ORDERS . " o left join " . TABLE_HOLDING_ORDERS_TOTAL . " ot on (o.orders_id = ot.orders_id), " . TABLE_STATUS . " s where o.orders_status = s.status_id and status_type='orders' and s.language_id = '" . $languages_id . "' and ot.class = 'ot_total'  ".$sWhere." order by  ".((!empty($sOrder)) ? $sOrder : 'o.orders_id DESC');

    $orders_split = new splitPageResults($page, $rowbyp, $query_raw, $query_numrows);
    $orders_query = $DB->query($query_raw);

    while ($orders = $orders_query->fetchAssoc()) {
      $ord['oID']=$orders['orders_id'];
      $ord['orders_id']=$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['null']=tep_draw_checkbox_field('action_multi['.$ord['oID'].']','action_mutli_'.$ord['oID'],$ord['orders_id']);
      $ord['action']=self::get_item_action($ord);
      self::$list[]=$ord;
    }

    $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){
    include(DIR_WS_FUNCTIONS.'lib.orders.php');
    self::$order=new order((int)$id, 'HOLDING');

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

}

?>