<?php



/**

  * Orders tab for admin panel, AdminOrders.php

  * @category admin

  *

  * @author PrestaShop <support@prestashop.com>

  * @copyright PrestaShop

  * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0

  * @version 1.0

  *

  */



include_once(PS_ADMIN_DIR.'/../classes/AdminTab.php');



class AdminOrders extends AdminTab

{

	public function __construct()

	{

	 	$this->table = 'order';

	 	$this->className = 'Order';

	 	$this->view = true;

		$this->colorOnBackground = true;

	 	$this->_select = 'a.id_order AS id_pdf, CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`, osl.`name` AS `osname`, os.`color`';

	 	$this->_join = 'LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = a.`id_customer`)

	 	LEFT JOIN `'._DB_PREFIX_.'order_history` oh ON (oh.`id_order` = a.`id_order`)

		LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = oh.`id_order_state`)

		LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = a.`id_lang`)';

		$this->_where = 'AND oh.`id_order_history` = (SELECT MAX(`id_order_history`) FROM `'._DB_PREFIX_.'order_history` moh WHERE moh.`id_order` = a.`id_order` GROUP BY moh.`id_order`)';

		

		global $cookie, $currentIndex;

		$statesArray = array();

		$states = OrderState::getOrderStates(intval($cookie->id_lang));

		foreach ($states AS $state)

			$statesArray[$state['id_order_state']] = $state['name'];



 		$this->fieldsDisplay = array(

		'id_order' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25),

		'customer' => array('title' => $this->l('Customer'), 'width' => 140, 'filter_key' => 'customer', 'tmpTableFilter' => true),

		'total_paid' => array('title' => $this->l('Total'), 'width' => 50, 'align' => 'right', 'prefix' => '<b>', 'suffix' => '</b>', 'price' => true, 'currency' => true),

		'payment' => array('title' => $this->l('Payment'), 'width' => 100),

		'osname' => array('title' => $this->l('Status'), 'type' => 'select', 'select' => $statesArray, 'filter_key' => 'os!id_order_state', 'filter_type' => 'int', 'width' => 200),

		'date_add' => array('title' => $this->l('Date'), 'width' => 90, 'align' => 'right', 'type' => 'date', 'filter_key' => 'a!date_add'),

		'id_pdf' => array('title' => $this->l('PDF'), 'width' => 20, 'prefix' => '<a href="pdf.php?id_order=', 'align' => 'right', 'suffix' => '&pdf"><img src="../img/admin/pdf.gif" alt="'.$this->l('PDF').'" /></a>', 'orderby' => false, 'search' => false));



		parent::__construct();

	}



	/**

	  * @global object $cookie Employee cookie necessary to keep trace of his/her actions

	  */

	public function postProcess()

	{

		global $currentIndex, $cookie;



		/* Change order state, add a new entry in order history and send an e-mail to the customer if needed */

		if ((Tools::isSubmit('submitState') OR Tools::isSubmit('submitShippingNumber')) AND ($id_order = intval(Tools::getValue('id_order'))) AND Validate::isLoadedObject($order = new Order($id_order)))

		{

			$_GET['view'.$this->table] = true;

			$lastOrderStatus = OrderHistory::getLastOrderState($id_order);

			if (Tools::isSubmit('submitShippingNumber') OR (Tools::isSubmit('submitState') AND ($newOrderStatusId = intval(Tools::getValue('id_order_state'))) == _PS_OS_SHIPPING_ AND $lastOrderStatus->id != _PS_OS_SHIPPING_))

			{

			 	if ($this->tabAccess['edit'] === '1')

		 		{

					if ($shipping_number = Tools::getValue('shipping_number'))

					{

						$order->shipping_number = $shipping_number;

						$order->update();

					}

				}

				else

					$this->_errors[] = Tools::displayError('You do not have permission to edit anything here.');

			}

			if (!Validate::isLoadedObject($lastOrderStatus))

				die(Tools::displayError());

			/* New status OR shipping number setting WITH a new status being the shipping */

			if (Tools::isSubmit('submitState') OR (Tools::isSubmit('submitShippingNumber') AND $newOrderStatusId == _PS_OS_SHIPPING_ AND $lastOrderStatus->id != _PS_OS_SHIPPING_))

			{

				$history = new OrderHistory();

				$history->id_order = $id_order;

				$history->changeIdOrderState(intval($newOrderStatusId), intval($id_order));

				$history->id_employee = intval($cookie->id_employee);

				$carrier = new Carrier(intval($order->id_carrier), intval($order->id_lang));

				$templateVars = array('{followup}' => ($history->id_order_state == _PS_OS_SHIPPING_ AND $order->shipping_number) ? str_replace('@', $order->shipping_number, $carrier->url) : '');

				if ($history->addWithemail(true, $templateVars))

					Tools::redirectAdmin($currentIndex.'&id_order='.$id_order.'&vieworder'.'&token='.$this->token);

				$this->_errors[] = Tools::displayError('an error occurred while changing status or was unable to send e-mail to the customer');

			}

		}



		/* Add a new message for the current order and send an e-mail to the customer if needed */

		elseif (isset($_POST['submitMessage']))

		{

			$_GET['view'.$this->table] = true;

		 	if ($this->tabAccess['edit'] === '1')

			{

				if (!($id_order = intval(Tools::getValue('id_order'))) OR !($id_customer = intval(Tools::getValue('id_customer'))))

					$this->_errors[] = Tools::displayError('an error occurred before sending message');

				elseif (!Tools::getValue('message'))

					$this->_errors[] = Tools::displayError('message cannot be blank');

				else

				{

					/* Get message rules and and check fields validity */

					$rules = call_user_func(array('Message', 'getValidationRules'), 'Message');

					foreach ($rules['required'] AS $field)

						if (($value = Tools::getValue($field)) == false AND (string)$value != '0')

							if (!Tools::getValue('id_'.$this->table) OR $field != 'passwd')

								$this->_errors[] = Tools::displayError('field').' <b>'.$field.'</b> '.Tools::displayError('is required');

					foreach ($rules['size'] AS $field => $maxLength)

						if (Tools::getValue($field) AND Tools::strlen(Tools::getValue($field)) > $maxLength)

							$this->_errors[] = Tools::displayError('field').' <b>'.$field.'</b> '.Tools::displayError('is too long').' ('.$maxLength.' '.Tools::displayError('chars max').')';

					foreach ($rules['validate'] AS $field => $function)

						if (Tools::getValue($field))

							if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8')))

								$this->_errors[] = Tools::displayError('field').' <b>'.$field.'</b> '.Tools::displayError('is invalid');

					if (!sizeof($this->_errors))

					{

						$message = new Message();

						$message->id_employee = intval($cookie->id_employee);

						$message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8');

						$message->id_order = $id_order;

						$message->private = Tools::getValue('visibility');

						if (!$message->add())

							$this->_errors[] = Tools::displayError('an error occurred while sending message');

						elseif ($message->private)

							Tools::redirectAdmin($currentIndex.'&id_order='.$id_order.'&vieworder&conf=11'.'&token='.$this->token);

						elseif (Validate::isLoadedObject($customer = new Customer($id_customer)))

						{

							$order = new Order(intval($message->id_order));

							if (Validate::isLoadedObject($order))

								if (Mail::Send(intval($order->id_lang), 'order_merchant_comment', $this->l('New message regarding your order').' '.$message->id_order, array('{genre}' => Gender::getNameById($message->id_customer), '{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => ((Configuration::get('PS_MAIL_TYPE') == 3 || Configuration::get('PS_MAIL_TYPE') == 2) ? $message->message : nl2br2($message->message))), $customer->email, $customer->firstname.' '.$customer->lastname))

									Tools::redirectAdmin($currentIndex.'&id_order='.$id_order.'&vieworder&conf=11'.'&token='.$this->token);

						}

						$this->_errors[] = Tools::displayError('an error occurred while sending e-mail to the customer');

					}

				}

			}

			else

				$this->_errors[] = Tools::displayError('You do not have permission to delete here.');

		}



		/* Cancel product from order */

		elseif (Tools::isSubmit('cancelProduct') AND Validate::isLoadedObject($order = new Order(intval(Tools::getValue('id_order')))))

		{

		 	if ($this->tabAccess['delete'] === '1')

			{

				$productList = Tools::getValue('id_product');

				$qtyList = Tools::getValue('cancelQuantity');

				

				if ($productList AND sizeof($productList) AND $qtyList AND sizeof($qtyList))

				{

					foreach ($productList AS $key => $id_product)

					{

						$qtyCancelProduct = $qtyList[$key];

						$orderDetail = new OrderDetail(intval($id_product));

						

						if (!$qtyCancelProduct)

						{

							$this->_errors[] = Tools::displayError('No quantity selected for product.');

							break ;

						}

						

						// Delete product

						if (!$order->deleteProduct($id_product, $qtyCancelProduct))

							$this->_errors[] = Tools::displayError('an error occurred during deletion for the product').' <span class="bold">'.$orderDetail->product_name.'</span>';

						Module::hookExec('deleteproduct', array('order' => $order, 'id_product' => $id_product));

						

						// Reinject product

						if (isset($_POST['reinjectQuantities']) AND !Product::reinjectQuantities($id_product, $qtyCancelProduct))

							$this->_errors[] = Tools::displayError('Cannot re-stock product').' <span class="bold">'.$orderDetail->product_name.'</span>';

					}

					

					// E-mail params

					if ((isset($_POST['generateCreditSlip']) OR isset($_POST['generateDiscount'])) AND !sizeof($this->_errors))

					{

						$customer = new Customer(intval($order->id_customer));

						$params['{genre}'] = Gender::getNameById($customer->id);

						$params['{lastname}'] = $customer->lastname;

						$params['{firstname}'] = $customer->firstname;

						$params['{id_order}'] = $order->id;

					}

					

					// Generate credit slip

					if (isset($_POST['generateCreditSlip']) AND !sizeof($this->_errors))

					{

						if (!OrderSlip::createOrderSlip($order, $productList, $qtyList))

							$this->_errors[] = Tools::displayError('Cannot generate credit slip');

						else

						{

							Module::hookExec('orderSlip', array('order'=>$order, 'productList'=>$productList, 'qtyList'=>$qtyList));

							@Mail::Send(intval($order->id_lang), 'credit_slip', $this->l('New credit slip regarding your order #').' '.$order->id, $params, $customer->email, $customer->firstname.' '.$customer->lastname);

						}

					}

					

					// Generate voucher

					if (isset($_POST['generateDiscount']) AND !sizeof($this->_errors))

					{

						if (!$voucher = Discount::createOrderDiscount($order, $productList, $qtyList, $this->l('Voucher on order')))

							$this->_errors[] = Tools::displayError('Cannot generate voucher');

						else

						{

							$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));

							$params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false, false);

							$params['{voucher_num}'] = $voucher->name;

							@Mail::Send(intval($order->id_lang), 'voucher', $this->l('New voucher regarding your order #').' '.$order->id, $params, $customer->email, $customer->firstname.' '.$customer->lastname);

						}

					}

				}

				else

					$this->_errors[] = Tools::displayError('No product or quantity selected.');

				

				// Redirect if no errors

				if (!sizeof($this->_errors))

					Tools::redirectLink($currentIndex.'&id_order='.$order->id.'&vieworder&conf=1&token='.$this->token);

			}

			else

				$this->_errors[] = Tools::displayError('You do not have permission to delete here.');

		}

		parent::postProcess();

	}



	public function viewDetails()

	{

		global $currentIndex, $cookie;

		$irow = 0;

		$order = $this->loadObject();



		$customer = new Customer($order->id_customer);

		$customerStats = $customer->getStats();

		$addressInvoice = new Address($order->id_address_invoice, intval($cookie->id_lang));

		if (Validate::isLoadedObject($addressInvoice) AND $addressInvoice->id_state)

			$invoiceState = new State(intval($addressInvoice->id_state));

		$addressDelivery = new Address($order->id_address_delivery, intval($cookie->id_lang));

		if (Validate::isLoadedObject($addressDelivery) AND $addressDelivery->id_state)

			$deliveryState = new State(intval($addressDelivery->id_state));

		$carrier = new Carrier($order->id_carrier);

		$history = $order->getHistory($cookie->id_lang);

		$products = $order->getProducts();

		$discounts = $order->getDiscounts();

		$messages = Message::getMessagesByOrderId($order->id);

		$states = OrderState::getOrderStates(intval($cookie->id_lang));

		$currency = new Currency($order->id_currency);

		$currentLanguage = new Language(intval($cookie->id_lang));

		$link = new Link();



		$row = array_shift($history);

		echo '<h2>'.$customer->firstname.' '.$customer->lastname.' #'.sprintf('%06d', $order->id).'

		- <a href="pdf.php?id_order='.$order->id.'&pdf"><img src="../img/admin/pdf.gif" alt="'.$this->l('View invoice').'" /></a>

		- <a href="javascript:window.print()"><img src="../img/admin/printer.gif" alt="'.$this->l('Print order').'" /></a></h2>';

		if ($order->total_paid != $order->total_paid_real)

			echo '<center><span class="warning" style="font-size: 16px">'.$this->l('Warning:').' '.Tools::displayPrice($order->total_paid_real, $currency, false, false).' '.$this->l('paid instead of').' '.Tools::displayPrice($order->total_paid, $currency, false, false).' !</span></center><div class="clear"><br /><br /></div>';



		// display bar code if module enabled

		$hook = Module::hookExec('invoice', array('id_order' => $order->id));

		if ($hook !== false)

		{

			echo '<div style="float: right; margin: -40px 40px 10px 0;">';

			echo $hook;

			echo '</div><br style="clear: both;" />';

		}



		// display hook specified to this page : AdminOrder

		if (($hook = Module::hookExec('adminOrder', array('id_order' => $order->id))) !== false)

		{

			echo $hook;

		}



		/* Display current state */

		echo '

		<div style="float: left;"><table cellspacing="0" cellpadding="0" class="table" style="width: 429px">

			<tr>

				<th>'.Tools::displayDate($row['date_add'], 1, true).'</th>

				<th><img src="../img/os/'.$row['id_order_state'].'.gif" /></th>

				<th>'.stripslashes($row['ostate_name']).'</th>

				<th>'.((!empty($row['employee_lastname'])) ? '('.stripslashes(substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'</th>

			</tr>';



		/* Display previous states */

		foreach ($history AS $row)

		{

			echo '

			<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">

				<td>'.Tools::displayDate($row['date_add'], 1, true).'</td>

				<td><img src="../img/os/'.$row['id_order_state'].'.gif" /></td>

				<td>'.stripslashes($row['ostate_name']).'</td>

				<td>'.((!empty($row['employee_name'])) ? '('.stripslashes(substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'</td>

			</tr>';

		}

		echo '</table></div>';



		echo '<div style="float: left; margin-left: 40px">

			<form action="'.$currentIndex.'&view'.$this->table.'&token='.$this->token.'" method="post">

				<select name="id_order_state">';

		$currentState = $order->getCurrentStateFull($cookie->id_lang);

		foreach ($states AS $state)

			echo '<option value="'.$state['id_order_state'].'"'.(($state['id_order_state'] == $currentState['id_order_state']) ? ' selected="selected"' : '').'>'.stripslashes($state['name']).'</option>';

		echo '

				</select>

				<input type="hidden" name="id_order" value="'.$order->id.'" />

				<input type="submit" name="submitState" value="'.$this->l('Change').'" class="button" />

				<br />';



		/* Display shipping number field */

		if ($carrier->url)

		echo '<input type="text" name="shipping_number" value="' . $order->shipping_number . '" style="margin-top: 10px;" />

			<input type="submit" name="submitShippingNumber" value="'.$this->l('Set shipping number').'" class="button" style="margin-top: 10px;" />';

		

		echo '

			</form>

		</div>

		<div class="clear">&nbsp;</div>';



		if ($order->shipping_number)

		{

			echo '<br />

			<fieldset><legend><img src="../img/admin/delivery.gif" /> '.$this->l('Shipping number').'</legend>

				'.$this->l('Click on the following URL to track the shipment:').' <a href="'.str_replace('@', $order->shipping_number, $carrier->url).'" target="_blank">'.str_replace('@', $order->shipping_number, $carrier->url).'</a>

			</fieldset>

			<div class="clear">&nbsp;</div>';

		}



		/* Display customer information */

		echo '

		<div style="float: left;">

			<fieldset style="width: 400px">

				<legend><img src="../img/admin/tab-customers.gif" /> '.$this->l('Customer information').'</legend>

				<span style="font-weight: bold; font-size: 14px;"><a href="?tab=AdminCustomers&id_customer='.$customer->id.'&viewcustomer&token='.Tools::getAdminToken('AdminCustomers'.intval(Tab::getIdFromClassName('AdminCustomers')).intval($cookie->id_employee)).'"> '.$customer->firstname.' '.$customer->lastname.'</a></span><br />

				(<a href="mailto:'.$customer->email.'">'.$customer->email.'</a>)<br /><br />

				'.$this->l('Account registered:').' '.Tools::displayDate($customer->date_add, 1, true).'<br />

				'.$this->l('Valid orders placed:').' <b>'.$customerStats['nb_orders'].'</b><br />

				'.$this->l('Total paid since registration:').' <b>'.Tools::displayPrice($customerStats['total_orders'], $currency, false, false).'</b><br />

			</fieldset>';

			if (sizeof($messages))

			{

				echo '<br /><fieldset style="width: 400px"><legend><img src="../img/admin/email.gif" /> '.$this->l('Messages').'</legend>';

				foreach ($messages as $message)

					echo '('.Tools::displayDate($message['date_add'], 1, true).') <b>'.(($message['elastname']) ? ($message['efirstname'].' '.$message['elastname']) : ($message['cfirstname'].' '.$message['clastname'])).'</b>'.(intval($message['private']) == 1 ? ' ['.$this->l('Private').']' : '').': '.nl2br2($message['message']).'<br />';

				echo '</fieldset><div class="clear">&nbsp;</div>';

			}

		echo '</div>

		<div style="float: left; margin-left: 40px">

			<fieldset style="width: 400px">

				<legend><img src="../img/admin/details.gif" /> '.$this->l('Order details').'</legend>

				<label>'.$this->l('Payment mode:').' </label>

				<div style="margin: 2px 0 1em 190px;">'.$order->payment.' '.($order->module ? '('.$order->module.')' : '').'</div>

				<div style="margin: 2px 0 1em 50px;">

					<table class="table" width="300px;" cellspacing="0" cellpadding="0">

						<tr><td width="150px;">'.$this->l('Products').'</td><td align="right">'.Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency, false, false).'</td></tr>

						<tr><td>'.$this->l('Discounts').'</td><td align="right">'.Tools::displayPrice($order->total_discounts, $currency, false, false).'</td></tr>

						<tr><td>'.$this->l('Wrapping').'</td><td align="right">'.Tools::displayPrice($order->total_wrapping, $currency, false, false).'</td></tr>

						<tr><td>'.$this->l('Shipping').'</td><td align="right">'.Tools::displayPrice($order->total_shipping, $currency, false, false).'</td></tr>

						<tr style="font-size: 20px"><td>'.$this->l('Total').'</td><td align="right">'.Tools::displayPrice($order->total_paid, $currency, false, false).($order->total_paid != $order->total_paid_real ? '<br /><font color="red">('.$this->l('Paid:').' '.Tools::displayPrice($order->total_paid_real, $currency, false, false).')</font>' : '').'</td></tr>

					</table>

				</div>

				<label>'.$this->l('Carrier:').'</label>

				<div style="margin: 2px 0 1em 190px;">

					'.((file_exists(_PS_SHIP_IMG_DIR_.$carrier->id.'.jpg')) ? '<img src="'._THEME_SHIP_DIR_.$carrier->id.'.jpg" />' : ($carrier->name == '0' ? Configuration::get('PS_SHOP_NAME'): $carrier->name).'&nbsp;').'

					<br />'.(!empty($order->shipping_number) ? $this->l('Tracking number:').' '.$order->shipping_number : $this->l('No tracking number')).'

				</div>

				<div style="float: left; margin-right: 10px; margin-left: 42px;">

					<span class="bold">'.$this->l('Recycled package:').'</span>

					'.($order->recyclable ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />').'

				</div>

				<div style="float: left; margin-right: 10px;">				

					<span class="bold">'.$this->l('Gift wrapping:').'</span>

					 '.($order->gift ? '<img src="../img/admin/enabled.gif" />

				'.(!empty($order->gift_message) ? '<div style="border: 1px dashed #999; padding: 5px; margin-top: 8px;"><b>'.$this->l('Message:').'</b><br />'.$order->gift_message.'</div>' : '') : '<img src="../img/admin/disabled.gif" />').'</div>

			</fieldset>

		</div>';



		/* Display adresses : delivery & invoice */

		echo '<div class="clear">&nbsp;</div>

		<div style="float: left">

			<fieldset style="width: 400px;">

				<legend><img src="../img/admin/delivery.gif" alt="Shipping" />'.$this->l('Shipping').'</legend>

				<div style="float: right"><a href="'.$link->getUrlWith('tab', 'AdminAddresses').'&id_address='.$addressDelivery->id.'&addaddress&realedit=1&id_order='.$order->id.($addressDelivery->id == $addressInvoice->id ? '&address_type=1' : '').'&token='.Tools::getAdminToken('AdminAddresses'.intval(Tab::getIdFromClassName('AdminAddresses')).intval($cookie->id_employee)).'&back='.urlencode($_SERVER['REQUEST_URI']).'"><img src="../img/admin/edit.gif" /></a></div>

				'. (!empty($addressDelivery->company) ? $addressDelivery->company.'<br />' : '') .$addressDelivery->firstname.' '.$addressDelivery->lastname.'<br />

				'.$addressDelivery->address1.'<br />'. (!empty($addressDelivery->address2) ? $addressDelivery->address2.'<br />' : '') .'

				'.$addressDelivery->postcode.' '.$addressDelivery->city.'<br />

				'.$addressDelivery->country.($addressDelivery->id_state ? ' - '.$deliveryState->name : '').'

				'.(!empty($addressDelivery->other) ? '<hr />'.$addressDelivery->other.'<br />' : '').'

				<hr />

				<img src="../img/admin/google.gif" alt="" class="middle" /> <a href="http://maps.google.com/maps?f=q&hl='.$currentLanguage->iso_code.'&geocode=&q='.$addressDelivery->address1.' '.$addressDelivery->postcode.' '.$addressDelivery->city.($addressDelivery->id_state ? ' '.$deliveryState->name: '').'">'.$this->l('Try to find this address with Google Maps').'</a>

			</fieldset>

		</div>

		<div style="float: left; margin-left: 40px">

			<fieldset style="width: 400px;">

				<legend><img src="../img/admin/invoice.gif" alt="'.$this->l('Invoice').'" />'.$this->l('Invoice').'</legend>

				<div style="float: right"><a href="'.$link->getUrlWith('tab', 'AdminAddresses').'&id_address='.$addressInvoice->id.'&addaddress&realedit=1&id_order='.$order->id.($addressDelivery->id == $addressInvoice->id ? '&address_type=2' : '').'&back='.urlencode($_SERVER['REQUEST_URI']).'&token='.Tools::getAdminToken('AdminAddresses'.intval(Tab::getIdFromClassName('AdminAddresses')).intval($cookie->id_employee)).'"><img src="../img/admin/edit.gif" /></a></div>

				'. (!empty($addressInvoice->company) ? $addressInvoice->company.'<br />' : '') .$addressInvoice->firstname.' '.$addressInvoice->lastname.'<br />

				'.$addressInvoice->address1.'<br />'. (!empty($addressInvoice->address2) ? $addressInvoice->address2.'<br />' : '') .'

				'.$addressInvoice->postcode.' '.$addressInvoice->city.'<br />

				'.$addressInvoice->country.($addressInvoice->id_state ? ' - '.$invoiceState->name : '').'

				'.(!empty($addressInvoice->other) ? '<hr />'.$addressInvoice->other.'<br />' : '').'

			</fieldset>

		</div>

		<div class="clear">&nbsp;</div>';



		// List of products

		echo '<a name="products"><br /></a>

		<form action="'.$currentIndex.'&submitCreditSlip&vieworder&token='.$this->token.'" method="post" onsubmit="return orderDeleteProduct(\''.$this->l('Cannot return this product').'\', \''.$this->l('Quantity to cancel is superior than quantity ordered').'\');"><fieldset style="width: 868px;">

		<input type="hidden" name="id_order" value="'.$order->id.'" />

		<legend><img src="../img/admin/cart.gif" alt="'.$this->l('Products').'" />'.$this->l('Products').'</legend>

		<table style="width: 868px" cellspacing="0" cellpadding="0" class="table" id="orderProducts">

			<tr>

				<th>&nbsp;</th>

				<th style="width: 60px">'.$this->l('Quantity to cancel').'</th>

				<th>'.$this->l('Photo').'</th>

				<th>'.$this->l('Product').'</th>

				<th style="width: 100px">'.$this->l('Unit price').'</th>

				<th style="width: 60px">'.$this->l('Quantity ordered').'</th>

				<th style="width: 60px">'.$this->l('Quantity canceled').'</th>

				<th style="width: 100px">'.$this->l('Total price').'</th>

			</tr>';

		$tokenCatalog = Tools::getAdminToken('AdminCatalog'.intval(Tab::getIdFromClassName('AdminCatalog')).intval($cookie->id_employee));

		$isCancel = OrderState::invoiceAvailable($order->getCurrentState());

		foreach ($products as $k => $product)

		{

		 	$image = Db::getInstance()->getRow('

			SELECT id_image

			FROM '._DB_PREFIX_.'image

			WHERE id_product = '.intval($product['product_id']).' AND cover = 1');

			echo '

			<tr>

				<td>'.($isCancel ? '<input type="checkbox" name="id_product['.$k.']" value="'.$product['id_order_detail'].'" />' : '').'</td>

				<td align="center" class="cancelQuantity">'.($isCancel ? '<input type="text" value="" name="cancelQuantity['.$k.']" size="2" />' : '-').'</td>

				<td>'.(isset($image['id_image']) ? cacheImage(_PS_IMG_DIR_.'p/'.$product['product_id'].'-'.intval($image['id_image']).'.jpg',

				'product_mini_'.$product['product_id'].'.jpg', 45, 'jpg') : '--').'</td>

				<td><a href="index.php?tab=AdminCatalog&id_product='.$product['product_id'].'&updateproduct&token='.$tokenCatalog.'">'.$product['product_reference'];

                echo (strlen($product['product_reference']) and strlen($product['product_supplier_reference']))? ' / ' : '' ;

                echo $product['product_supplier_reference'].'<br /><span class="productName">'.$product['product_name'].'</span></a></td>

				<td align="center">'.Tools::displayPrice($product['product_price_wt'], $currency, false, false).'</td>

				<td align="center" class="productQuantity" >'.intval($product['product_quantity']).'</td>

				<td align="center" class="returnQuantity" >'.intval($product['product_quantity_return']).'</td>

				<td align="center">'.Tools::displayPrice($product['total_wt'], $currency, false, false).'</td>

			</tr>';

		}

		echo '</table><div class="clear">&nbsp;</div>';

		if ($isCancel)

		{

			echo '

			<div style="float:left;">

				<input type="checkbox" name="reinjectQuantities" class="button" />&nbsp;'.$this->l('Re-stock products').'<br />

				<input type="checkbox" name="generateCreditSlip" class="button" />&nbsp;'.$this->l('Generate a credit slip').'<br />

				<input type="checkbox" name="generateDiscount" class="button" />&nbsp;'.$this->l('Generate a voucher').'<br />

			</div>

			';

			echo '

			<div style="float:left; margin-left:40px;">

				<input type="submit" name="cancelProduct" value="'.$this->l('Cancel selected products').'" class="button" style="margin-bottom:8px;" /><br />

				'.$this->l('By clicking this button you can cancel a product of its order.').'

			</div>';

		}

		echo '</fieldset>

		</form><br /><br />';

		if (sizeof($discounts))

		{

			echo '<table cellspacing="0" cellpadding="0" class="table"><tr><th>'.$this->l('Discount name').'</th><th>'.$this->l('Value').'</th></tr>';

			foreach ($discounts as $discount)

				echo '<tr><td>'.$discount['name'].'</td><td align="right">-'.Tools::displayPrice($discount['value'], $currency, false).'</td></tr>';

			echo '</table><div class="clear">&nbsp;</div>';

		}



		/* Display send a message to customer & returns/credit slip*/

		$returns = OrderReturn::getOrdersReturn($order->id_customer, $order->id);

		$slips = OrderSlip::getOrdersSlip($order->id_customer, $order->id);

		echo '

		<div style="float: left">

			<form action="'.$_SERVER['REQUEST_URI'].'&token='.$this->token.'" method="post" onsubmit="if (getE(\'visibility\').checked == true) return confirm(\''.addslashes($this->l('Do you want to send this message to the customer?')).'\');">

			<fieldset style="width: 400px;">

				<legend style="cursor: pointer;" onclick="openCloseLayer(\'message\');openCloseLayer(\'message_m\');"><img src="../img/admin/email_edit.gif" /> '.$this->l('New message').'</legend>

				<div id="message_m" style="display: '.(Tools::getValue('message') ? 'none' : 'block').'">

					<a href="javascript:openCloseLayer(\'message\');openCloseLayer(\'message_m\');"><b>'.$this->l('Click here').'</b> '.$this->l('to add a comment or send a message to the customer').'</a>

				</div>

				<div id="message" style="display: '.(Tools::getValue('message') ? 'block' : 'none').'">

					<b>'.$this->l('Display to consumer?').'</b>

					<input type="radio" name="visibility" id="visibility" value="0" /> '.$this->l('Yes').'

					<input type="radio" name="visibility" value="1" checked="checked" /> '.$this->l('No').'

					<p id="nbchars" style="display:inline;font-size:10px;color:#666;"></p><br /><br />

					<textarea id="txt_msg" name="message" cols="60" rows="8" onKeyUp="var length = document.getElementById(\'txt_msg\').value.length; if (length > 600) length = \'600+\'; document.getElementById(\'nbchars\').innerHTML = \''.$this->l('600 chars max').' (\' + length + \')\';">'.htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8').'</textarea><br /><br />

					<input type="hidden" name="id_order" value="'.intval($order->id).'" />

					<input type="hidden" name="id_customer" value="'.intval($order->id_customer).'" />

					<input type="submit" class="button" name="submitMessage" value="'.$this->l('Send').'" />

				</div>

			</fieldset>

			</form>

		</div>';

		

		echo '<div style="float: left; margin-left: 40px">

			<fieldset style="width: 400px;">

				<legend><img src="../img/admin/return.gif" alt="'.$this->l('Merchandise returns').'" />'.$this->l('Merchandise returns').'</legend>';

		if (!sizeof($returns))

			echo $this->l('No merchandise return for this order.');

		else

			foreach ($returns as $return)

			{

				$state = new OrderReturnState($return['state']);

				echo '('.Tools::displayDate($return['date_upd'], $cookie->id_lang).') :

				<b><a href="index.php?tab=AdminReturn&id_order_return='.$return['id_order_return'].'&updateorder_return&token='.Tools::getAdminToken('AdminReturn'.intval(Tab::getIdFromClassName('AdminReturn')).intval($cookie->id_employee)).'">'.$this->l('#RE').sprintf('%06d', $return['id_order_return']).'</a></b> -

				'.$state->name[$cookie->id_lang].'<br />';

			}

		echo '</fieldset>

				<br />

				<fieldset style="width: 400px;">

					<legend><img src="../img/admin/slip.gif" alt="'.$this->l('Credit slip').'" />'.$this->l('Credit slip').'</legend>';

		if (!sizeof($slips))

			echo $this->l('No slip for this order.');

		else

			foreach ($slips as $slip)

				echo '('.Tools::displayDate($slip['date_upd'], $cookie->id_lang).') : <b><a href="pdf.php?id_order_slip='.$slip['id_order_slip'].'">'.$this->l('#').sprintf('%06d', $slip['id_order_slip']).'</a></b><br />';

		echo '</fieldset>

		</div>';

		echo '<div class="clear">&nbsp;</div>';

		echo '<br /><br /><a href="'.$currentIndex.'&token='.$this->token.'"><img src="../img/admin/arrow2.gif" /> '.$this->l('Back to list').'</a><br />';

	}



	public function display()

	{

		global $cookie;



		if (isset($_GET['view'.$this->table]))

			$this->viewDetails();

		else

		{

			$this->getList(intval($cookie->id_lang), !Tools::getValue($this->table.'Orderby') ? 'date_add' : NULL, !Tools::getValue($this->table.'Orderway') ? 'DESC' : NULL);

			$this->displayList();

		}

	}

}



?>