<?php

// +-------------------------------------------------+
// | 2002-2007 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: pmbesAnimations.class.php,v 1.1.2.2 2025/10/30 13:23:25 rtigero Exp $

if (stristr($_SERVER['REQUEST_URI'], ".class.php")) die("no access");

use Pmb\Animations\Models\AnimationModel;
use Pmb\Animations\Opac\Models\RegistrationModel;
use Pmb\Animations\Models\RegistredPersonModel;
use Pmb\Common\Helper\HashModel;

global $class_path, $include_path;
require_once($class_path . "/external_services.class.php");
require_once("$include_path/mysql_connect.inc.php");

class pmbesAnimations extends external_services_api_class
{
	public function __construct($external_services, $group_name, &$proxy_parent)
	{
		parent::__construct($external_services, $group_name, $proxy_parent);
	}

	/**
	 * Convertit un array en stdClass
	 *
	 * @param array $array
	 * @return stdClass
	 */
	protected function arrayToStdClass(array $array): stdClass
	{
		$object = new stdClass();

		foreach ($array as $key => $value) {
			$object->$key = $value;
		}

		return $object;
	}

	/**
	 * Formate une animation
	 *
	 * @param AnimationModel $animation
	 * @return array
	 */
	protected function formatAnimation(AnimationModel $animation)
	{
		$animation->getViewData();

		foreach ($animation->childrens as &$child) {
			$childAnimation = new AnimationModel($child['idAnimation']);
			$childAnimation->getViewData();

			$child = $childAnimation;
		}

		return array(
			'id' => $animation->idAnimation,
			'name' => encoding_normalize::utf8_normalize($animation->name),
			'comment' => encoding_normalize::utf8_normalize($animation->comment),
			'description' => encoding_normalize::utf8_normalize($animation->description),
			'logo' => $animation->logo,
			'event' => $animation->event,
			'parent' => $animation->parent,
			'customFields' => $animation->customFields,
			'prices' => $animation->prices,
			'location' => $animation->location,
			'concepts' => $animation->concepts,
			'categories' => $animation->categories,
			'calendar' => $animation->calendar,
			'internetAvailable' => $animation->internetAvailable,
			'hasQuotas' => $animation->hasQuotas,
			'allQuotas' => $animation->allQuotas,
			'type' => $animation->type,
			'status' => $animation->status,
			'uniqueRegistration' => $animation->uniqueRegistration,
			'hasChildrens' => $animation->hasChildrens,
			'childrens' => $animation->childrens,
			'registrationRequired' => $animation->registrationRequired,
			'autoRegistration' => $animation->autoRegistration,
			'allowWaitingList' => $animation->allowWaitingList,
		);
	}

	/**
	 * Récupère les animations formatées
	 *
	 * @param array $animations_ids
	 * @return array
	 */
	public function listAnimations($animations_ids)
	{
		$result = array();
		foreach ($animations_ids as $animation_id) {
			$result[] = $this->formatAnimation(new AnimationModel($animation_id));
		}
		return $result;
	}

	/**
	 * Récupère les identifiants des animations à venir
	 *
	 * @return array
	 */
	public function getUpcomingAnimations()
	{
		$query = "SELECT DISTINCT anim_animations.id_animation 
				  FROM anim_animations 
				  JOIN anim_events ON anim_events.id_event = anim_animations.num_event
				  WHERE ((anim_events.during_day = 1 AND anim_events.start_date >= CURRENT_TIMESTAMP) 
				  OR anim_events.end_date >= CURRENT_TIMESTAMP)
				  ORDER BY anim_events.start_date ASC";

		$result = pmb_mysql_query($query);

		$animationsIds = [];
		while ($row = pmb_mysql_fetch_assoc($result)) {
			$animationsIds[] = $row['id_animation'];
		}

		return $animationsIds;
	}

	/**
	 * Récupère une inscription
	 *
	 * @param int $empr_id
	 * @param int $animation_id
	 * @return mixed
	 */
	public function getRegistration($empr_id, $animation_id) {
		$registration = new RegistrationModel(RegistrationModel::getIdRegistrationFromEmprAndAnimation($empr_id, $animation_id));
		return $registration->getViewData($empr_id);
	}

	/**
	 * Ajoute une inscription
	 *
	 * @param mixed $data
	 * @return array
	 */
	public function addRegistration($data) {

		// Si le paramètre est un array, on le transforme en object pour respecter la structure attendue dans les animations
		if(!is_object($data)) {
			$data = $this->arrayToStdClass($data);
		}

		// Si une liste de personnes est fournie, on la transforme en array pour respecter la structure attendue dans les animations
		if(is_countable($data->registrationListPerson)) {
			foreach ($data->registrationListPerson as $index => $person) {
				if(!is_object($person)) {
					$data->registrationListPerson[$index] = $this->arrayToStdClass($person);
				}
			}
		}

		// Vérification que l'emprunteur n'est pas déjà inscrit
		if(isset($data->numEmpr) && $data->numEmpr > 0) {
			// Si l'inscription est pour plusieurs animations (cas ou on s'incrit par l'animation parente)
			if(isset($data->animationsSelected) && !empty($data->animationsSelected)) {
				foreach ($data->animationsSelected as $animation_id) {
					$animationModel = new AnimationModel($animation_id);
					if($animationModel->emprAlreadyRegistred(intval($data->numEmpr))) {
						return [
							"success" => false,
							"message" => "Reader already registered"
						];
					}
				}
			// Si une seule animation est sélectionnée (cas ou on s'incrit par l'animation)
			} else {
				$animationModel = new AnimationModel($data->numAnimation);
				if($animationModel->emprAlreadyRegistred(intval($data->numEmpr))) {
					return [
						"success" => false,
						"message" => "Reader already registered"
					];
				}
			}
		}

		return RegistrationModel::addRegistration($data);
	}

	/**
	 * Supprime une inscription
	 *
	 * @param int $empr_id
	 * @param int $animation_id
	 * @param string $hash
	 * @param int $id_person
	 * @return bool
	 */
	public function deleteRegistration($empr_id, $animation_id, $hash, $id_person = 0) {
		// Récupérer l'ID de l'inscription
		$id_registration = RegistrationModel::getIdRegistrationFromEmprAndAnimation($empr_id, $animation_id);

		if (empty($id_registration)) {
			return false;
		}

		$registration_model = new RegistrationModel($id_registration);

		// Créer le paramètre pour vérifier le hash
		$param = $registration_model->idRegistration . $registration_model->date . $registration_model->numAnimation;

		$hash_model = new HashModel();

		// Vérifier que le hash est valide et correspond bien à l'inscription
		if (false === $hash_model->verifeHash($hash, $param) && $registration_model->hash !== $hash) {
			return false;
		}

		$is_contact = false;

		// Si un id_person est fourni, vérifier si c'est la personne de contact
		if (!empty($id_person)) {
			$registred_person_model = new RegistredPersonModel($id_person);

			// La personne de contact n'est pas forcément inscrite pour l'animation
			// Si c'est la personne de contact qui se désinscrit, on supprime tout
			if ($registration_model->numEmpr === $registred_person_model->numEmpr) {
				$is_contact = true;
			}
		} else {
			// Si pas d'id_person spécifié, c'est la personne de contact qui se désinscrit
			$is_contact = true;
		}

		if (empty($registration_model->idRegistration)) {
			return false;
		}

		// Supprimer l'inscription
		$registration_model->delete($is_contact, $id_person);

		return true;
	}
}
