<?php
/**
 * @package    Techjoomla.Libraries
 *
 * @author     Techjoomla <extensions@techjoomla.com>
 * @copyright  Copyright (C) 2009 - 2019 Techjoomla. All rights reserved.
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

// No direct access.
defined('_JEXEC') or die();

use Joomla\CMS\Factory;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Filesystem\Path;
use Joomla\Archive\Zip;

/**
 * Helper class for common functions in JSocial library
 *
 * @package     Techjoomla.Libraries
 * @subpackage  JSocial
 * @since       1.0.4
 */
class TechjoomlaCommon
{
	/**
	 * Get itemid for given link
	 *
	 * @param   string   $link          link
	 * @param   integer  $skipIfNoMenu  Decide to use Itemid from $input
	 *
	 * @return  item id
	 *
	 * @since  3.0
	 */
	public static function getItemId($link, $skipIfNoMenu = 0)
	{
		$itemid    = 0;
		$app = Factory::getApplication();
		$jinput = $app->input;

		if ($app->isClient('site'))
		{
			$menu  = $app->getMenu();
			$items = $menu->getItems('link', $link);

			if (isset($items[0]))
			{
				$itemid = $items[0]->id;
			}
		}

		if (!$itemid)
		{
			$db = Factory::getDbo();
			$query = $db->getQuery(true);

			$query->select($db->quoteName('id'));
			$query->from($db->quoteName('#__menu'));
			$query->where($db->quoteName('link') . ' LIKE ' . $db->quote('%' . $link . '%'));
			$query->where($db->quoteName('published') . '=' . $db->quote(1));
			$query->setLimit(1);

			$db->setQuery($query);
			$itemid = $db->loadResult();
		}

		if (!$itemid)
		{
			if ($skipIfNoMenu)
			{
				$itemid = 0;
			}
			else
			{
				$itemid  = $jinput->get('Itemid', '0', 'INT');
			}
		}

		return $itemid;
	}

	/**
	 * This function get the view path
	 *
	 * @param   string  $component      Component name
	 * @param   string  $viewname       View name
	 * @param   string  $layout         Layout
	 * @param   string  $searchTmpPath  Site
	 * @param   string  $useViewpath    Site
	 *
	 * @return  boolean
	 *
	 * @since  1.0.0
	 */
	public function getViewpath($component, $viewname, $layout = 'default', $searchTmpPath = 'SITE', $useViewpath = 'SITE')
	{
		$app = Factory::getApplication();

		$searchTmpPath = ($searchTmpPath == 'SITE') ? JPATH_SITE : JPATH_ADMINISTRATOR;
		$useViewpath   = ($useViewpath == 'SITE') ? JPATH_SITE : JPATH_ADMINISTRATOR;

		$layoutname = $layout . '.php';

		$override = $searchTmpPath . '/templates/' . $app->getTemplate() . '/html/' . $component . '/' . $viewname . '/' . $layoutname;

		if (File::exists($override))
		{
			return $view = $override;
		}
		else
		{
			return $view = $useViewpath . '/components/' . $component . '/views/' . $viewname . '/tmpl/' . $layoutname;
		}
	}

	/**
	 * Sort given array with the provided column and provided order
	 *
	 * @param   array   $array   array of data
	 * @param   string  $column  column name
	 * @param   string  $order   order in which array has to be sort
	 *
	 * @return  array
	 *
	 * @since   1.0
	 */
	public function multi_d_sort($array, $column, $order)
	{
		if (isset($array) && count($array))
		{
			foreach ($array as $key => $row)
			{
				$orderby[$key] = $row->$column;
			}

			if ($order == 'asc')
			{
				array_multisort($orderby, SORT_ASC, $array);
			}
			else
			{
				array_multisort($orderby, SORT_DESC, $array);
			}
		}

		return $array;
	}

	/**
	 * Get all the dates converted to utc
	 *
	 * @param   date  $date  date of lesson
	 *
	 * @return   date in utc format
	 *
	 * @since   1.0
	 */
	public function getDateInUtc($date)
	{
		// Change date in UTC
		$user   = Factory::getUser();
		$config = Factory::getConfig();
		$offset = $user->getParam('timezone', $config->get('offset'));

		if (!empty($date) && $date != '0000-00-00 00:00:00')
		{
			$udate = Factory::getDate($date, $offset);
			$date = $udate->toSQL();
		}

		return $date;
	}

	/**
	 * Get all the dates converted to utc
	 *
	 * @param   date    $date                 date of lesson
	 * @param   int     $getOnlyDate          Flag used to get only date or datetime
	 * @param   string  $date_formatwithtime  Date format with time
	 * @param   string  $date_format          Date format
	 *
	 * @return   date in utc format
	 *
	 * @since   1.0
	 */
	public function getDateInLocal($date, $getOnlyDate = 0, $date_formatwithtime = 'Y-m-d H:i:s', $date_format = 'Y-m-d')
	{
		if (!empty($date) && $date != '0000-00-00 00:00:00')
		{
			if ($getOnlyDate == 0)
			{
				// Create JDate object set to now in the users timezone.
				$date = HTMLHelper::date($date, $date_formatwithtime, true);
			}
			else
			{
				$date = HTMLHelper::date($date, $date_format, true);
			}
		}

		return $date;
	}

	/**
	 * Function extact the uploaded zip
	 *
	 * @param   string  $extractdir  Directory where you want to extract the zip
	 * @param   string  $archive     Absolute Path of the zip file
	 *
	 * @return  true if successful
	 *
	 * @since 1.0.0
	 */
	public function extractCourse($extractdir, $archive)
	{
		$archive = Path::clean($archive);
		$extractdir = Path::clean($extractdir);

		if (version_compare(JVERSION, '4.0', 'le'))
		{
			if (JArchive::extract($archive, $extractdir))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else 
		{
			$zip         = new Zip;
			if ($zip->extract($archive, $extractdir))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}

	/**
	 * Returns last 12 months from current month
	 *
	 * @return  array of last 12 months from current date
	 *
	 * @since   1.0.0
	 */
	public function getLastTwelveMonths()
	{
		// Get current date
		$currentDate      = date('Y-m-d');

		// Get one year back date
		$lastYearDate = date('Y-m-d', strtotime(date("Y-m-d", time()) . " - 365 day"));

		// Convert dates to UNIX timestamp
		$lastYearTime    = strtotime($lastYearDate);
		$CurrentDateTime = strtotime($currentDate);
		$tmp             = date('mY', $CurrentDateTime);
		$year            = date('Y', $lastYearTime);

		// $months[] = array("month" => date('F', $lastYearTime), "year" => date('Y', $lastYearTime));

		while ($lastYearTime < $CurrentDateTime)
		{
			// Array to store months with 30 and 31 days
			$month31 = array(1, 3, 5, 7, 8, 10, 12);
			$month30 = array(4, 6, 9, 11);

			$month = date('m', $lastYearTime);

			if (array_search($month, $month31))
			{
				$lastYearTime = strtotime(date('Y-m-d', $lastYearTime) . ' +31 days');
			}
			elseif (array_search($month, $month30))
			{
				$lastYearTime = strtotime(date('Y-m-d', $lastYearTime) . ' +30 days');
			}
			else
			{
				if (((0 == $year % 4) && (0 != $year % 100)) || (0 == $year % 400))
				{
					$lastYearTime = strtotime(date('Y-m-d', $lastYearTime) . ' +29 days');
				}
				else
				{
					$lastYearTime = strtotime(date('Y-m-d', $lastYearTime) . ' +28 days');
				}
			}

			if (date('mY', $lastYearTime) != $tmp && ($lastYearTime < $CurrentDateTime))
			{
				$months[] = array(
					"month" => date('F', $lastYearTime),
					"year"  => date('Y', $lastYearTime),
				);
			}
		}

		$months[] = array("month" => date('F', $CurrentDateTime), "year" => date('Y', $CurrentDateTime));

		return $months;
	}

	/**
	 * If you want to use outsource javascript, and wants to use in multiple modules or plugins
	 *
	 * @param   string  $script  script name
	 *
	 * @return  void
	 *
	 * @since  1.6
	 */
	public static function loadScriptOnce($script)
	{
		$doc = Factory::getDocument();
		$flg = 0;

		foreach ($doc->_scripts as $name => $ar)
		{
			if ($name == $script)
			{
				$flg = 1;
			}
		}

		if ($flg == 0)
		{
			HTMLHelper::_('script', $script);
		}
	}

	/**
	 * Function to return extension version
	 *
	 * @param   string  $extensionType  Extension Type
	 *
	 * @param   string  $extensionName  Extesion Name
	 *
	 * @return  float
	 *
	 * @since  1.6
	 */
	public function getExtensionVersion($extensionType, $extensionName)
	{
		if (empty($extensionName) || empty($extensionType))
		{
			return false;
		}

		$db = Factory::getDbo();

		$query = $db->getQuery(true);

		$query->select($db->quoteName(array('name', 'manifest_cache')))
			->from($db->quoteName('#__extensions'))
			->where($db->quoteName('type') . ' = ' . $db->quote($extensionType))
			->where($db->quoteName('name') . ' = ' . $db->quote($extensionName));

		$db->setQuery($query);

		$extension = $db->loadObject();

		$decode = json_decode($extension->manifest_cache);

		return $decode->version;
	}
}
