<?php

if (!function_exists('duree')) {
	function duree($time)
	{
		$tabTemps = array("jours" => 86400,
			"h" => 3600,
			"m" => 60,
			"s" => 1);
		$result = "";

		foreach ($tabTemps as $uniteTemps => $nombreSecondesDansUnite) {

			$$uniteTemps = floor($time / $nombreSecondesDansUnite);

			$time = $time % $nombreSecondesDansUnite;

			if ($$uniteTemps > 0 || !empty($result)) {

				$result .= $$uniteTemps . " $uniteTemps ";
			}
		}

		return $result;

	}

}

if (!function_exists('dateDiff')) {
	function dateDiff($date1, $date2, $class = null)
	{
		$diff = abs($date1 - $date2); // abs pour avoir la valeur absolute, ainsi éviter d'avoir une différence négative
		$retour = array();

		$tmp = $diff;
		$second = $tmp % 60;

		$tmp = floor(($tmp - $second) / 60);
		$minute = $tmp % 60;

		$tmp = floor(($tmp - $minute) / 60);
		$heure = $tmp % 24;

		$tmp = floor(($tmp - $heure) / 24);
		$jour = $tmp;

		return $class->lang->line('since') . ' ' . $jour . ' ' . $class->lang->line('days') . ' ' . $heure . ' ' . $class->lang->line('hours') . ' ' . $minute . ' ' . $class->lang->line('minutes') . ' ' . $second . ' ' . $class->lang->line('seconds');
	}
}


if (!function_exists('traitementTemps')) {
	function traitementTemps($time, $dateAjout, $class = null)
	{
		if ($time == null) {
			$now = time();
			$date2 = strtotime($dateAjout);

			return dateDiff($now, $date2, $class);
		} else {
			return duree($time);
		}
	}
}


if (!function_exists('getDelayOfTreatmentInSeconds')) {
	function getDelayOfTreatmentInSeconds($time, $dateAjout)
	{
		if ($time == null) {
			$now = time();
			$date2 = strtotime($dateAjout);
			return abs($now - $date2);
		} else {
			return $time;
		}

	}
}

if (!function_exists('line_with_arguments'))
{
	function line_with_arguments($line, $args = array())
	{
		return vsprintf($line, $args);
//		return str_replace('%s', $swap, $line);
	}
}

if (!function_exists('convertDate')) {
	function convertDate($date)
	{
		$month = null;
		switch ($date) {
			case "Jan":
				$month = 1;
				break;
			case "Feb":
				$month = 2;
				break;
			case "Mar":
				$month = 3;
				break;
			case "Apr":
				$month = 4;
				break;
			case "May":
				$month = 5;
				break;
			case "Jun":
				$month = 6;
				break;
			case "Jul":
				$month = 7;
				break;
			case "Aug":
				$month = 8;
				break;
			case "Sep":
				$month = 9;
				break;
			case "Oct":
				$month = 10;
				break;
			case "Nov":
				$month = 11;
				break;
			case "Dec":
				$month = 12;
				break;
		}
		return $month;
	}
}

if (!function_exists('hashSSHA')) {
	function hashSSHA($password) {
		$salt = sha1(rand());
		$salt = substr($salt, 0, 10);
		$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
		return array("salt" => $salt, "encrypted" => $encrypted);
	}
}

if (!function_exists('checkhashSSHA')) {
	function checkhashSSHA($salt, $password) {
		return base64_encode(sha1($password . $salt, true) . $salt);
	}
}

if (!function_exists('makeRequest')) {
	function makeRequest($service , $method , $path , $request_body = []){
		if(empty($_SESSION['email'])) {
			return json_encode(['status' => 401]);
		}

		switch ($service){
			case 'user-service':
				$baseUrl = USER_SERVICE_URL;
				$token = USER_SERVICE_TOKEN;
				break;
			case 'nano-service':
				$baseUrl = NANO_SANTE_SERVICE_URL;
				$token = NANO_SANTE_SERVICE_TOKEN;
				break;
			case 'wallet-service':
				$baseUrl = WALLET_SERVICE_URL;
				$token = WALLET_SERVICE_TOKEN;
				break;
			default:
				$baseUrl = '';
				$token = '';
		}
		$url = $baseUrl.$path;
		if($method == 'GET'){
			$data = http_build_query($_POST);
			$ch = curl_init($url."?".$data);
		}else{
			$ch = curl_init($url);
		}
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
		/* set the content type json */
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type:application/json',
			'Authorization:'.$token,
			'X-localization:'. $_SESSION['site_lang'] == 'french' ? 'fr' : 'en'
		));
		/* set return type json */
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$body = new \stdClass();
		foreach ($request_body as $key => $value){
			$body->{$key} = $value;
		}
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

		/* execute request */
		$result = curl_exec($ch);
		/* close cURL resource */
		curl_close($ch);

		if ($result) {
			return $result;
		}else{
			return json_encode(['status' => 500]);
		}
	}
}

if (!function_exists('getStatusBadge')) {
	function getStatusBadge($status, $lang)
	{
		// On s'assure que le statut est propre
		$statusKey = strtolower(trim($status));
		
		$line = $lang->line('status_' . $statusKey);
		$label = (!empty($line)) ? $line : ucfirst($statusKey);

		// Style commun pour garder l'effet "pillule" arrondi que vous aviez
		$style = 'padding: 6px 12px; border-radius: 20px; font-size: 12px;';

		switch ($statusKey) {

			case 'pending':
				return '<span class="label label-warning" style="'.$style.'">'.$label.'</span>';

			case 'actived':
				return '<span class="label label-success" style="'.$style.'">'.$label.'</span>';

			case 'validated':
				return '<span class="label label-primary" style="'.$style.'">'.$label.'</span>';

			case 'close':
			case 'closed':
				return '<span class="label label-default" style="'.$style.' background-color: #d2d6de; color: #444;">'.$label.'</span>';

			case 'rejected':
				return '<span class="label label-danger" style="'.$style.'">'.$label.'</span>';

			default:
				return '<span class="label label-info" style="'.$style.'">'.$label.'</span>';
		}
	}

	if(!function_exists('truncateText')) {
		function truncateText($text, $limit = 30, $end = '...') 
		{
			// On vérifie si la longueur du texte dépasse la limite
			if (mb_strlen($text) > $limit) {
				// On coupe à 30 et on ajoute le suffixe
				return mb_substr($text, 0, $limit) . $end;
			}
			// Si le texte est court, on le retourne tel quel
			return $text;
		}
	}
}

