<?php
/**
 *----------------------------------------------------------------------------
 * iCagenda     Events Management Extension for Joomla!
 *----------------------------------------------------------------------------
 * @version     4.0.0 2025-12-09
 *
 * @package     iCagenda.Admin
 * @subpackage  src.Utilities.Registration
 * @link        https://www.joomlic.com
 *
 * @author      Cyril Reze
 * @copyright   (c) 2012-2026 Cyril Reze / JoomliC. All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 *
 * @since       4.0
 *----------------------------------------------------------------------------
*/

namespace iCutilities\Participants;

use iCutilities\Event\Event as icagendaEvent;
use iCutilities\Events\Events as icagendaEvents;
use iCutilities\Render\Render as icagendaRender;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Layout\FileLayout;
use Joomla\CMS\HTML\HTMLHelper;

// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects

/**
 * class icagendaParticipants
 */
class Participants
{
	/**
	 * Function to check if display of participants list
	 */
	static public function listDisplay($item)
	{
		$iCparams = ComponentHelper::getParams('com_icagenda');

		// Get Option if usage of iCagenda registration form for this event
		$evtParams = icagendaEvent::evtParams($item->params);
		$regLink   = $evtParams->get('RegButtonLink', '');

		// Hide/Show Option
		$participantsList = $iCparams->get('participantList', 0);

		// Access Levels Option
		$accessParticipantList = $iCparams->get('accessParticipantList', 1);

		if ($participantsList == 1
			&& ! $regLink
			&& icagendaEvents::accessLevels($accessParticipantList)
		) {
			return $participantsList;
		}

		return false;
	}

	/**
	 * Function to display list of participants
	 */
	static public function renderParticipants($item)
	{
		if (!self::listDisplay($item)) {
			return;
		}

		$app   = Factory::getApplication();
		$input = $app->input;

		$eventTimeZone = null;

		// Get Component PARAMS
		$iCparams = ComponentHelper::getParams('com_icagenda');

		// Get Type Registration (for all dates or per date)
		$typeReg = $item->params->get('typeReg', 1);

		// Preparing connection to db
		$db = Factory::getContainer()->get('DatabaseDriver');

		// Preparing the query
		$query = $db->createQuery()
			->select([
				$db->qn('r.id', 'regID'),
				$db->qn('r.userid', 'userid'),
				$db->qn('r.name', 'registeredUsers'),
				$db->qn('r.date', 'regDate'),
				$db->qn('r.people', 'regPeople'),
				$db->qn('r.email', 'regEmail'),
				$db->qn('u.name', 'name'),
				$db->qn('u.username', 'username'),
				'GROUP_CONCAT(' . $db->qn('ua.user_action') . ') AS ' . $db->qn('user_action'),
			])
			->from($db->qn('#__icagenda_registration', 'r'))
			->join('LEFT', $db->qn('#__users', 'u'), $db->qn('u.id') . ' = ' . $db->qn('r.userid'))
			->join('LEFT', $db->qn('#__icagenda_user_actions', 'ua'), $db->qn('ua.parent_id') . ' = ' . $db->qn('r.id'));

		$query->group(
				[
					$db->quoteName('r.id'),
					$db->quoteName('ua.parent_id'),
				]
			)
			->where($db->qn('r.eventid') . ' = ' . (int) $item->id)
			->where($db->qn('r.status') . ' = 1')
			->where($db->qn('r.state') . ' = 1');

		// Get var event date alias if set or var 'event_date' set to session in event details view.
		$session    = Factory::getSession();
		$event_date = $session->get('event_date', '');
		$get_date   = $input->get('date', ($event_date ? date('Y-m-d-H-i', strtotime($event_date)) : ''));

		// Convert to SQL datetime if set, or return empty.
		$current_date_SQL = icagendaEvent::convertDateAliasToSQLDatetime($get_date);

		// Registration type: by single date/period (1)
		if ($current_date_SQL && $typeReg == 1) {
			// Single date or period split by day(s) of the week.
			$query->where('(' . $db->qn('r.date') . ' = ' . $db->q($current_date_SQL)
				. ' OR (' . $db->qn('r.date') . ' = "" AND ' . $db->qn('r.period') . ' = 1) )');
//			$query->where('r.date = ' . $db->q($current_date_SQL)); // This is the correct logic if correctly set
		} elseif ( ! $current_date_SQL && $typeReg == 1) {
			// Full period.
			$query->where($db->qn('r.date') . ' = ""');
//			$query->where('r.date = "" AND r.period = 0'); // This is the correct logic if correctly set
		}

		$db->setQuery($query);

		$registeredUsers = $db->loadObjectList();
		$nbusers         = \count($registeredUsers);
		$registration    = $item->params->get('statutReg', '');
		$columns         = '';

		// List of Participants params
		$participantsList    = $iCparams->get('participantList', 0);
		$participantsToggle  = $iCparams->get('participantsToggle', 1);
		$participantsDisplay = (int) $iCparams->get('participantDisplay', 1);
		$fullListColumns     = $iCparams->get('fullListColumns', 3);

		// logged-in Users: Name/User Name Option
		$nameJoomlaUser = $iCparams->get('nameJoomlaUser', 1);

		$current_event_date = HTMLHelper::date($current_date_SQL, 'Y-m-d H:i', $eventTimeZone);

		if ($participantsList == 1 && $registration == 1) {
			// Check Admin / Organiser permissions to access registration data
			$organiser_rights = Factory::getUser()->authorise('icagenda.access.registrations', 'com_icagenda');

			$participants      = [];
			$list_names        = '';
			$list_participants = '';

			foreach ($registeredUsers as $reguser) {
				$this_reg_date = strtotime($reguser->regDate)
					? HTMLHelper::date($reguser->regDate, 'Y-m-d H:i', $eventTimeZone)
					: $reguser->regDate;

				if (($this_reg_date == $current_event_date || empty($get_date))
					|| $typeReg == 2
					|| ($typeReg == 1 && ! $this_reg_date)
				) {
					// Get participant privacy consents
					$user_actions = (isset($reguser->user_action) && $reguser->user_action)
						? explode(',', $reguser->user_action)
						: [];

					// Get Name consent
					$name_consents = [];

//					foreach ($user_actions AS $k => $action) {
//						$ex_action = explode('__', $action);

//						if ($ex_action[0] == 'consent_name'
//							&& isset($ex_action[1])
//						) {
//							$name_consents = explode('_', $ex_action[1]);
//						}
//					}

					if (\in_array('consent_name_public', $user_actions)) {
						$name_consents = ['public'];
					}

					if (\in_array('consent_name_users', $user_actions)) {
						$name_consents = ['users'];
					}

					$force_name_visibility = $iCparams->get('participant_name_consent', '');

					if ($force_name_visibility == '0') {
						$participant_name_visibility = $iCparams->get('participant_name_visibility', '');

						if ($participant_name_visibility == 1) {
							$name_consents = ['public'];
						} elseif ($participant_name_visibility == 2) {
							$name_consents = ['users'];
						}
					}

					if (\in_array('public', $name_consents)
						|| (\in_array('users', $name_consents) && Factory::getUser()->id > 0)
					) {
						// Get Username and name (To check: Is it needed ?)
						if ( ! empty($reguser->userid)) {
							$data_name     = $reguser->name;
							$data_username = $reguser->username;

							if ($nameJoomlaUser == 1) {
								$reguser->registeredUsers = $reguser->registeredUsers;
							} else {
								$reguser->registeredUsers = $data_username;
							}
						}

						$participant_name = $reguser->registeredUsers;
					} elseif ($organiser_rights) {
						// Information to be extended for logged-in user with admin/organiser permissions...
						$participant_name = $reguser->registeredUsers;
					} else {
						$participant_name = Text::_('IC_ANONYMOUS');
					}

					if ($participantsDisplay === 1 || $participantsDisplay === 2) {
						// Get Gravatar consent
						if (\in_array('consent_gravatar', $user_actions)) {
							$avatar             = md5(strtolower(trim($reguser->regEmail)));
							$participant_avatar = '<img alt="avatar ' . $participant_name . '" src="https://www.gravatar.com/avatar/' . $avatar . '?&d=mm" width="48" height="48" />';
						} else {
//							$participant_avatar = '<span class="iCicon-user ic-avatar"></span>';
							$participant_avatar = '<img alt="avatar ' . $participant_name . '" src="./media/com_icagenda/images/avatar.svg" width="48" height="48" class="default-avatar-svg" />';
						}
					}

					if ($participantsDisplay === 1) {

						$regDate = '';

						// Test if registered date before 3.3.3 could be converted
						if (strtotime($reguser->regDate)) {
							// Control if date valid format (Y-m-d H:i)
							$datetime_format   = 'Y-m-d H:i:s';
							$datetime_input    = $reguser->regDate;
							$datetime_input    = trim($datetime_input);
							$datetime_is_valid = date($datetime_format, strtotime($datetime_input)) == $datetime_input;

							if ($datetime_is_valid) {
								// New Data value (since 3.3.3)
								$ex_reg_datetime_db = explode (' ', $datetime_input);
								$registered_date    = icagendaRender::dateToFormat(date('Y-m-d', strtotime($ex_reg_datetime_db['0'])));
								$reg_time_get       = isset($ex_reg_datetime_db['1']) ? $ex_reg_datetime_db['1'] : '';
							} else {
								// Test if old date format (before 3.3.3) could be converted. If not, displays old format.
								$ex_reg_datetime    = explode (' - ', trim($reguser->regDate));

								// Control if date valid format (Y-m-d) - Means could be converted
								$date_format   = 'Y-m-d H:i:s';
								$date_input    = $ex_reg_datetime['0'];
								$date_input    = trim($date_input);
								$date_str      = strtotime($date_input);
								$date_is_valid = date($date_format, $date_str) == $date_input;

								if ($date_is_valid) {
									$registered_date = icagendaRender::dateToFormat(date('Y-m-d', $date_str));
								} else {
									$registered_date = $ex_reg_datetime['0'];
								}

								$reg_time_get = isset($ex_reg_datetime['1']) ? $ex_reg_datetime['1'] : '';
							}

							$regDate.= $registered_date;

							if ($reg_time_get) {
								$regDate.= ' - ' . date('H:i', strtotime($reg_time_get));
							}
						} else {
							$regDate.= $reguser->regDate;
						}

						$customFields = self::loadRegistrationCustomFields($reguser->regID);

						// Add participant to the list of participants.
						$participants[] = [
							'userid'        => $reguser->userid,
							'avatar'        => $participant_avatar,
							'name'          => $participant_name,
							'tickets'       => $reguser->regPeople,
							'date'          => $regDate,
							'custom_fields' => $customFields,
						];
					}

					if ($participantsDisplay === 2) {
						$participants[] = [
							'userid'  => $reguser->userid,
							'avatar'  => $participant_avatar,
							'name'    => $participant_name,
						];
					}

					if ($participantsDisplay === 3) {
						$list_names.= $participant_name . ', ';
					}
				}
			}

			if ($participantsDisplay === 1) {
				// Full display
				$columns = isset($fullListColumns) ? $fullListColumns : 3;
			}

			if ($participantsDisplay === 3) {
				$list_participants = trim($list_names, ", ");

				$participants['list_participants'] = $list_participants;
			}
		} else {
			return '';
		}

		// Data for layouts
		$displayData = [
			'noparticipants' => ((int) $nbusers === 0),
			'toggle'         => $participantsToggle,
			'display'        => (int) $participantsDisplay,
			'columns'        => $columns,
			'participants'   => $participants,
			'theme'          => $item->params->get('template', 'default'),
		];

		$layout = new FileLayout('icagenda.participants.list');
		$layout->addIncludePaths(JPATH_SITE . '/components/com_icagenda/themes/packs/' . $item->params->get('template', 'default') . '/layouts');

		return $layout->render($displayData);
	}

	/**
	 * Loads the registration's custom fields for this participant.
	 *
	 * @param   integer   $id  Registration id
	 *
	 * @return  object[]  List of custom fields
	 */
	static public function loadRegistrationCustomFields($id = null)
	{
		// Get the database connector.
		$db = Factory::getContainer()->get('DatabaseDriver');

		$query = $db->createQuery()
			->select('cfd.*, cf.*')
			->from($db->qn('#__icagenda_customfields_data') . ' AS cfd')
			->leftJoin('#__icagenda_customfields AS cf ON cf.slug = cfd.slug')
			->where($db->qn('cfd.parent_id') . ' = ' . (int) $id)
			->where($db->qn('cfd.parent_form') . ' = 1')
			->where($db->qn('cf.parent_form') . ' = 1')
			->where($db->qn('cfd.state') . ' = 1')
			->where($db->qn('cf.state') . ' = 1')
			->where($db->qn('cfd.value') . ' NOT IN ("", "{}")')
			->order('cf.ordering ASC');

		// Tell the database connector what query to run.
		$db->setQuery($query);

		// Invoke the query or data retrieval helper.
		return $db->loadObjectList();
	}
}
