<?php
/**
 * @package    JBusinessDirectory
 *
 * @author     CMSJunkie http://www.cmsjunkie.com
 * @copyright  Copyright (C) 2007 - 2021 CMSJunkie. All rights reserved.
 * @license    https://www.gnu.org/licenses/agpl-3.0.en.html
 */

defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');

/**
 * Orders List Model
 *
 * @package     JBusinessDirectory
 * @subpackage  com_jbusinessdirectory
 */
class JBusinessDirectoryModelOrders extends JModelList {
	/**
	 * Constructor.
	 *
	 * @param   array  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array()) {
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'id', 'inv.id',
				'title', 'inv.name',
				"order_id", 'inv.order_id',
				"company", 'c.name',
				"package", 'p.name',
				"package_type", 'p.package_type',
				"amount", 'inv.amount',
				"created", 'inv.created',
				"transaction_id", 'inv.transaction_id',
				"paid_at", 'inv.start_date',
				"user_name", 'inv.user_name',
				"discount_code", "inv.discount_code",
				"state", 'inv.state'
			);
		}

		parent::__construct($config);
	}

	/**
	 * Overrides the getItems method to attach additional metrics to the list.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   1.6.1
	 */
	public function getItems() {
		// Get a storage key.
		$store = $this->getStoreId('getItems');

		// Try to load the data from internal storage.
		if (!empty($this->cache[$store])) {
			return $this->cache[$store];
		}

		// Load the list items.
		$items = parent::getItems();

		// If empty or an error, just return.
		if (empty($items)) {
			return array();
		}


		// Add the items to the internal cache.
		$this->cache[$store] = $items;

		return $this->cache[$store];
	}

	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return  string  An SQL query
	 *
	 * @since   1.6
	 */
	protected function getListQuery() {
		// Create a new query object.
		$db    = $this->getDbo();
		$query = $db->getQuery(true);

		// Select all fields from the table.
		$query->select($this->getState('list.select', 'inv.*'));
		$query->from($db->quoteName('#__jbusinessdirectory_orders') . ' AS inv');

		// Join over the company types
		$query->select('c.name as companyName');
		$query->join('LEFT', $db->quoteName('#__jbusinessdirectory_companies') . ' AS c ON c.id=inv.company_id');
		
		$search = $this->getState('filter.search');
		$packageType = $this->getState('filter.package_type');
		if (is_numeric($packageType) || !empty($search)) {
			// Join over the company types
			$query->select('p.name as packageName');
			$query->join('LEFT', $db->quoteName('#__jbusinessdirectory_packages') . ' AS p ON p.id=inv.package_id');
		}
		
		// Filter by search in title.
		if (!empty($search)) {
			$query->where("(inv.order_id LIKE '%" . trim($db->escape($search)) . "%' or c.phone LIKE '%" . trim($db->escape($search)) . "%' or c.name LIKE '%" . trim($db->escape($search)) . "%' or p.name LIKE '%" . trim($db->escape($search)) . "%' )");
		}

		$statusId = $this->getState('filter.state_id');
		if (is_numeric($statusId)) {
			$query->where("inv.state =" . (int) $statusId);
		}

		$companyId = $this->getState('filter.company_id');
		if (is_numeric($companyId)) {
			$query->where("inv.company_id =" . (int) $companyId);
		}

		$packageId = $this->getState('filter.package_id');
		if (is_numeric($packageId)) {
			$query->where("inv.package_id =" . (int) $packageId);
		}

		if (is_numeric($packageType)) {
			$query->where("p.package_type =" . (int) $packageType);
		}

		$startDate = $this->getState('filter.start_date');
		$endDate = $this->getState('filter.end_date');

		// Filter offer orders by start and end date
		if (!empty($startDate) && !empty($endDate)) {
			$query->where("inv.created between '" . JBusinessUtil::convertToMysqlFormat($startDate) . " 00:00:00' and '" . JBusinessUtil::convertToMysqlFormat($endDate) . " 23:59:59'");
		} elseif (!empty($startDate)) {
			$query->where("inv.created >= '" . JBusinessUtil::convertToMysqlFormat($startDate) . " 00:00:00'");
		} elseif (!empty($endDate)) {
			$query->where("inv.created <= '" . JBusinessUtil::convertToMysqlFormat($endDate) . " 23:59:59'");
		}

		$query->group('inv.id');

		// Add the list ordering clause.
		$orderCol  = $this->state->get('list.ordering', 'inv.id');
		$orderDirn = $this->state->get('list.direction', 'ASC');

		// Add the list ordering clause.
		$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDirn));

		return $query;
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string $ordering  An optional ordering field.
	 * @param   string $direction An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = "inv.id", $direction = "desc") {
		$app = JFactory::getApplication('administrator');

		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$statusId = $app->getUserStateFromRequest($this->context . '.filter.state_id', 'filter_state_id');
		$this->setState('filter.state_id', $statusId);

		$companyId = $app->getUserStateFromRequest($this->context . '.filter.company_id', 'filter_company_id');
		$this->setState('filter.company_id', $companyId);

		$packageId = $app->getUserStateFromRequest($this->context . '.filter.package_id', 'filter_package_id');
		$this->setState('filter.package_id', $packageId);

		$startDate = $this->getUserStateFromRequest($this->context . '.filter.start_date', 'filter_start_date', '');
		$this->setState('filter.start_date', $startDate);

		$endDate = $this->getUserStateFromRequest($this->context . '.filter.end_date', 'filter_end_date', '');
		$this->setState('filter.end_date', $endDate);

		// Check if the ordering field is in the white list, otherwise use the incoming value.
		$value = $app->getUserStateFromRequest($this->context . '.ordercol', 'filter_order', $ordering);
		$this->setState('list.ordering', $value);

		// Check if the ordering direction is valid, otherwise use the incoming value.
		$value = $app->getUserStateFromRequest($this->context . '.orderdir', 'filter_order_Dir', $direction);
		$this->setState('list.direction', $value);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	public function exportOrdersCSV() {
		$csv_output = $this->getOrdersCSV();

		$fileName = "jbusinessdirectory_orders";
		header("Content-type: application/vnd.ms-excel");
		header("Content-disposition: csv" . date("Y-m-d") . ".csv");
		header("Content-disposition: filename=" . $fileName . ".csv");
		print $csv_output;
	}

	public function getOrdersCSV() {
		$jinput    = JFactory::getApplication()->input;
		$delimiter = $jinput->getString("delimiter", ",");

		$ordersTable = JTable::getInstance("Order", "JTable");
		$orders      = $ordersTable->getOrdersForExport();

		$csv_output = "order_id" . $delimiter . "company_id" . $delimiter . "package_id" . $delimiter . "initial_amount" . $delimiter
			. "amount" . $delimiter . "amount_paid" . $delimiter . "created" . $delimiter . "paid_at" . $delimiter . "state" . $delimiter
			. "transaction_id" . $delimiter . "user_name" . $delimiter . "service" . $delimiter . "description" . $delimiter
			. "start_date" . $delimiter . "type" . $delimiter . "currency" . $delimiter . "expiration_email_date" . $delimiter
			. "discount_code" . $delimiter . "discount_amount" . $delimiter . "vat_amount" . "\n";

		foreach ($orders as $order) {
			$order->description = str_replace(array("\r\n", "\r", "\n"), "<br />", $order->description);
			$order->description = str_replace('"', '""', $order->description);
			$csv_output         .= "\"$order->order_id\"" . $delimiter . "\"" . $order->company_id . "\"" . $delimiter . "\"$order->package_id\"" . $delimiter .
				"\"$order->initial_amount\"" . $delimiter . "\"$order->amount\"" . $delimiter . "\"$order->amount_paid\"" . $delimiter .
				"\"$order->created\"" . $delimiter . "\"$order->paid_at\"" . $delimiter . "\"$order->state\"" . $delimiter .
				"$order->transaction_id" . $delimiter . "\"$order->user_name\"" . $delimiter . "\"$order->service\"" . $delimiter .
				"\"$order->description\"" . $delimiter . "\"$order->start_date\"" . $delimiter . "\"$order->type\"" . $delimiter .
				"\"$order->currency\"" . $delimiter . "\"$order->expiration_email_date\"" . $delimiter . "\"$order->discount_code\"" . $delimiter .
				"\"$order->discount_amount\"" . $delimiter . "\"$order->vat_amount\"";
			$csv_output         .= "\n";
		}

		return $csv_output;
	}

	public function getLogs() {
		$app =JFactory::getApplication();
		$file = new stdClass();
		
		$path = JPATH_COMPONENT_SITE.DS.'logs';
		$file->path = $path;
		$files = scandir($path);
		$file->content = '';

		$date = "";
		foreach ($files as $key => $val) {
				$date = substr($val, -14, 10);
				$files[$date] = $files[$key];
				unset($files[$key]);
		}
		uksort($files, function ($a, $b) {
			return strtotime($a) > strtotime($b) ? -1 : 1;
		});

		foreach ($files as $log) {
			if ($log != "." && $log != "..") {
				$filePath = JPATH_COMPONENT_SITE.DS.'logs'.DS.$log;
				$file->filePath = $filePath;

				$fileinfo = pathinfo($filePath);
				$file->name = $fileinfo["basename"];
				$file->extension = $fileinfo["extension"];
			
				jimport('joomla.filesystem.file');
			
				if (JFile::exists($filePath) && $file->extension == "log") {
					if (filesize($filePath) !== 0) {
						$file->content .= '<div class="font-weight-bold pt-2 pb-1">Log file: '.$file->name.'</div>'. file_get_contents($filePath);
						$file->content .= '<br/>';
					}
				}
			}
		}
		$this->file = $file;
		
		return $file ;
	}
}
