<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  \licence GPL 2005-2010  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/11/10, 21:37
  \author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  \encode UTF-8
  \class order
*/

class order {
  var $info, $totals, $products, $customer, $delivery, $content_type,$coupon;

  /**
    @a array  tableau de table
  */
  private static $tables;

  /**
    @a bool Mode (orders=true | holding_order=false)
  */
  private static $mode;

  /**
   * \fn order($order_id = '', $table = '')
   * @param $order_id int
   * @param $table string
  */
  function order($order_id = '', $table = '') {
    $this->info = array();
    $this->totals = array();
    $this->products = array();
    $this->customer = array();
    $this->delivery = array();

    if (tep_not_null($order_id) && is_numeric($order_id)) {

      self::$mode=(tep_not_null($table)?false:true);

      $table=((!self::$mode)? '_'.strtoupper($table) : '');

      self::$tables=array( 'ORDERS'=>constant('TABLE'.$table.'_ORDERS'),
			   'TOTAL'=>constant('TABLE'.$table.'_ORDERS_TOTAL'),
			   'PRODUCTS'=>constant('TABLE'.$table.'_ORDERS_PRODUCTS'),
			   'ATTRIBUTES'=>constant('TABLE'.$table.'_ORDERS_PRODUCTS_ATTRIBUTES'),
			  );
      $this->query($order_id);
    } else {
      link_post_variable('cc_type');
      link_post_variable('cc_owner');
      link_post_variable('cc_number');
      link_post_variable('cc_expires');
      link_post_variable('comments');
      $this->cart();
    }


  }

  /**
   * \fn query($order_id)
   * \brief Recuperation d'un command enregsitré
   * @param $order_id int
  */
  function query($order_id) {
    global $languages_id;

    $order_id = tep_db_prepare_input($order_id);

    $sql="select orders_id,orders_prefix,customers_id,customers_name, customers_company, customers_street_address, customers_suburb, customers_city, customers_postcode, customers_state, customers_country, o.customers_telephone, o.customers_email_address, customers_address_format_id, customers_group_name, delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, delivery_postcode, delivery_state, delivery_country, delivery_address_format_id, billing_name, billing_company, billing_street_address, billing_suburb, billing_city, billing_postcode, billing_state, billing_country, billing_address_format_id, payment_method, cc_type, cc_owner, cc_number, cc_expires, currency, currency_value, date_purchased, orders_status, last_modified,ip_address, total_weight,orders_date_finished ".((self::$mode)?" ,facture_id ,holding_origin_id ":'')." from " . self::$tables['ORDERS'] . " o left join " . TABLE_CUSTOMERS . " using(customers_id) left join " . TABLE_CUSTOMERS_GROUPS . " using(customers_group_id) where orders_id = '" . (int)$order_id . "'";

    $order_query = tep_db_query($sql);
    $order = tep_db_fetch_array($order_query);

    $totals_query = tep_db_query("select title, text from " . self::$tables['TOTAL'] . " where orders_id = '" . (int)$order_id . "' order by sort_order");
    while ($totals = tep_db_fetch_array($totals_query)) {
      $this->totals[] = array('title' => $totals['title'],
			      'text' => $totals['text']);
    }

    $order_total_query = tep_db_query("select text from " . self::$tables['TOTAL'] . " where orders_id = '" . (int)$order_id . "' and class = 'ot_total'");
    $order_total = tep_db_fetch_array($order_total_query);

    $shipping_method_query = tep_db_query("select title from " . self::$tables['TOTAL'] . " where orders_id = '" . (int)$order_id . "' and class = 'ot_shipping'");
    $shipping_method = tep_db_fetch_array($shipping_method_query);

    $order_status_query = tep_db_query("select status_id, status_name as orders_status_name from " . TABLE_STATUS . " where status_type='orders' and status_id = '" . $order['orders_status'] . "' and language_id = '" . (int)$languages_id . "'");
    $order_status = tep_db_fetch_array($order_status_query);

    $this->info = array('orders_id' => $order['orders_id'],
			'orders_prefix' => $order['orders_prefix'],
			'currency' => $order['currency'],
			'currency_value' => $order['currency_value'],
			'payment_method' => $order['payment_method'],
			'cc_type' => $order['cc_type'],
			'cc_owner' => $order['cc_owner'],
			'cc_number' => $order['cc_number'],
			'cc_expires' => $order['cc_expires'],
			'date_purchased' => $order['date_purchased'],
			'orders_status' => $order_status['orders_status_name'],
			'orders_status_id' => $order_status['status_id'],
			'last_modified' => $order['last_modified'],
			'total' => strip_tags($order_total['text']),
			'shipping_method' => ((substr($shipping_method['title'], -1) == ':') ? substr(strip_tags($shipping_method['title']), 0, -1) : strip_tags($shipping_method['title'])),
			'ip_address'=>$order['ip_address'],
			'total_weight'=>$order['total_weight'],
			'date_finish'=>$order['orders_date_finished'],
		      );
    if(self::$mode) {
      $this->info['facture_id']=$order['facture_id'];
      $this->info['holding_origin_id']=$order['holding_origin_id'];
    }

    $this->customer = array('id' => $order['customers_id'],
			    'name' => $order['customers_name'],
			    'company' => $order['customers_company'],
			    'street_address' => $order['customers_street_address'],
			    'suburb' => $order['customers_suburb'],
			    'city' => $order['customers_city'],
			    'postcode' => $order['customers_postcode'],
			    'state' => $order['customers_state'],
			    'country' => $order['customers_country'],
			    'format_id' => $order['customers_address_format_id'],
			    'customers_group_name' => $order['customers_group_name'],
			    'telephone' => $order['customers_telephone'],
			    'email_address' => $order['customers_email_address']);

    $this->delivery = array('name' => $order['delivery_name'],
			    'company' => $order['delivery_company'],
			    'street_address' => $order['delivery_street_address'],
			    'suburb' => $order['delivery_suburb'],
			    'city' => $order['delivery_city'],
			    'postcode' => $order['delivery_postcode'],
			    'state' => $order['delivery_state'],
			    'country' => $order['delivery_country'],
			    'format_id' => $order['delivery_address_format_id']);

    if (empty($this->delivery['name']) && empty($this->delivery['street_address'])) {
      $this->delivery = false;
    }

    $this->billing = array('name' => $order['billing_name'],
			    'company' => $order['billing_company'],
			    'street_address' => $order['billing_street_address'],
			    'suburb' => $order['billing_suburb'],
			    'city' => $order['billing_city'],
			    'postcode' => $order['billing_postcode'],
			    'state' => $order['billing_state'],
			    'country' => $order['billing_country'],
			    'format_id' => $order['billing_address_format_id']);

    $index = 0;
    $orders_products_query = tep_db_query("select orders_products_id, products_id, products_name, products_model, products_price, products_tax, products_quantity, final_price, products_returned,products_exchanged,products_exchanged_id  from " .self::$tables['PRODUCTS'] . " where orders_id = '" . (int)$order_id . "'");

    while ($orders_products = tep_db_fetch_array($orders_products_query)) {
      $this->products[$index] = array('qty' => $orders_products['products_quantity'],
				      'id' => $orders_products['products_id'],
				      'name' => $orders_products['products_name'],
				      'model' => $orders_products['products_model'],
				      'tax' => $orders_products['products_tax'],
				      'price' => $orders_products['products_price'],
				      'final_price' => $orders_products['final_price'],
				      'id' => $orders_products['products_id'],
				      'return' => $orders_products['products_returned'],
				      'exchange' => $orders_products['products_exchanged'],
				      'exchange_id' => $orders_products['products_exchanged_id'] );

      $subindex = 0;
      $attributes_query = tep_db_query("select products_options, products_options_values, options_values_price, price_prefix from " .self::$tables['ATTRIBUTES'] . " where orders_id = '" . (int)$order_id . "' and orders_products_id = '" . (int)$orders_products['orders_products_id'] . "'");
      if (tep_db_num_rows($attributes_query)) {
	while ($attributes = tep_db_fetch_array($attributes_query)) {
	  $this->products[$index]['attributes'][$subindex] = array('option' => $attributes['products_options'],
								    'value' => $attributes['products_options_values'],
								    'prefix' => $attributes['price_prefix'],
								    'price' => $attributes['options_values_price']);

	  $subindex++;
	}
      }

      $shown_price= ($this->products[$index]['final_price'] * $this->products[$index]['qty']);

      $this->products[$index]['total_line'] 		= $shown_price;
      $this->products[$index]['total_line_taxe'] 	= tep_calculate_tax($shown_price, $this->products[$index]['tax']);
      $this->products[$index]['total_line_ttc']		= tep_add_tax($this->products[$index]['final_price'], $this->products[$index]['tax'])  * $this->products[$index]['qty'];

      $this->info['tax_groups']["{$this->products[$index]['tax']}"] = '1';

      $index++;
    }
  }

  function cart() {
    global $customer_id, $sendto, $billto, $cart, $languages_id, $currency, $currencies, $shipping, $payment,$tax_address,$coupon_sav;

    $this->content_type = $cart->get_content_type();

    $customer_address_query = tep_db_query("select c.customers_firstname, c.customers_lastname, c.customers_telephone, c.customers_email_address, ab.entry_company, ab.entry_street_address, ab.entry_suburb, ab.entry_postcode, ab.entry_city, ab.entry_zone_id, z.zone_name, co.countries_id, co.countries_name, co.countries_iso_code_2, co.countries_iso_code_3, co.address_format_id, ab.entry_state from " . TABLE_CUSTOMERS . " c, " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) left join " . TABLE_COUNTRIES . " co on (ab.entry_country_id = co.countries_id) where c.customers_id = '" . (int)$customer_id . "' and ab.customers_id = '" . (int)$customer_id . "' and c.customers_default_address_id = ab.address_book_id");
    $customer_address = tep_db_fetch_array($customer_address_query);

    $shipping_address_query = tep_db_query("select ab.entry_firstname, ab.entry_lastname, ab.entry_company, ab.entry_street_address, ab.entry_suburb, ab.entry_postcode, ab.entry_city, ab.entry_zone_id, z.zone_name, ab.entry_country_id, c.countries_id, c.countries_name, c.countries_iso_code_2, c.countries_iso_code_3, c.address_format_id, ab.entry_state from " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) left join " . TABLE_COUNTRIES . " c on (ab.entry_country_id = c.countries_id) where ab.customers_id = '" . (int)$customer_id . "' and ab.address_book_id = '" . (int)$sendto . "'");
    $shipping_address = tep_db_fetch_array($shipping_address_query);
// print_r($shipping_address);
    $billing_address_query = tep_db_query("select ab.entry_firstname, ab.entry_lastname, ab.entry_company, ab.entry_street_address, ab.entry_suburb, ab.entry_postcode, ab.entry_city, ab.entry_zone_id, z.zone_name, ab.entry_country_id, c.countries_id, c.countries_name, c.countries_iso_code_2, c.countries_iso_code_3, c.address_format_id, ab.entry_state from " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) left join " . TABLE_COUNTRIES . " c on (ab.entry_country_id = c.countries_id) where ab.customers_id = '" . (int)$customer_id . "' and ab.address_book_id = '" . (int)$billto . "'");
    $billing_address = tep_db_fetch_array($billing_address_query);

    $tax_address_query = tep_db_query("select ab.entry_country_id, ab.entry_zone_id from " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) where ab.customers_id = '" . (int)$customer_id . "' and ab.address_book_id = '" . (int)($this->content_type == 'virtual' ? $billto : $sendto) . "'");
    $tax_address = tep_db_fetch_array($tax_address_query);

    $this->info = array('order_status' => DEFAULT_ORDERS_STATUS_ID,
			'currency' => $currency,
			'currency_value' => $currencies->currencies[$currency]['value'],
			'payment_method' => $payment,
			'cc_type' => (isset($GLOBALS['cc_type']) ? $GLOBALS['cc_type'] : ''),
			'cc_owner' => (isset($GLOBALS['cc_owner']) ? $GLOBALS['cc_owner'] : ''),
			'cc_number' => (isset($GLOBALS['cc_number']) ? $GLOBALS['cc_number'] : ''),
			'cc_expires' => (isset($GLOBALS['cc_expires']) ? $GLOBALS['cc_expires'] : ''),
			'shipping_method' => $shipping['title'],
			'shipping_cost_ht' => (isset($shipping['cost_ht'])? $shipping['cost_ht']:0),
			'shipping_cost' => $shipping['cost'],
			'shipping_tax' => (isset($shipping['shipping_tax_total'])?$shipping['shipping_tax_total']:0),
			'subtotal_ht' => 0,
			'subtotal_taxe' => 0,
			'subtotal' => 0,
			'tax' => 0,
			'tax_groups' => array(),
			'total_weight' => 0,
			'comments' => (isset($GLOBALS['comments']) ? $GLOBALS['comments'] : ''));

    if (isset($GLOBALS[$payment]) && is_object($GLOBALS[$payment])) {
      $this->info['payment_method'] = $GLOBALS[$payment]->title;

      if ( isset($GLOBALS[$payment]->order_status) && is_numeric($GLOBALS[$payment]->order_status) && ($GLOBALS[$payment]->order_status > 0) ) {
	$this->info['order_status'] = $GLOBALS[$payment]->order_status;
      }
    }

    $this->customer = array('firstname' => $customer_address['customers_firstname'],
			    'lastname' => $customer_address['customers_lastname'],
			    'company' => $customer_address['entry_company'],
			    'street_address' => $customer_address['entry_street_address'],
			    'suburb' => $customer_address['entry_suburb'],
			    'city' => $customer_address['entry_city'],
			    'postcode' => $customer_address['entry_postcode'],
			    'state' => ((tep_not_null($customer_address['entry_state'])) ? $customer_address['entry_state'] : $customer_address['zone_name']),
			    'zone_id' => $customer_address['entry_zone_id'],
			    'country' => array('id' => $customer_address['countries_id'], 'title' => $customer_address['countries_name'], 'iso_code_2' => $customer_address['countries_iso_code_2'], 'iso_code_3' => $customer_address['countries_iso_code_3']),
			    'format_id' => $customer_address['address_format_id'],
			    'telephone' => $customer_address['customers_telephone'],
			    'email_address' => $customer_address['customers_email_address']);

    $this->delivery = array('firstname' => $shipping_address['entry_firstname'],
			    'lastname' => $shipping_address['entry_lastname'],
			    'company' => $shipping_address['entry_company'],
			    'street_address' => $shipping_address['entry_street_address'],
			    'suburb' => $shipping_address['entry_suburb'],
			    'city' => $shipping_address['entry_city'],
			    'postcode' => $shipping_address['entry_postcode'],
			    'state' => ((tep_not_null($shipping_address['entry_state'])) ? $shipping_address['entry_state'] : $shipping_address['zone_name']),
			    'zone_id' => $shipping_address['entry_zone_id'],
			    'country' => array('id' => $shipping_address['countries_id'], 'title' => $shipping_address['countries_name'], 'iso_code_2' => $shipping_address['countries_iso_code_2'], 'iso_code_3' => $shipping_address['countries_iso_code_3']),
			    'country_id' => $shipping_address['entry_country_id'],
			    'format_id' => $shipping_address['address_format_id']);

    $this->billing = array('firstname' => $billing_address['entry_firstname'],
			    'lastname' => $billing_address['entry_lastname'],
			    'company' => $billing_address['entry_company'],
			    'street_address' => $billing_address['entry_street_address'],
			    'suburb' => $billing_address['entry_suburb'],
			    'city' => $billing_address['entry_city'],
			    'postcode' => $billing_address['entry_postcode'],
			    'state' => ((tep_not_null($billing_address['entry_state'])) ? $billing_address['entry_state'] : $billing_address['zone_name']),
			    'zone_id' => $billing_address['entry_zone_id'],
			    'country' => array('id' => $billing_address['countries_id'], 'title' => $billing_address['countries_name'], 'iso_code_2' => $billing_address['countries_iso_code_2'], 'iso_code_3' => $billing_address['countries_iso_code_3']),
			    'country_id' => $billing_address['entry_country_id'],
			    'format_id' => $billing_address['address_format_id']);

    $index = 0;
    $products = $cart->get_products();

    if( tep_session_is_registered( 'coupon_sav' ) && tep_not_null( $coupon_sav ) ) {
      require_once( DIR_WS_CLASSES.'discount_coupon.php' );
      $this->coupon = new discount_coupon( $coupon_sav, $this->delivery );
      $this->coupon->total_valid_products( $products );
      $valid_products_count = 0;
    }


    foreach($products as $prdct){

      $this->products[$index] = array('qty' => $prdct['quantity'],
				      'name' => $prdct['name'],
				      'model' => $prdct['model'],

				      'tax' =>tep_get_tax_rate($prdct['tax_class_id'], $tax_address['entry_country_id'], $tax_address['entry_zone_id']),
				      'tax_description' => tep_get_tax_description($prdct['tax_class_id'], $tax_address['entry_country_id'], $tax_address['entry_zone_id']),

				      'price' => $prdct['final_price'],
				      'final_price' => $prdct['final_price'],
				      'final_price_ttc' => $prdct['final_price_ttc'],

				      'weight' => $prdct['weight'] ,
				      'id' => $prdct['id'],

				      'total_line' => $prdct['total_line'],
				      'total_line_taxe' => ($prdct['total_line_ttc'] -$prdct['total_line']),
				      'total_line_ttc' => $prdct['total_line_ttc'],
				      );

      if ($prdct['attributes']) {
	$subindex = 0;
	reset($prdct['attributes']);
	while (list($option, $value) = each($prdct['attributes'])) {
	  $attributes_query = tep_db_query("select popt.products_options_name, popt.products_options_track_stock, poval.products_options_values_name, pa.options_values_price, pa.price_prefix,pa.options_values_weight from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_OPTIONS_VALUES . " poval, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where pa.products_id = '" . (int)$prdct['id'] . "' and pa.options_id = '" . (int)$option . "' and pa.options_id = popt.products_options_id and pa.options_values_id = '" . (int)$value . "' and pa.options_values_id = poval.products_options_values_id and popt.language_id = '" . (int)$languages_id . "' and poval.language_id = '" . (int)$languages_id . "'");

	  $attributes = tep_db_fetch_array($attributes_query);
	  if(isset($prdct['attributes_values'][$option]) ) {
	  /* Specifique option type texte / file champ personnalisé par le client */
	    $attributes['products_options_values_name'] .= '('.$prdct['attributes_values'][$option].')';
	  }
	  $this->products[$index]['attributes'][$subindex] = array('option' => $attributes['products_options_name'],
								    'value' => $attributes['products_options_values_name'],
								    'option_id' => $option,
								    'value_id' => $value,
								    'prefix' => $attributes['price_prefix'],
								    'price' => $attributes['options_values_price'],
								    'track_stock' => $attributes['products_options_track_stock']);

	  $subindex++;
	}
      }

    /*
      Calcul des totaux pour la commande.
      Seul les "$this->products" doivent être utilsié pour le calcul
    */
      if( is_object( $this->coupon ) ) {
	$applied_discount = 0;
	$discount = $this->coupon->calculate_discount( $this->products[$index], $valid_products_count );
	if( $discount['applied_discount'] > 0 ) $valid_products_count++;
	$shown_price = $this->coupon->calculate_shown_price( $discount, $this->products[$index] );
	$shown_taxe = tep_calculate_tax($shown_price['shown_price'], $this->products[$index]['tax']);
	$this->products[$index]['total_line']		= $shown_price['shown_price'];
	$this->products[$index]['total_line_taxe']	= $shown_taxe;
	$this->products[$index]['total_line_ttc']	= tep_add_tax($shown_price['shown_price'], $this->products[$index]['tax']);
      }




    /*
      Arrondis des sorties / line
    */
      $this->products[$index]['total_line']	  =tep_round($this->products[$index]['total_line'],$currencies->currencies[DEFAULT_CURRENCY]['decimal_places']);
      $this->products[$index]['total_line_ttc'] =tep_round($this->products[$index]['total_line_ttc'],$currencies->currencies[DEFAULT_CURRENCY]['decimal_places']);

      $products_tax = $this->products[$index]['tax'];
      $products_tax_description = $this->products[$index]['tax_description'];

//       $ttax=  $shown_taxe;
      $ttax = $this->products[$index]['total_line_taxe'];
      $this->info['tax'] += $ttax;

      if (isset($this->info['tax_groups']["$products_tax_description"]))   $this->info['tax_groups']["$products_tax_description"] +=$ttax;
      else   $this->info['tax_groups']["$products_tax_description"] =$ttax;

      $this->info['total_weight'] += $this->products[$index]['weight'];

      $this->info['subtotal_ht'] 	+= $this->products[$index]['total_line'];
      $this->info['subtotal_taxe'] 	+= $this->products[$index]['total_line_taxe'];
      $this->info['subtotal'] 	+= $this->products[$index]['total_line_ttc'];
      $index++;
    }

    $this->info['total'] = $this->info['subtotal']  ;
    $this->info['total_ht'] = $this->info['subtotal_ht'] + $this->info['shipping_cost_ht'];

    if( is_object( $this->coupon ) )  $this->info = $this->coupon->finalize_discount($this->info);

  }


}
?>