<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

defined('_JEXEC') or die();

class Djcatalog2ExportHelper
{

	protected static $_djc2_params;

	public static function exportOrders($cid = array())
	{
		$app = JFactory::getApplication();

		$success = false;
		$msg = '';

		JModelLegacy::addIncludePath(JPATH_BASE . '/administrator/components/com_djcatalog2/models', 'DJCatalog2Model');
		$model = JModelLegacy::getInstance('Orders', 'Djcatalog2Model', array('ignore_request' => true));
		$model->getState();


		if (count($cid)) {
			$model->setState('filter.ids', implode($cid, ","));
		}

		$user = JFactory::getUser();
		$salesman = $user->authorise('djcatalog2.salesman', 'com_djcatalog2');
		$salesUser = $app->getUserState($app->getUserState('com_djcatalog2.checkout.user_id', null));

		if (!$salesman && !$salesUser) {
			$model->setState('filter.user', $user->id);
		} else {
			if ((int)$salesUser > 0) {
				$model->setState('filter.user', (int)$salesUser);
			} else {
				$model->setState('filter.salesman', $user->id);
			}
		}

		$model->setState('list.ordering', 'a.created_date');
		$model->setState('list.direction', 'desc');
		$model->setState('order_items', true);


		$orders = $model->getItems();
		$csv = '';

		foreach ($orders as $order) {


			$csv .= self::orderToCsv($order);
			$csv .= "\r\n\r\n\r\n";
		}

		$csv .= "\r\n\r\n\r\n";

		$file_name = 'orders-' . date("Y-m-d_H_i_s") .'-U'.$user->id. '.csv';
		$csv_path = self::getExportPath('order') . '/' . $file_name;

		if (!JFile::write($csv_path, $csv)) {
			$msg = JText::_('COM_DJCATALOG2_EXPORT_FAILED');
		} else {
			$msg = '<a href="' . JRoute::_('index.php?option=com_djcatalog2&task=download_file&path=' . base64_encode($csv_path)) . '">' . $file_name . '</a></br>';
			$success = true;
		}

		return array(
			'success' => $success,
			'message' => '',
			'filename' => $file_name
		);
	}

	public static function exportQuotes($cid = array())
	{
		$app = JFactory::getApplication();

		$success = false;
		$msg = '';

		if ($app->isClient('administrator')) {
			JModelLegacy::addIncludePath(JPATH_BASE . '/administrator/components/com_djcatalog2/models', 'DJCatalog2Model');
			$model = JModelLegacy::getInstance('Queries', 'Djcatalog2Model', array('ignore_request' => true));
		} else {
			$model = JModelLegacy::getInstance('Questions', 'Djcatalog2Model', array('ignore_request' => true));
		}

		$model->getState();


		if (count($cid)) {
			$model->setState('filter.ids', implode($cid, ","));
		}

		$user = JFactory::getUser();
		$salesman = $user->authorise('djcatalog2.salesman', 'com_djcatalog2');
		$salesUser = $app->getUserState($app->getUserState('com_djcatalog2.checkout.user_id', null));

		if (!$salesman && !$salesUser) {
			$model->setState('filter.user', $user->id);
		} else {
			if ((int)$salesUser > 0) {
				$model->setState('filter.user', (int)$salesUser);
			} else {
				$model->setState('filter.salesman', $user->id);
				//$this->setState('filter.user', -1);
			}
		}

		$model->setState('list.ordering', 'a.created_date');
		$model->setState('list.direction', 'desc');
		$model->setState('quote_items', true);


		$quotes = $model->getItems();

		$csv = '';

		foreach ($quotes as $quote) {


			$csv .= self::quoteToCsv($quote);
			$csv .= "\r\n\r\n\r\n";
		}

		$csv .= "\r\n\r\n\r\n";

		$file_name = 'quotes-' . date("Y-m-d_H_i_s") .'-U'.$user->id. '.csv';
		$csv_path = self::getExportPath('quotes') . '/' . $file_name;

		if (!JFile::write($csv_path, $csv)) {
			$msg = JText::_('COM_DJCATALOG2_EXPORT_FAILED');
		} else {
			$msg = '<a href="' . JRoute::_('index.php?option=com_djcatalog2&task=download_file&path=' . base64_encode($csv_path)) . '">' . $file_name . '</a></br>';
			$success = true;
		}

		return array(
			'success' => $success,
			'message' => '',
			'filename' => $file_name
		);
	}

	private static function orderToCsv($order)
	{

		$csv = '';
		$delimeter = self::getDelimeter();

		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_NUMBER')) . $delimeter . self::formatCsvType($order->order_number) . $delimeter . "\r\n";
		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_CREATED_DATE')) . $delimeter . self::formatCsvType($order->created_date) . $delimeter . "\r\n";
		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_FIELDSET_CUSTOMER')) . $delimeter . self::formatCsvType($order->delivery_firstname . " " . $order->delivery_lastname . " " . $order->delivery_company) . $delimeter . "\r\n";
		if ($order->tax > 0) {
			$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_TAX')) . $delimeter . self::formatCsvType($order->tax) . $delimeter . "\r\n";
		}

		if (count($order->items)) {
			$csv .= "\r\n" . self::formatCsvType(JText::_('COM_DJCATALOG2_NAME')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_SKU')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_QUANTITY')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_TOTAL')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_GRAND_TOTAL')) . $delimeter . "\r\n";

			foreach ($order->items as $order_item) {
				$csv .=
					self::formatCsvType($order_item->item_name) . $delimeter .
					self::formatCsvType($order_item->sku) . $delimeter .
					self::formatCsvType($order_item->quantity) . $delimeter .
					self::formatCsvType($order_item->cost, true) . $delimeter .
					self::formatCsvType($order_item->total, true) . $delimeter . "\r\n";
			}
		}
		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_GRAND_TOTAL')) . $delimeter . $delimeter . $delimeter . self::formatCsvType($order->grand_total, true) . $delimeter . "\r\n";

		return $csv;

	}

	private static function quoteToCsv($quote)
	{

		$csv = '';
		$delimeter = self::getDelimeter();

		$csv .= self::formatCsvType('E-mail') . $delimeter . self::formatCsvType($quote->email) . $delimeter . "\r\n";
		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_CREATED_DATE')) . $delimeter . self::formatCsvType($quote->created_date) . $delimeter . "\r\n";
		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_FIELDSET_CUSTOMER')) . $delimeter . self::formatCsvType($quote->firstname . " " . $quote->lastname . " " . $quote->company . " " . $quote->address . " " . $quote->city . " " . $quote->postcode) . $delimeter . "\r\n";
		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_CART_QUERY_MESSAGE')) . $delimeter . self::formatCsvType($quote->customer_note) . $delimeter . "\r\n";

		if (count($quote->items)) {
			$csv .= "\r\n" . self::formatCsvType(JText::_('COM_DJCATALOG2_NAME')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_SKU')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_QUANTITY')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_PRICE')) . $delimeter . self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_GRAND_TOTAL')) . $delimeter . "\r\n";

			foreach ($quote->items as $quote_item) {
				$csv .=
					self::formatCsvType($quote_item->item_name) . $delimeter .
					self::formatCsvType($quote_item->sku) . $delimeter .
					self::formatCsvType($quote_item->quantity) . $delimeter .
					self::formatCsvType($quote_item->price, true) . $delimeter .
					self::formatCsvType($quote_item->total, true) . $delimeter . "\r\n";
			}
		}
		$csv .= self::formatCsvType(JText::_('COM_DJCATALOG2_ORDER_GRAND_TOTAL')) . $delimeter . $delimeter . $delimeter . self::formatCsvType($quote->grand_total, true) . $delimeter . "\r\n";

		return $csv;

	}


	private static function formatCsvType($var, $price = false)
	{
		$params = self::getParams();

		if (is_numeric($var)) {
			$number_separator = $params->get('export_number_separator', ',');
			$decimal_places = $params->get('export_number_decimals', 2);
			$display_punit = $params->get('export_price_unit', 1);
			$punit = $params->get('price_unit', '');


			$var = number_format($var, $decimal_places, $number_separator, '');

			if ($price) {
				if ($display_punit == -1) {
					$var = $punit . ' ' . $var;
				} elseif ($display_punit == 1) {
					$var .= ' ' . $punit;
				}
			}


			return $var;
		}


		if (is_string($var)) {
			$string_separator = $params->get('export_string_separator', '"');

			return $string_separator . $var . $string_separator;

		}


		return $var;
	}

	private static function getParams($reload = false)
	{
		if (!isset(self::$_djc2_params) || $reload) {
			self::$_djc2_params = JComponentHelper::getParams('com_djcatalog2');
		}

		return self::$_djc2_params;
	}

	private static function getDelimeter()
	{
		$params = self::getParams();
		return $params->get('export_column_delimeter', ';');
	}

	public static function getExportPath($type)
	{
		return JPATH_ROOT . '/media/djcatalog2/export/' . $type;
	}

}