<?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  13/03/11, 09:12
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class batch_print
*/

class batch_print
  implements ExtModPage, InterfaceModule {

  const FILENAME = FILENAME_BATCH_PRINT;
  /**
  */
  public static $code;

  public static $action;
  /**
    @param array $list
  */
  public static $list=array();
  /**
    @param array $orders_statuses
  */
  public static $orders_statuses=array();
  /**
    @param array $file_type_array
  */
  public static $file_type_array=array();

  /**
    class constructor
  */
  public function __construct() {
    self::$code=__CLASS__;

    osCSS_pdf::getInstance();

    self::$orders_statuses = array_merge(tep_get_status_array('orders'),array(array('id'=>'','text'=>TEXT_NONE)));
    self::$file_type_array= osCSS_pdf::get_module();
  }

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

    $DB=Database::getInstance();

    self::$action=$actions;

  $pageloop = "0";
  if (isset($_GET['mkey'])) $action = 'erreur';

  switch (self::$action) {
    case 'exe':
    // check if invoice number is a empty field .. if its not empty do this ..
    // if it is empty skip down to the check date entered code.
    if (isset($_POST['invoicenumbers']) && tep_not_null($_POST['invoicenumbers']) || isset($_GET['oID']) && tep_not_null($_GET['oID'])) {
       $invoicenumbers =(!empty($_POST['invoicenumbers'])) ? $_POST['invoicenumbers'] : $_GET['oID'];
       $time0   = time();
      $invoicenumbers = tep_db_prepare_input($invoicenumbers);
      $arr_no = explode(',',$invoicenumbers);
      foreach ($arr_no as $key=>$value) {
        $arr_no[$key]=trim($value);
        if (substr_count($arr_no[$key],'-')>0) {
          $temp_range=explode('-',$arr_no[$key]);
          $arr_no[$key]=implode(',',range((int) $temp_range[0], (int) $temp_range[1]));
        }
      }
      $invoicenumbers=implode(',',$arr_no);

       $type=(isset($_GET['file_type'])) ? $_GET['file_type'] : $_POST['file_type'] ;
    } else {

      try{
	if (!isset($_POST['startdate'])) throw new Exception(__("precise date start"));
	$_POST['startdate']= tep_date_raw($_POST['startdate']);
	if ((strlen($_POST['startdate']) != 10) || self::verify_start_date($_POST['startdate']))throw new Exception(__("error bad date"));

	if (!isset($_POST['enddate'])) throw new Exception(__("precise date end"));
	$_POST['enddate']= tep_date_raw($_POST['enddate']);
	if ((strlen($_POST['enddate']) != 10) || self::verify_start_date($_POST['enddate']))throw new Exception(__("error bad date"));

	if (!is_writeable(BATCH_PDF_DIR)) throw new Exception(__("set permissions"));
      }catch(Exception $e){
	$messageStack->add_session($e->getMessage(), 'error');
	tep_redirect(tep_href_link(self::FILENAME));
      }


      $time0   = time();
      $startdate = tep_db_prepare_input($_POST['startdate']);
      $time0   = time();
      $enddate = tep_db_prepare_input($_POST['enddate']);
      $type=$_POST['file_type'];
    }

    $pdf=osCSS_pdf::OutputInit($type);
    $pageloop = "1";

    $get_customer_comments = (isset($_POST['show_comments']))? ' and h.orders_status_id = ' . DEFAULT_ORDERS_STATUS_ID : '' ;
    $pull_w_status =(isset($_POST['pull_status']) && tep_not_null($_POST['pull_status']))? " and o.orders_status = ". $_POST['pull_status']:'';

    // if there is a invoice number use first order query otherwise use second date style order query
    if ($invoicenumbers != '')  $orders_query = tep_db_query("select o.orders_id,o.orders_status,h.comments,MIN(h.date_added) from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_STATUS_HISTORY . " h where o.orders_id in (" . tep_db_input($invoicenumbers) . ") and h.orders_id = o.orders_id" . $pull_w_status . $get_customer_comments . ' group by o.orders_id');
    else  $orders_query = tep_db_query("select o.orders_id,o.orders_status,h.comments,MIN(h.date_added) from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_STATUS_HISTORY . " h where o.date_purchased between '" . tep_db_input($startdate) . "' and '" . tep_db_input($enddate) . " 23:59:59'  and h.orders_id = o.orders_id" . $pull_w_status . $get_customer_comments . ' group by o.orders_id');

    if (!tep_db_num_rows($orders_query) > 0) message_handler('FAILED_TO_OPEN');

    while ($orders = tep_db_fetch_array($orders_query)) {
      $order = new order($orders['orders_id']);

      osCSS_pdf::OutputAddPage();

      include(osCSS_pdf::getPathModele());

      $time1  = time();
      if ($time1 >= $time0 + 30) {
        $time0 = $time1;
        header('X-bpPing: Pong');
      }
    }

    $pdf=osCSS_pdf::OutputEnd($type);

    /* Succes */
//      $messageStack->add_session('A PDF of ' . $num . ' record(s) was successful! <a href="'.$fname.'" target="_blank"><b>Click here</b></a> to download the order file.', 'info');
 }


    return self::$action;
  }

  public function get_header(){
    ?>
      <script type="text/javascript"><!--
      var tax_rates = new Array();
      $(function() {
	$.datepicker.setDefaults($.extend({
	  duration: '',
	  changeMonth: true,
	  changeYear: true,
	  showOn: 'button',
	  buttonImage: '<?php echo DIR_WS_ICONS . 'calendar.gif';?>',
	  buttonImageOnly: true
	}
      <?php if (($lng=language::LangueSelected())&&  $lng != 'en') echo ",\n"."$.datepicker.regional['".$lng."']"."\n";  ?>
	));
	$('#bt_startdate').datepicker({altField: '#startdate'});
	$('#bt_enddate').datepicker({altField: '#enddate'});
      });
      // -->
      </script>
    <?php
  }


  public static function load_db_values($ID){
  }

  public function display_view(){
    return tep_get_include_contents(self::$code.'.form');
  }



/** specifique private  methode */
  private static function verify_start_date($startdate) {
    $error = 0;
    list($year,$month,$day) = explode('-', $startdate);

    if ((strlen($year) != 4) || !is_numeric($year)) $error++;
    if ((strlen($month) != 2) || !is_numeric($month))  $error++;
    if ((strlen($day) != 2) || !is_numeric($day))  $error++;

    return $error;
  }

  private static function verify_end_date($enddate) {
    $error = 0;
    list($year,$month,$day) = explode('-', $enddate);

    if ((strlen($year) != 4) || !is_numeric($year)) $error++;
    if ((strlen($month) != 2) || !is_numeric($month))  $error++;
    if ((strlen($day) != 2) || !is_numeric($day))  $error++;

    return $error;
  }

/** Interface module */

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

?>