<?php
/**
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @copyright   Copyright (C) 2016-2024 CMExension
 * @license     GNU General Public License version 2 or later
 */

defined('_JEXEC') or die;

use Joomla\CMS\Router\Route;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\MVC\View\GenericDataException;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Layout\FileLayout;

/**
 * Helper class for com_cmgiftcard.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardHelper
{
	/**
	 * Configure the Linkbar.
	 *
	 * @param   string  $vName  The name of the active view.
	 *
	 * @return  void
	 *
	 * @since   1.0.0
	 */
	public static function addSubmenu($vName)
	{
		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_DASHBOARD'),
			'index.php?option=com_cmgiftcard&view=dashboard',
			$vName == 'dashboard'
		);

		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_DESIGNS'),
			'index.php?option=com_cmgiftcard&view=designs',
			$vName == 'designs'
		);

		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_TEMPLATES'),
			'index.php?option=com_cmgiftcard&view=templates',
			$vName == 'templates'
		);

		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_ORDERS'),
			'index.php?option=com_cmgiftcard&view=orders',
			$vName == 'orders'
		);

		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_CARDS'),
			'index.php?option=com_cmgiftcard&view=cards',
			$vName == 'cards'
		);

		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_CODES'),
			'index.php?option=com_cmgiftcard&view=codes',
			$vName == 'codes'
		);

		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_SCANNER'),
			'index.php?option=com_cmgiftcard&view=scanner',
			$vName == 'scanner'
		);

		\JHtmlSidebar::addEntry(
			Text::_('COM_CMGIFTCARD_SUBMENU_TOOLS'),
			'index.php?option=com_cmgiftcard&view=tools',
			$vName == 'tools'
		);
	}

	/**
	 * Prepare route.
	 *
	 * @param   string   $url     URL
	 * @param   boolean  $jroute  Use JRoute
	 *
	 * @return  string
	 *
	 * @since   1.0.0
	 */
	public static function prepareRoute($url, $jroute = true)
	{
		$menu = Factory::getApplication()->getMenu();
		$uri = Uri::getInstance($url);
		$view = $uri->getVar('view');

		if ($view == 'card')
		{
			$item = $menu->getItems('link', 'index.php?option=com_cmgiftcard&view=card', true);

			if (empty($item))
			{
				$item = $menu->getItems('link', 'index.php?option=com_cmgiftcard&view=cards', true);
			}
		}
		elseif ($view == 'order')
		{
			$item = $menu->getItems('link', 'index.php?option=com_cmgiftcard&view=order', true);

			if (empty($item))
			{
				$item = $menu->getItems('link', 'index.php?option=com_cmgiftcard&view=orders', true);
			}
		}
		elseif ($view == 'form')
		{
			$type = $uri->getVar('type');
			$item = $menu->getItems('link', 'index.php?option=com_cmgiftcard&view=form&type=' . $type, true);

			if (empty($item))
			{
				$item = $menu->getItems('link', 'index.php?option=com_cmgiftcard&view=cart', true);
			}
		}
		else
		{
			$item = $menu->getItems('link', $url, true);
		}

		if (!empty($item))
		{
			$url .= '&Itemid=' . $item->id;
		}

		if ($jroute === true)
		{
			$url = Route::_($url, false);
		}

		return $url;
	}

	/**
	 * Return list of countries.
	 *
	 * @return  array
	 *
	 * @since   1.0.0
	 */
	public static function getCountries()
	{
		Factory::getLanguage()->load('com_cmgiftcard', JPATH_SITE . '/components/com_cmgiftcard', null, false, true);

		return array(
			"" => Text::_('COM_CMGIFTCARD_OPTION_SELECT_COUNTRY'),
			"united_states" => Text::_('COM_CMGIFTCARD_COUNTRIES_UNITED_STATES'),
			"afghanistan" => Text::_('COM_CMGIFTCARD_COUNTRIES_AFGHANISTAN'),
			"aland_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_ALAND_ISLANDS'),
			"albania" => Text::_('COM_CMGIFTCARD_COUNTRIES_ALBANIA'),
			"algeria" => Text::_('COM_CMGIFTCARD_COUNTRIES_ALGERIA'),
			"american_samoa" => Text::_('COM_CMGIFTCARD_COUNTRIES_AMERICAN_SAMOA'),
			"andorra" => Text::_('COM_CMGIFTCARD_COUNTRIES_ANDORRA'),
			"angola" => Text::_('COM_CMGIFTCARD_COUNTRIES_ANGOLA'),
			"anguilla" => Text::_('COM_CMGIFTCARD_COUNTRIES_ANGUILLA'),
			"antigua_and_barbuda" => Text::_('COM_CMGIFTCARD_COUNTRIES_ANTIGUA_AND_BARBUDA'),
			"argentina" => Text::_('COM_CMGIFTCARD_COUNTRIES_ARGENTINA'),
			"armenia" => Text::_('COM_CMGIFTCARD_COUNTRIES_ARMENIA'),
			"aruba" => Text::_('COM_CMGIFTCARD_COUNTRIES_ARUBA'),
			"australia" => Text::_('COM_CMGIFTCARD_COUNTRIES_AUSTRALIA'),
			"austria" => Text::_('COM_CMGIFTCARD_COUNTRIES_AUSTRIA'),
			"azerbaijan" => Text::_('COM_CMGIFTCARD_COUNTRIES_AZERBAIJAN'),
			"bahamas" => Text::_('COM_CMGIFTCARD_COUNTRIES_BAHAMAS'),
			"bahrain" => Text::_('COM_CMGIFTCARD_COUNTRIES_BAHRAIN'),
			"bangladesh" => Text::_('COM_CMGIFTCARD_COUNTRIES_BANGLADESH'),
			"barbados" => Text::_('COM_CMGIFTCARD_COUNTRIES_BARBADOS'),
			"belarus" => Text::_('COM_CMGIFTCARD_COUNTRIES_BELARUS'),
			"belgium" => Text::_('COM_CMGIFTCARD_COUNTRIES_BELGIUM'),
			"belize" => Text::_('COM_CMGIFTCARD_COUNTRIES_BELIZE'),
			"benin" => Text::_('COM_CMGIFTCARD_COUNTRIES_BENIN'),
			"bermuda" => Text::_('COM_CMGIFTCARD_COUNTRIES_BERMUDA'),
			"bhutan" => Text::_('COM_CMGIFTCARD_COUNTRIES_BHUTAN'),
			"bolivia" => Text::_('COM_CMGIFTCARD_COUNTRIES_BOLIVIA'),
			"bosnia_and_herzegowina" => Text::_('COM_CMGIFTCARD_COUNTRIES_BOSNIA_AND_HERZEGOWINA'),
			"botswana" => Text::_('COM_CMGIFTCARD_COUNTRIES_BOTSWANA'),
			"bouvet_island" => Text::_('COM_CMGIFTCARD_COUNTRIES_BOUVET_ISLAND'),
			"brazil" => Text::_('COM_CMGIFTCARD_COUNTRIES_BRAZIL'),
			"british_antarctic_territory" => Text::_('COM_CMGIFTCARD_COUNTRIES_BRITISH_ANTARCTIC_TERRITORY'),
			"british_indian_ocean_territory" => Text::_('COM_CMGIFTCARD_COUNTRIES_BRITISH_INDIAN_OCEAN_TERRITORY'),
			"brunei_darussalam" => Text::_('COM_CMGIFTCARD_COUNTRIES_BRUNEI_DARUSSALAM'),
			"bulgaria" => Text::_('COM_CMGIFTCARD_COUNTRIES_BULGARIA'),
			"burkina_faso" => Text::_('COM_CMGIFTCARD_COUNTRIES_BURKINA_FASO'),
			"burundi" => Text::_('COM_CMGIFTCARD_COUNTRIES_BURUNDI'),
			"cambodia" => Text::_('COM_CMGIFTCARD_COUNTRIES_CAMBODIA'),
			"cameroon" => Text::_('COM_CMGIFTCARD_COUNTRIES_CAMEROON'),
			"canada" => Text::_('COM_CMGIFTCARD_COUNTRIES_CANADA'),
			"canton__enderbury_i" => Text::_('COM_CMGIFTCARD_COUNTRIES_CANTON__ENDERBURY_I'),
			"cape_verde" => Text::_('COM_CMGIFTCARD_COUNTRIES_CAPE_VERDE'),
			"cayman_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_CAYMAN_ISLANDS'),
			"central_african_republic" => Text::_('COM_CMGIFTCARD_COUNTRIES_CENTRAL_AFRICAN_REPUBLIC'),
			"chad" => Text::_('COM_CMGIFTCARD_COUNTRIES_CHAD'),
			"chile" => Text::_('COM_CMGIFTCARD_COUNTRIES_CHILE'),
			"china" => Text::_('COM_CMGIFTCARD_COUNTRIES_CHINA'),
			"christmas_island" => Text::_('COM_CMGIFTCARD_COUNTRIES_CHRISTMAS_ISLAND'),
			"cocos_keeling_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_COCOS_KEELING_ISLANDS'),
			"colombia" => Text::_('COM_CMGIFTCARD_COUNTRIES_COLOMBIA'),
			"comoros" => Text::_('COM_CMGIFTCARD_COUNTRIES_COMOROS'),
			"congo_the_democratic_republic_of_the" => Text::_('COM_CMGIFTCARD_COUNTRIES_CONGO_THE_DEMOCRATIC_REPUBLIC_OF_THE'),
			"cook_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_COOK_ISLANDS'),
			"costa_rica" => Text::_('COM_CMGIFTCARD_COUNTRIES_COSTA_RICA'),
			"cote_divoire" => Text::_('COM_CMGIFTCARD_COUNTRIES_COTE_DIVOIRE'),
			"croatia" => Text::_('COM_CMGIFTCARD_COUNTRIES_CROATIA'),
			"cyprus" => Text::_('COM_CMGIFTCARD_COUNTRIES_CYPRUS'),
			"czech_republic" => Text::_('COM_CMGIFTCARD_COUNTRIES_CZECH_REPUBLIC'),
			"denmark" => Text::_('COM_CMGIFTCARD_COUNTRIES_DENMARK'),
			"djibouti" => Text::_('COM_CMGIFTCARD_COUNTRIES_DJIBOUTI'),
			"dominica" => Text::_('COM_CMGIFTCARD_COUNTRIES_DOMINICA'),
			"dominican_republic" => Text::_('COM_CMGIFTCARD_COUNTRIES_DOMINICAN_REPUBLIC'),
			"dronning_maud_land" => Text::_('COM_CMGIFTCARD_COUNTRIES_DRONNING_MAUD_LAND'),
			"ecuador" => Text::_('COM_CMGIFTCARD_COUNTRIES_ECUADOR'),
			"egypt" => Text::_('COM_CMGIFTCARD_COUNTRIES_EGYPT'),
			"el_salvador" => Text::_('COM_CMGIFTCARD_COUNTRIES_EL_SALVADOR'),
			"equatorial_guinea" => Text::_('COM_CMGIFTCARD_COUNTRIES_EQUATORIAL_GUINEA'),
			"eritrea" => Text::_('COM_CMGIFTCARD_COUNTRIES_ERITREA'),
			"estonia" => Text::_('COM_CMGIFTCARD_COUNTRIES_ESTONIA'),
			"ethiopia" => Text::_('COM_CMGIFTCARD_COUNTRIES_ETHIOPIA'),
			"falkland_islands_malvinas" => Text::_('COM_CMGIFTCARD_COUNTRIES_FALKLAND_ISLANDS_MALVINAS'),
			"faroe_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_FAROE_ISLANDS'),
			"fiji" => Text::_('COM_CMGIFTCARD_COUNTRIES_FIJI'),
			"finland" => Text::_('COM_CMGIFTCARD_COUNTRIES_FINLAND'),
			"france" => Text::_('COM_CMGIFTCARD_COUNTRIES_FRANCE'),
			"french_guiana" => Text::_('COM_CMGIFTCARD_COUNTRIES_FRENCH_GUIANA'),
			"french_polynesia" => Text::_('COM_CMGIFTCARD_COUNTRIES_FRENCH_POLYNESIA'),
			"french_southern_territories" => Text::_('COM_CMGIFTCARD_COUNTRIES_FRENCH_SOUTHERN_TERRITORIES'),
			"gabon" => Text::_('COM_CMGIFTCARD_COUNTRIES_GABON'),
			"gambia" => Text::_('COM_CMGIFTCARD_COUNTRIES_GAMBIA'),
			"georgia" => Text::_('COM_CMGIFTCARD_COUNTRIES_GEORGIA'),
			"germany" => Text::_('COM_CMGIFTCARD_COUNTRIES_GERMANY'),
			"ghana" => Text::_('COM_CMGIFTCARD_COUNTRIES_GHANA'),
			"gibraltar" => Text::_('COM_CMGIFTCARD_COUNTRIES_GIBRALTAR'),
			"gilbert_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_GILBERT_ISLANDS'),
			"greece" => Text::_('COM_CMGIFTCARD_COUNTRIES_GREECE'),
			"greenland" => Text::_('COM_CMGIFTCARD_COUNTRIES_GREENLAND'),
			"grenada" => Text::_('COM_CMGIFTCARD_COUNTRIES_GRENADA'),
			"guadeloupe" => Text::_('COM_CMGIFTCARD_COUNTRIES_GUADELOUPE'),
			"guam" => Text::_('COM_CMGIFTCARD_COUNTRIES_GUAM'),
			"guatemala" => Text::_('COM_CMGIFTCARD_COUNTRIES_GUATEMALA'),
			"guernsey" => Text::_('COM_CMGIFTCARD_COUNTRIES_GUERNSEY'),
			"guinea" => Text::_('COM_CMGIFTCARD_COUNTRIES_GUINEA'),
			"guineabissau" => Text::_('COM_CMGIFTCARD_COUNTRIES_GUINEABISSAU'),
			"guyana" => Text::_('COM_CMGIFTCARD_COUNTRIES_GUYANA'),
			"haiti" => Text::_('COM_CMGIFTCARD_COUNTRIES_HAITI'),
			"heard_and_mcdonald_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_HEARD_AND_MCDONALD_ISLANDS'),
			"honduras" => Text::_('COM_CMGIFTCARD_COUNTRIES_HONDURAS'),
			"hong_kong" => Text::_('COM_CMGIFTCARD_COUNTRIES_HONG_KONG'),
			"hungary" => Text::_('COM_CMGIFTCARD_COUNTRIES_HUNGARY'),
			"iceland" => Text::_('COM_CMGIFTCARD_COUNTRIES_ICELAND'),
			"india" => Text::_('COM_CMGIFTCARD_COUNTRIES_INDIA'),
			"indonesia" => Text::_('COM_CMGIFTCARD_COUNTRIES_INDONESIA'),
			"iraq" => Text::_('COM_CMGIFTCARD_COUNTRIES_IRAQ'),
			"ireland" => Text::_('COM_CMGIFTCARD_COUNTRIES_IRELAND'),
			"isle_of_man" => Text::_('COM_CMGIFTCARD_COUNTRIES_ISLE_OF_MAN'),
			"israel" => Text::_('COM_CMGIFTCARD_COUNTRIES_ISRAEL'),
			"italy" => Text::_('COM_CMGIFTCARD_COUNTRIES_ITALY'),
			"jamaica" => Text::_('COM_CMGIFTCARD_COUNTRIES_JAMAICA'),
			"japan" => Text::_('COM_CMGIFTCARD_COUNTRIES_JAPAN'),
			"jersey" => Text::_('COM_CMGIFTCARD_COUNTRIES_JERSEY'),
			"johnston_island" => Text::_('COM_CMGIFTCARD_COUNTRIES_JOHNSTON_ISLAND'),
			"jordan" => Text::_('COM_CMGIFTCARD_COUNTRIES_JORDAN'),
			"kazakhstan" => Text::_('COM_CMGIFTCARD_COUNTRIES_KAZAKHSTAN'),
			"kenya" => Text::_('COM_CMGIFTCARD_COUNTRIES_KENYA'),
			"kiribati" => Text::_('COM_CMGIFTCARD_COUNTRIES_KIRIBATI'),
			"kuwait" => Text::_('COM_CMGIFTCARD_COUNTRIES_KUWAIT'),
			"kyrgyzstan" => Text::_('COM_CMGIFTCARD_COUNTRIES_KYRGYZSTAN'),
			"lao_peoples_democratic_republic" => Text::_('COM_CMGIFTCARD_COUNTRIES_LAO_PEOPLES_DEMOCRATIC_REPUBLIC'),
			"latvia" => Text::_('COM_CMGIFTCARD_COUNTRIES_LATVIA'),
			"lebanon" => Text::_('COM_CMGIFTCARD_COUNTRIES_LEBANON'),
			"lesotho" => Text::_('COM_CMGIFTCARD_COUNTRIES_LESOTHO'),
			"liberia" => Text::_('COM_CMGIFTCARD_COUNTRIES_LIBERIA'),
			"libyan_arab_jamahiriya" => Text::_('COM_CMGIFTCARD_COUNTRIES_LIBYAN_ARAB_JAMAHIRIYA'),
			"liechtenstein" => Text::_('COM_CMGIFTCARD_COUNTRIES_LIECHTENSTEIN'),
			"lithuania" => Text::_('COM_CMGIFTCARD_COUNTRIES_LITHUANIA'),
			"luxembourg" => Text::_('COM_CMGIFTCARD_COUNTRIES_LUXEMBOURG'),
			"macau" => Text::_('COM_CMGIFTCARD_COUNTRIES_MACAU'),
			"macedonia" => Text::_('COM_CMGIFTCARD_COUNTRIES_MACEDONIA'),
			"madagascar" => Text::_('COM_CMGIFTCARD_COUNTRIES_MADAGASCAR'),
			"malawi" => Text::_('COM_CMGIFTCARD_COUNTRIES_MALAWI'),
			"malaysia" => Text::_('COM_CMGIFTCARD_COUNTRIES_MALAYSIA'),
			"maldives" => Text::_('COM_CMGIFTCARD_COUNTRIES_MALDIVES'),
			"mali" => Text::_('COM_CMGIFTCARD_COUNTRIES_MALI'),
			"malta" => Text::_('COM_CMGIFTCARD_COUNTRIES_MALTA'),
			"marshall_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_MARSHALL_ISLANDS'),
			"martinique" => Text::_('COM_CMGIFTCARD_COUNTRIES_MARTINIQUE'),
			"mauritania" => Text::_('COM_CMGIFTCARD_COUNTRIES_MAURITANIA'),
			"mauritius" => Text::_('COM_CMGIFTCARD_COUNTRIES_MAURITIUS'),
			"mexico" => Text::_('COM_CMGIFTCARD_COUNTRIES_MEXICO'),
			"micronesia" => Text::_('COM_CMGIFTCARD_COUNTRIES_MICRONESIA'),
			"midway_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_MIDWAY_ISLANDS'),
			"moldova" => Text::_('COM_CMGIFTCARD_COUNTRIES_MOLDOVA'),
			"monaco" => Text::_('COM_CMGIFTCARD_COUNTRIES_MONACO'),
			"mongolia" => Text::_('COM_CMGIFTCARD_COUNTRIES_MONGOLIA'),
			"montenegro" => Text::_('COM_CMGIFTCARD_COUNTRIES_MONTENEGRO'),
			"montserrat" => Text::_('COM_CMGIFTCARD_COUNTRIES_MONTSERRAT'),
			"morocco" => Text::_('COM_CMGIFTCARD_COUNTRIES_MOROCCO'),
			"mozambique" => Text::_('COM_CMGIFTCARD_COUNTRIES_MOZAMBIQUE'),
			"namibia" => Text::_('COM_CMGIFTCARD_COUNTRIES_NAMIBIA'),
			"nauru" => Text::_('COM_CMGIFTCARD_COUNTRIES_NAURU'),
			"nepal" => Text::_('COM_CMGIFTCARD_COUNTRIES_NEPAL'),
			"netherlands" => Text::_('COM_CMGIFTCARD_COUNTRIES_NETHERLANDS'),
			"netherlands_antilles" => Text::_('COM_CMGIFTCARD_COUNTRIES_NETHERLANDS_ANTILLES'),
			"new_caledonia" => Text::_('COM_CMGIFTCARD_COUNTRIES_NEW_CALEDONIA'),
			"new_hebrides" => Text::_('COM_CMGIFTCARD_COUNTRIES_NEW_HEBRIDES'),
			"new_zealand" => Text::_('COM_CMGIFTCARD_COUNTRIES_NEW_ZEALAND'),
			"nicaragua" => Text::_('COM_CMGIFTCARD_COUNTRIES_NICARAGUA'),
			"niger" => Text::_('COM_CMGIFTCARD_COUNTRIES_NIGER'),
			"nigeria" => Text::_('COM_CMGIFTCARD_COUNTRIES_NIGERIA'),
			"norfolk_island" => Text::_('COM_CMGIFTCARD_COUNTRIES_NORFOLK_ISLAND'),
			"northern_mariana_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_NORTHERN_MARIANA_ISLANDS'),
			"norway" => Text::_('COM_CMGIFTCARD_COUNTRIES_NORWAY'),
			"oman" => Text::_('COM_CMGIFTCARD_COUNTRIES_OMAN'),
			"pakistan" => Text::_('COM_CMGIFTCARD_COUNTRIES_PAKISTAN'),
			"palau" => Text::_('COM_CMGIFTCARD_COUNTRIES_PALAU'),
			"palestinian_territory_occupied" => Text::_('COM_CMGIFTCARD_COUNTRIES_PALESTINIAN_TERRITORY_OCCUPIED'),
			"panama" => Text::_('COM_CMGIFTCARD_COUNTRIES_PANAMA'),
			"papua_new_guinea" => Text::_('COM_CMGIFTCARD_COUNTRIES_PAPUA_NEW_GUINEA'),
			"paraguay" => Text::_('COM_CMGIFTCARD_COUNTRIES_PARAGUAY'),
			"peru" => Text::_('COM_CMGIFTCARD_COUNTRIES_PERU'),
			"philippines" => Text::_('COM_CMGIFTCARD_COUNTRIES_PHILIPPINES'),
			"pitcairn" => Text::_('COM_CMGIFTCARD_COUNTRIES_PITCAIRN'),
			"poland" => Text::_('COM_CMGIFTCARD_COUNTRIES_POLAND'),
			"portugal" => Text::_('COM_CMGIFTCARD_COUNTRIES_PORTUGAL'),
			"puerto_rico" => Text::_('COM_CMGIFTCARD_COUNTRIES_PUERTO_RICO'),
			"qatar" => Text::_('COM_CMGIFTCARD_COUNTRIES_QATAR'),
			"reunion" => Text::_('COM_CMGIFTCARD_COUNTRIES_REUNION'),
			"romania" => Text::_('COM_CMGIFTCARD_COUNTRIES_ROMANIA'),
			"russia" => Text::_('COM_CMGIFTCARD_COUNTRIES_RUSSIA'),
			"rwanda" => Text::_('COM_CMGIFTCARD_COUNTRIES_RWANDA'),
			"saint_barthelemy" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAINT_BARTHELEMY'),
			"saint_kitts_and_nevis" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAINT_KITTS_AND_NEVIS'),
			"saint_lucia" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAINT_LUCIA'),
			"saint_martin_french_portion" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAINT_MARTIN_FRENCH_PORTION'),
			"saint_vincent_and_the_grenadines" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAINT_VINCENT_AND_THE_GRENADINES'),
			"saipan" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAIPAN'),
			"samoa" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAMOA'),
			"san_marino" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAN_MARINO'),
			"sao_tome_and_principe" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAO_TOME_AND_PRINCIPE'),
			"saudi_arabia" => Text::_('COM_CMGIFTCARD_COUNTRIES_SAUDI_ARABIA'),
			"scotland" => Text::_('COM_CMGIFTCARD_COUNTRIES_SCOTLAND'),
			"senegal" => Text::_('COM_CMGIFTCARD_COUNTRIES_SENEGAL'),
			"serbia_republic_of_serbia" => Text::_('COM_CMGIFTCARD_COUNTRIES_SERBIA_REPUBLIC_OF_SERBIA'),
			"seychelles" => Text::_('COM_CMGIFTCARD_COUNTRIES_SEYCHELLES'),
			"sierra_leone" => Text::_('COM_CMGIFTCARD_COUNTRIES_SIERRA_LEONE'),
			"singapore" => Text::_('COM_CMGIFTCARD_COUNTRIES_SINGAPORE'),
			"slovakia" => Text::_('COM_CMGIFTCARD_COUNTRIES_SLOVAKIA'),
			"slovenia" => Text::_('COM_CMGIFTCARD_COUNTRIES_SLOVENIA'),
			"solomon_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_SOLOMON_ISLANDS'),
			"somalia" => Text::_('COM_CMGIFTCARD_COUNTRIES_SOMALIA'),
			"south_africa" => Text::_('COM_CMGIFTCARD_COUNTRIES_SOUTH_AFRICA'),
			"south_georgia_and_the_south_sandwich_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS'),
			"south_korea" => Text::_('COM_CMGIFTCARD_COUNTRIES_SOUTH_KOREA'),
			"southern_rhodesia" => Text::_('COM_CMGIFTCARD_COUNTRIES_SOUTHERN_RHODESIA'),
			"spain" => Text::_('COM_CMGIFTCARD_COUNTRIES_SPAIN'),
			"sri_lanka" => Text::_('COM_CMGIFTCARD_COUNTRIES_SRI_LANKA'),
			"st_helena" => Text::_('COM_CMGIFTCARD_COUNTRIES_ST_HELENA'),
			"st_pierre_and_miquelon" => Text::_('COM_CMGIFTCARD_COUNTRIES_ST_PIERRE_AND_MIQUELON'),
			"suriname" => Text::_('COM_CMGIFTCARD_COUNTRIES_SURINAME'),
			"svalbard_and_jan_mayen_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_SVALBARD_AND_JAN_MAYEN_ISLANDS'),
			"swaziland" => Text::_('COM_CMGIFTCARD_COUNTRIES_SWAZILAND'),
			"switzerland" => Text::_('COM_CMGIFTCARD_COUNTRIES_SWITZERLAND'),
			"taiwan" => Text::_('COM_CMGIFTCARD_COUNTRIES_TAIWAN'),
			"tajikistan" => Text::_('COM_CMGIFTCARD_COUNTRIES_TAJIKISTAN'),
			"tanzania_united_republic" => Text::_('COM_CMGIFTCARD_COUNTRIES_TANZANIA_UNITED_REPUBLIC'),
			"thailand" => Text::_('COM_CMGIFTCARD_COUNTRIES_THAILAND'),
			"timorleste" => Text::_('COM_CMGIFTCARD_COUNTRIES_TIMORLESTE'),
			"togo" => Text::_('COM_CMGIFTCARD_COUNTRIES_TOGO'),
			"tokelau" => Text::_('COM_CMGIFTCARD_COUNTRIES_TOKELAU'),
			"tonga" => Text::_('COM_CMGIFTCARD_COUNTRIES_TONGA'),
			"trinidad_and_tobago" => Text::_('COM_CMGIFTCARD_COUNTRIES_TRINIDAD_AND_TOBAGO'),
			"tunisia" => Text::_('COM_CMGIFTCARD_COUNTRIES_TUNISIA'),
			"turkey" => Text::_('COM_CMGIFTCARD_COUNTRIES_TURKEY'),
			"turkmenistan" => Text::_('COM_CMGIFTCARD_COUNTRIES_TURKMENISTAN'),
			"turks_and_caicos_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_TURKS_AND_CAICOS_ISLANDS'),
			"tuvalu" => Text::_('COM_CMGIFTCARD_COUNTRIES_TUVALU'),
			"uganda" => Text::_('COM_CMGIFTCARD_COUNTRIES_UGANDA'),
			"ukraine" => Text::_('COM_CMGIFTCARD_COUNTRIES_UKRAINE'),
			"united_arab_emirates" => Text::_('COM_CMGIFTCARD_COUNTRIES_UNITED_ARAB_EMIRATES'),
			"united_kingdom" => Text::_('COM_CMGIFTCARD_COUNTRIES_UNITED_KINGDOM'),
			"uruguay" => Text::_('COM_CMGIFTCARD_COUNTRIES_URUGUAY'),
			"uzbekistan" => Text::_('COM_CMGIFTCARD_COUNTRIES_UZBEKISTAN'),
			"vanuatu" => Text::_('COM_CMGIFTCARD_COUNTRIES_VANUATU'),
			"venezuela" => Text::_('COM_CMGIFTCARD_COUNTRIES_VENEZUELA'),
			"vietnam" => Text::_('COM_CMGIFTCARD_COUNTRIES_VIETNAM'),
			"virgin_islands_british" => Text::_('COM_CMGIFTCARD_COUNTRIES_VIRGIN_ISLANDS_BRITISH'),
			"wake_island" => Text::_('COM_CMGIFTCARD_COUNTRIES_WAKE_ISLAND'),
			"wallis_and_futuna_islands" => Text::_('COM_CMGIFTCARD_COUNTRIES_WALLIS_AND_FUTUNA_ISLANDS'),
			"west_indies" => Text::_('COM_CMGIFTCARD_COUNTRIES_WEST_INDIES'),
			"western_sahara" => Text::_('COM_CMGIFTCARD_COUNTRIES_WESTERN_SAHARA'),
			"yemen" => Text::_('COM_CMGIFTCARD_COUNTRIES_YEMEN'),
			"yugoslavia" => Text::_('COM_CMGIFTCARD_COUNTRIES_YUGOSLAVIA'),
			"zaire" => Text::_('COM_CMGIFTCARD_COUNTRIES_ZAIRE'),
			"zambia" => Text::_('COM_CMGIFTCARD_COUNTRIES_ZAMBIA'),
			"zimbabwe" => Text::_('COM_CMGIFTCARD_COUNTRIES_ZIMBABWE'),
		);
	}

	/**
	 * Send email for successful order.
	 *
	 * @param   integer  $orderId  Order ID.
	 *
	 * @return  boolean
	 *
	 * @since   1.0.0
	 */
	public static function sendOrderEmail($orderId)
	{
		$app = Factory::getApplication();
		$db = Factory::getDbo();
		$order = self::getOrder($orderId);
		$template = self::getMailTemplate('order_success');

		if (!isset($order->id) || !isset($template->id) || $order->order_status != 'paid')
			return false;

		PluginHelper::importPlugin('cmgiftcard');

		$payments = $app->triggerEvent('onCMGCGetPaymentIdentity');
		$paymentMethod = '';

		if (count($payments))
		{
			foreach ($payments as $payment)
			{
				if ($payment['id'] == $order->payment_method)
				{
					$paymentMethod = $payment['name'];
					break;
				}
			}
		}

		$emailSubject = $template->subject;
		$emailBody = $template->body;

		$completed = $order->completed ? HTMLHelper::_('date', $order->completed, 'DATE_FORMAT_LC2') : '';
		$amount = $order->amount ? HTMLHelper::_('cmgiftcard.formatPrice', $order->amount) : '';

		$mailTags = array(
			'{first_name}'		=> $order->first_name,
			'{last_name}'		=> $order->last_name,
			'{completed_date}'	=> $completed,
			'{order_amount}'	=> $amount,
			'{order_number}'	=> $order->order_number,
			'{payment_method}'	=> $paymentMethod,
			'{transaction_id}'	=> $order->transaction_id,
		);

		foreach ($mailTags as $tag => $value)
		{
			$emailSubject = str_replace($tag, $value, $emailSubject);
			$emailBody = str_replace($tag, $value, $emailBody);
		}

		$params = ComponentHelper::getParams('com_cmgiftcard');

		$attachInvoice = $params->get('attach_invoice', 0);
		$filePath = '';

		if ($attachInvoice)
		{
			jimport('mpdf.mpdf');
			$attachInvoice = class_exists('\Mpdf\Mpdf') ? true : false;
		}

		if ($attachInvoice)
		{
			$invoiceHtml = $params->get('invoice_template');
			$folderPath = $app->get('tmp_path');
			$fileName = 'invoice-' . $order->order_number . '.pdf';
			$filePath = $folderPath . '/' . $fileName;

			$orderDate = ($order->completed != null) ? HTMLHelper::_('date', $order->completed, 'DATE_FORMAT_LC2') : '';

			if (File::exists(JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts/invoice_items_custom.php'))
			{
				$layoutName = 'invoice_items_custom';
			}
			else
			{
				$layoutName = 'invoice_items';
			}

			$query = $db->getQuery(true)
				->select($db->qn('c') . '.*')
				->select($db->qn('d.title') . ' AS design_title')
				->from($db->qn('#__cmgiftcard_cards', 'c'))
				->where($db->qn('c.order_id') . ' = ' . $db->q((int) $order->id))
				->join('LEFT', $db->qn('#__cmgiftcard_designs') . ' AS d ON ' . $db->qn('d.id') . ' = ' . $db->qn('c.design_id'));
			$cards = $db->setQuery($query)->loadObjectList();

			$layout = new FileLayout($layoutName, JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts');
			$orderItems = $layout->render(array('cards' => $cards));
			$countries = self::getCountries();
			$country = isset($countries[$order->country]) ? $countries[$order->country] : '';

			$invoiceTags = array(
				'{customer_name}'			=> $order->first_name . ' ' . $order->last_name,
				'{customer_email}'			=> $order->email,
				'{customer_address_1}'		=> $order->address_1,
				'{customer_address_2}'		=> $order->address_2,
				'{customer_address_3}'		=> $order->address_3,
				'{customer_postal_box}'		=> $order->postal_box,
				'{customer_city}'			=> $order->city,
				'{customer_state}'			=> $order->state,
				'{customer_postal_code}'	=> $order->postal_code,
				'{customer_country}'		=> $country,
				'{order_number}'			=> $order->order_number,
				'{order_date}'				=> $orderDate,
				'{payment_method}'			=> $paymentMethod,
				'{transaction_id}'			=> $order->transaction_id,
				'{order_items}'				=> $orderItems,
			);

			foreach ($invoiceTags as $tag => $value)
			{
				$invoiceHtml = str_replace($tag, $value, $invoiceHtml);
			}

			$mpdf = new \Mpdf\Mpdf([
				'mode'	=> 'utf-8',
				'format'=> 'A4'
			]);

			$mpdf->WriteHTML($invoiceHtml);
			$mpdf->Output($filePath, 'F');
		}

		$mail = Factory::getMailer();
		$mail->setSender(
				array(
					$app->get('mailfrom'),
					$app->get('fromname')
				)
			)
			->addRecipient($order->email)
			->setSubject($emailSubject)
			->setBody($emailBody)
			->isHtml(true);

		if ($attachInvoice && File::exists($filePath))
		{
			$mail->addAttachment($filePath, $fileName);
		}

		$sent = $mail->send();

		if ($sent && $params->get('send_copy', 0))
		{
			$query = $db->getQuery(true)
				->select($db->qn(array('name', 'email', 'sendEmail', 'id')))
				->from($db->qn('#__users'))
				->where($db->qn('sendEmail') . ' = ' . $db->q(1));

			$admins = $db->setQuery($query)->loadObjectList();

			if (count($admins))
			{
				$emailSubject = $params->get('copy_prefix') . $emailSubject;

				foreach ($admins as $admin)
				{
						$mail = Factory::getMailer();
						$mail->setSender(
							array(
								$app->get('mailfrom'),
								$app->get('fromname')
							)
						)
						->addRecipient($admin->email)
						->setSubject($emailSubject)
						->setBody($emailBody)
						->isHtml(true);

					if ($attachInvoice && File::exists($filePath))
					{
						$mail->addAttachment($filePath, $fileName);
					}

					$sent = $mail->send();
				}
			}
		}

		if ($filePath != '' && File::exists($filePath))
		{
			File::delete($filePath);
		}

		return $sent;
	}

	/**
	 * Send gift card email for electronic gift card.
	 *
	 * @param   integer  $orderId  Order ID.
	 *
	 * @return  void
	 *
	 * @since   1.2.0
	 */
	public static function sendElectronicCardEmail($orderId)
	{
		require_once JPATH_ROOT . '/administrator/components/com_cmgiftcard/helpers/html/cmgiftcard.php';

		$db = Factory::getDbo();

		$query = $db->getQuery(true)
			->select('a.*')
			->from($db->qn('#__cmgiftcard_cards') . ' AS a')
			->where($db->qn('a.delivered') . ' IS NULL')
			->where($db->qn('d.card_type') . ' = ' . $db->q('electronic'))
			->where($db->qn('o.order_status') . ' = ' . $db->q('paid'));

		$query
			->select($db->qn('o.first_name') . ' AS sender_first_name')
			->select($db->qn('o.last_name') . ' AS sender_last_name')
			->select($db->qn('o.email') . ' AS sender_email')
			->select($db->qn('o.created') . ' AS created')
			->select($db->qn('o.completed') . ' AS completed')
			->select($db->qn('o.order_number') . ' AS order_number')
			->select($db->qn('o.order_status') . ' AS order_status')
			->join('LEFT', $db->qn('#__cmgiftcard_orders') . ' AS o ON '
				. $db->qn('o.id') . ' = ' . $db->qn('a.order_id')
			)
			->where($db->qn('o.id') . ' = ' . $db->q($orderId));

		$query->select($db->qn('d.image') . ' AS design_image')
			->select($db->qn('d.card_type') . ' AS card_type')
			->join('LEFT', $db->qn('#__cmgiftcard_designs') . ' AS d ON '
				. $db->qn('d.id') . ' = ' . $db->qn('a.design_id')
			);

		$amountSubQuery = $db->getQuery(true)
			->select('SUM(' . $db->qn('c.amount') . ')')
			->from($db->qn('#__cmgiftcard_cards') . ' AS c')
			->where($db->qn('c.order_id') . ' = ' . $db->qn('o.id'));

		$query->select('(' . $amountSubQuery . ') AS order_amount');

		$cards = $db->setQuery($query)->loadObjectList();

		if (count($cards))
		{
			$params = ComponentHelper::getParams('com_cmgiftcard');
			$canSelectDate = $params->get('electronic_date_selection', 0);

			if ($canSelectDate)
			{
				$date = Factory::getDate('now', 'UTC');
				$now = $date->format('Y-m-d', true, false);

				foreach ($cards as $card)
				{
					if ($now == $card->deliver_date)
					{
						self::sendGiftCardEmail($card);
					}
				}
			}
			else
			{
				foreach ($cards as $card)
				{
					self::sendGiftCardEmail($card);
				}
			}
		}
	}

	/**
	 * Send notification emails to admins for new physical gift card.
	 *
	 * @param   integer  $orderId  Order ID.
	 *
	 * @return  void
	 *
	 * @since   1.2.0
	 */
	public static function sendPhysicalCardEmail($orderId)
	{
		$params = ComponentHelper::getParams('com_cmgiftcard');
		$sendEmail = $params->get('send_physical_email', 0);

		if (!$sendEmail)
			return;

		$order = self::getOrder($orderId);
		$template = self::getMailTemplate('physical_admin');

		if (!isset($order->id) || !isset($template->id))
			return;

		require_once JPATH_ROOT . '/administrator/components/com_cmgiftcard/helpers/html/cmgiftcard.php';

		$app = Factory::getApplication();
		$db = Factory::getDbo();

		$query = $db->getQuery(true)
			->select('a.*')
			->from($db->qn('#__cmgiftcard_cards') . ' AS a');

		$query
			->join('LEFT', $db->qn('#__cmgiftcard_orders') . ' AS o ON '
				. $db->qn('o.id') . ' = ' . $db->qn('a.order_id')
			)
			->where($db->qn('o.id') . ' = ' . $db->q($orderId))
			->where($db->qn('o.order_status') . ' = ' . $db->q('paid'));

		$query->select($db->qn('d.card_type') . ' AS card_type')
			->join('LEFT', $db->qn('#__cmgiftcard_designs') . ' AS d ON '
				. $db->qn('d.id') . ' = ' . $db->qn('a.design_id')
			)
			->where($db->qn('d.card_type') . ' = ' . $db->q('physical'));

		$amountSubQuery = $db->getQuery(true)
			->select('SUM(' . $db->qn('c.amount') . ')')
			->from($db->qn('#__cmgiftcard_cards') . ' AS c')
			->where($db->qn('c.order_id') . ' = ' . $db->q($orderId));

		$query->select('(' . $amountSubQuery . ') AS order_amount');

		$cards = $db->setQuery($query)->loadObjectList();

		$adminQuery = $db->getQuery(true)
			->select($db->qn(array('name', 'email', 'sendEmail', 'id')))
			->from($db->qn('#__users'))
			->where($db->qn('sendEmail') . ' = ' . $db->q(1));

		$admins = $db->setQuery($adminQuery)->loadObjectList();

		if (!count($cards) || !count($admins))
			return;

		$config = Factory::getConfig();

		$payments = $app->triggerEvent('onCMGCGetPaymentIdentity');
		$paymentMethod = '';

		if (count($payments))
		{
			foreach ($payments as $payment)
			{
				if ($payment['id'] == $order->payment_method)
				{
					$paymentMethod = $payment['name'];
					break;
				}
			}
		}

		foreach ($cards as $card)
		{
			$emailSubject = $template->subject;
			$emailBody = $template->body;

			$completed = $order->completed ? HTMLHelper::_('date', $order->completed, 'DATE_FORMAT_LC2') : '';
			$amount = $card->order_amount ? HTMLHelper::_('cmgiftcard.formatPrice', $card->order_amount) : '';

			$mailTags = array(
				'{gift_card_code}'			=> $card->card_code,
				'{gift_card_amount}'		=> HTMLHelper::_('cmgiftcard.formatPrice', $card->amount),
				'{order_number}'			=> $order->order_number,
				'{completed_date}'			=> $completed,
				'{order_amount}'			=> $amount,
				'{payment_method}'			=> $paymentMethod,
				'{transaction_id}'			=> $order->transaction_id,
				'{sender_name}'				=> !empty($card->from_name) ? $card->from_name : $order->first_name . ' ' . $order->last_name,
				'{recipient_name}'			=> $card->to_name,
				'{recipient_email}'			=> $card->to_email,
				'{recipient_address_1}'		=> $card->to_address_1,
				'{recipient_address_2}'		=> $card->to_address_2,
				'{recipient_address_3}'		=> $card->to_address_3,
				'{recipient_postal_box}'	=> $card->to_postal_box,
				'{recipient_city}'			=> $card->to_city,
				'{recipient_state}'			=> $card->to_state,
				'{recipient_postal_code}'	=> $card->to_postal_code,
				'{recipient_country}'		=> $card->to_country,
				'{gift_card_message}'		=> $card->message,
			);

			foreach ($mailTags as $tag => $value)
			{
				$emailSubject = str_replace($tag, $value, $emailSubject);
				$emailBody = str_replace($tag, $value, $emailBody);
			}

			foreach ($admins as $admin)
			{
				$mail = Factory::getMailer();
				$mail->setSender(
					array(
						$config->get('mailfrom'),
						$config->get('fromname')
					)
				)
				->addRecipient($admin->email)
				->setSubject($emailSubject)
				->setBody($emailBody)
				->isHtml(true);

				$mail->send();
			}
		}
	}

	/**
	 * Send email for electronic gift card
	 *
	 * @param   object  $card  Gift card.
	 *
	 * @return  boolean
	 *
	 * @since   1.0.0
	 */
	public static function sendGiftCardEmail($card)
	{
		require_once JPATH_ROOT . '/administrator/components/com_cmgiftcard/helpers/html/cmgiftcard.php';

		$config = Factory::getConfig();
		$params = ComponentHelper::getParams('com_cmgiftcard');
		$sent = false;
		$recipientTemplate = self::getMailTemplate('gift_card_recipient');
		$db = Factory::getDbo();
		$folderPath = $config->get('tmp_path');
		$fileName = $card->card_code . '.pdf';
		$filePath = $folderPath . '/' . $fileName;

		$pdfGiftCard = $params->get('electronic_pdf', 0);

		if ($pdfGiftCard)
		{
			jimport('mpdf.mpdf');
			$pdfGiftCard = class_exists('\Mpdf\Mpdf') ? true : false;
		}

		if (isset($card->id) && isset($recipientTemplate->id))
		{
			$emailSubject = $recipientTemplate->subject;
			$emailBody = $recipientTemplate->body;

			$cardImage = Uri::root() . self::getImageUrl($card->design_image);
			$cardImage = '<img src="' . $cardImage . '" style="width: 100%;">';

			$created = $card->created ? HTMLHelper::_('date', $card->created, 'DATE_FORMAT_LC2') : '';
			$completed = $card->completed ? HTMLHelper::_('date', $card->completed, 'DATE_FORMAT_LC2') : '';

			$mailTags = [
				'{sender_name}'			=> $card->from_name,
				'{recipient_name}'		=> $card->to_name,
				'{gift_card_image}'		=> $cardImage,
				'{gift_card_amount}'	=> HTMLHelper::_('cmgiftcard.formatPrice', $card->amount),
				'{gift_card_code}'		=> $card->card_code,
				'{gift_card_message}'	=> $card->message,
				'{order_date}'			=> $created,
				'{completed_date}'		=> $completed,
			];

			foreach ($mailTags as $tag => $value)
			{
				$emailSubject = str_replace($tag, $value, $emailSubject);
				$emailBody = str_replace($tag, $value, $emailBody);
			}

			$mail = Factory::getMailer();
			$mail->setSender([
					$config->get('mailfrom'),
					$config->get('fromname')
				])
				->addRecipient($card->to_email)
				->setSubject($emailSubject)
				->setBody($emailBody)
				->isHtml(true);

			if ($pdfGiftCard)
			{
				$pdfTags = $mailTags;
				$cardImagePath = JPATH_ROOT . '/' . str_replace('%20', ' ', CMGiftCardHelper::getImageUrl($card->design_image));
				$qrCodeSize = (int) $params->get('pdf_qrcode_size', 2);
				$qrCode = '<barcode code="' . $card->card_code . '" type="QR" class="barcode" size="' . $qrCodeSize . '" error="M" disableborder="1" />';

				$pdfTags['{gift_card_image}'] = '<img src="var:cardImage" style="width: 100%;">';
				$pdfTags['{gift_card_qr_code}'] = $qrCode;

				$giftCardContent = $params->get('electronic_pdf_template');

				foreach ($pdfTags as $tag => $value)
				{
					$giftCardContent = str_replace($tag, $value, $giftCardContent);
				}

				$tmpPath = Factory::getApplication()->get('tmp_path');

				$mpdf = new \Mpdf\Mpdf([
					'mode'	=> 'utf-8',
					'format'=> 'A4',
					'tempDir' => $tmpPath
				]);

				$mpdf->imageVars['cardImage'] = file_get_contents($cardImagePath);
				$mpdf->WriteHTML($giftCardContent);
				$mpdf->Output($filePath, 'F');
				$mail->addAttachment($filePath, $fileName);
			}

			$sent = $mail->send();

			if ($sent)
			{
				$query = $db->getQuery(true)
					->update($db->qn('#__cmgiftcard_cards'))
					->set($db->qn('delivered') . ' = ' . $db->q(Factory::getDate()->format('Y-m-d H:i:s')))
					->where($db->qn('id') . ' = ' . $db->q($card->id));

				$db->setQuery($query)->execute();
			}

			if ($sent && $params->get('send_copy', 0))
			{
				$query = $db->getQuery(true)
					->select($db->qn(array('name', 'email', 'sendEmail', 'id')))
					->from($db->qn('#__users'))
					->where($db->qn('sendEmail') . ' = ' . $db->q(1));

				$admins = $db->setQuery($query)->loadObjectList();

				if (count($admins))
				{
					$emailSubject = $params->get('copy_prefix') . $emailSubject;

					foreach ($admins as $admin)
					{
						$mail = Factory::getMailer();
						$mail->setSender(
							array(
								$config->get('mailfrom'),
								$config->get('fromname')
							)
						)
						->addRecipient($admin->email)
						->setSubject($emailSubject)
						->setBody($emailBody)
						->isHtml(true);

						if ($pdfGiftCard && File::exists($filePath))
						{
							$mail->addAttachment($filePath, $fileName);
						}

						$mail->send();
					}
				}
			}

			if ($sent)
			{
				$senderTemplate = self::getMailTemplate('gift_card_sender');

				if (isset($template->id))
				{
					$emailSubject = $senderTemplate->subject;
					$emailBody = $senderTemplate->body;

					$created = $card->created ? HTMLHelper::_('date', $card->created, 'DATE_FORMAT_LC2') : '';
					$completed = $card->completed ? HTMLHelper::_('date', $card->completed, 'DATE_FORMAT_LC2') : '';

					$mailTags = [
						'{sender_first_name}}'	=> $card->sender_first_name,
						'{sender_last_name}}'	=> $card->sender_last_name,
						'{recipient_name}'		=> $card->to_name,
						'{recipient_email}'		=> $card->to_email,
						'{order_date}'			=> $created,
						'{completed_date}'		=> $completed,
						'{gift_card_amount}'	=> HTMLHelper::_('cmgiftcard.formatPrice', $card->amount),
						'{order_amount}'		=> HTMLHelper::_('cmgiftcard.formatPrice', $card->order_amount),
						'{order_number}'		=> $card->order_number,
					];

					foreach ($mailTags as $tag => $value)
					{
						$emailSubject = str_replace($tag, $value, $emailSubject);
						$emailBody = str_replace($tag, $value, $emailBody);
					}

					$mail = Factory::getMailer();
					$mail->setSender(
						array(
							$config->get('mailfrom'),
							$config->get('fromname')
						)
					)
					->addRecipient($card->sender_email)
					->setSubject($emailSubject)
					->setBody($emailBody)
					->isHtml(true);

					if ($pdfGiftCard && File::exists($filePath))
					{
						$mail->addAttachment($filePath, $fileName);
					}

					$sent = $mail->send();

					if (count($admins))
					{
						$emailSubject = $params->get('copy_prefix') . $emailSubject;

						foreach ($admins as $admin)
						{
							$mail = Factory::getMailer();
							$mail->setSender(
								array(
									$config->get('mailfrom'),
									$config->get('fromname')
								)
							)
							->addRecipient($admin->email)
							->setSubject($emailSubject)
							->setBody($emailBody)
							->isHtml(true);

							if ($pdfGiftCard && File::exists($filePath))
							{
								$mail->addAttachment($filePath, $fileName);
							}

							$mail->send();
						}
					}
				}
			}
		}

		if (File::exists($filePath))
		{
			File::delete($filePath);
		}

		return $sent;
	}

	/**
	 * Get an order.
	 *
	 * @param   integer  $orderId  Order ID.
	 *
	 * @return  mixed
	 *
	 * @since   1.0.0
	 */
	public static function getOrder($orderId)
	{
		$db = Factory::getDbo();

		$amountSubQuery = $db->getQuery(true)
			->select('SUM(' . $db->qn('c.amount') . ')')
			->from($db->qn('#__cmgiftcard_cards') . ' AS c')
			->where($db->qn('c.order_id') . ' = ' . $db->qn('a.id'));

		$cardSubQuery = $db->getQuery(true)
			->select('COUNT(' . $db->qn('gc.id') . ')')
			->from($db->qn('#__cmgiftcard_cards') . ' AS gc')
			->where($db->qn('gc.order_id') . ' = ' . $db->qn('a.id'));

		$query = $db->getQuery(true)
			->select('a.*')
			->select('(' . $amountSubQuery->__toString() . ') as amount')
			->select('(' . $cardSubQuery->__toString() . ') as card_quantity')
			->from($db->qn('#__cmgiftcard_orders') . ' AS a')
			->where($db->qn('a.id') . ' = ' . $db->q((int) $orderId));

		return $db->setQuery($query)->loadObject();
	}

	/**
	 * Get an email template.
	 *
	 * @param   string  $templateId  Template ID.
	 *
	 * @return  mixed
	 *
	 * @since   1.0.0
	 */
	public static function getMailTemplate($templateId)
	{
		$db = Factory::getDbo();
		$query = $db->getQuery(true)
			->select('*')
			->from($db->qn('#__cmgiftcard_email_templates'))
			->where($db->qn('template_id') . ' = ' . $db->q($templateId));

		return $db->setQuery($query)->loadObject();
	}

	/**
	 * Genarate random string.
	 *
	 * @param   string   $charType  Character types: alphabetic, numeric, or alphanumeric
	 * @param   integer  $length    The lenght of the random string
	 *
	 * @return  string
	 *
	 * @since   1.0.0
	 */
	public static function generateRandomString($charType = 'alphanumeric', $length = 5)
	{
		$length = (int) $length;

		if ($charType == 'alphabetic')
		{
			$chars = 'abcdefghijklmnopqrstuvwxyz';
		}
		elseif ($charType == 'numeric')
		{
			$chars = '0123456789';
		}
		else
		{
			$chars = '0123456789abcdefghijklmnopqrstuvwxyz';
		}

		$string = '';

		for ($i = 0; $i < (int) $length; $i++)
		{
			$string .= $chars[mt_rand(0, strlen($chars) - 1)];
		}

		return $string;
	}

	/**
	 * Joomla 3 & 4 compatibility.
	 *
	 * @param   string  $errorMessage  Error message.
	 * @param   string  $errorCode     Error code.
	 *
	 * @return  boolean
	 *
	 * @since   2.0.0-alpha1
	 */
	public static function throwException($errorMessage, $errorCode)
	{
		if (version_compare(JVERSION, '4.0.0-alpha1', '<'))
		{
			JError::raiseError($errorCode, $errorMessage);
		}
		else
		{
			throw new GenericDataException($errorMessage, $errorCode);
		}

		return false;
	}

	/**
	 * Get Joomla's image path to usable URL.
	 *
	 * @param   string  $imageUrl  Image URL.
	 *
	 * @return  string
	 *
	 * @since   2.0.0-beta1
	 */
	public static function getImageUrl($imageUrl)
	{
		if (version_compare(JVERSION, '4.0.0-alpha1', '>='))
		{
			$img = HTMLHelper::cleanImageURL($imageUrl);

			return $img->url;
		}

		return $imageUrl;
	}
}