<?php
/** 
 * @package     VikAppointments
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2021 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

/**
 * VikAppointments custom field country rule dispatcher.
 *
 * @since 1.7.8
 */
class VAPCustomFieldRuleCountry extends VAPCustomFieldRule
{
	/**
	 * Returns the name of the rule.
	 *
	 * @return 	string
	 */
	public function getName()
	{
		return JText::translate('VAPMANAGECUSTOMER5');
	}

	/**
	 * Dispatches the field rule.
	 *
	 * @param 	mixed  $value  The value of the field set in request.
	 * @param 	array  &$args  The array data to fill-in in case of
	 *                         specific rules (name, e-mail, etc...).
	 * @param 	mixed  $field  The custom field object.
	 *
	 * @return 	void
	 */
	public function dispatch($value, &$args, $field)
	{
		$db = JFactory::getDbo();

		$query = $db->getQuery(true)
			->select($db->qn('country_2_code'))
			->from($db->qn('#__vikappointments_countries'))
			->where($db->qn('published') . ' = 1')
			->andWhere([
				$db->qn('country_2_code') . ' = ' . $db->q($value),
				$db->qn('country_name') . ' = ' . $db->q($value),
			], 'OR');

		$db->setQuery($query, 0, 1);
		$countryCode = $db->loadResult();

		// in case of multiple fields with country rule, use only the first specified one
		if ($countryCode && empty($args['country_code']))
		{
			// fill country column with field value
			$args['country_code'] = $countryCode;
		}
	}

	/**
	 * Renders the field rule.
	 *
	 * @param 	array   &$data  An array of display data.
	 * @param 	mixed   $field  The custom field object.
	 *
	 * @return 	string  The HTML that will be used in place of the layout
	 *                  defined by the field. Omit this value to keep using
	 *                  the default HTML of the field.
	 */
	public function render(&$data, $field)
	{
		// in case of select field, auto-fill the options with the supported countries
		if ($field->get('type') === 'select')
		{
			// iterate published countries
			foreach (VAPLocations::getCountries('country_name') as $country)
			{
				// use the country alpha-2 code as option value
				$data['options'][] = JHtml::fetch('select.option', $country['country_2_code'], $country['country_name']);
			}
		}

		return '';
	}
}
