<?php

	/*
	 *
	 * yMS (c) 2003 - 2020 Yal Publicidad
	 * Sistema: Macrodígital Software - de Yal Publicidad
	 *
	 */
	 
	 /* Autorizo acceso */
		defined('YMS') or die( 'No dispones de acceso' );
		
	function formato_moneda($formato,$numero,$divisa='PEN'){
		return yDivisa::formato_moneda($formato,$numero,$divisa);
	}

	class yDivisa{
		/*
		 * funcion para convertir divisa
		 * $ 100 USD
		 * ej yDivisa::convertir( '100', 'usd', 'pen' );
		 * retorna 350 -> PEN
		 */
		public static function convertir( $monto = 0, $de = 'usd', $a = 'pen' ){
			$de	 	= strtoupper( $de );
			$a 		= strtoupper( $a );
			
			$json	= json_decode( self::tipo_cambio( $de, $a ) );
			$tasa	= (isset( $json->tasa ) && is_numeric($json->tasa)) ? $json->tasa : 1;
			
			$monto	= ( $monto * $tasa );
			
			return $monto;
		}
		
		/*
		 * funcion para convertir divisa de factura a divisa de la organzacion
		 * $ 100 USD monto facturado
		 * ej yDivisa::convertir_factura( '100', 3.5, 'usd', 'pen' );
		 * retorna 350 -> PEN
		 */
		public static function convertir_factura( $monto = 0, $tasa=0, $de = 'usd', $a = 'pen' ){
			$de	 	= strtoupper( $de );
			$a 		= strtoupper( $a );
			
			// si ambas divisas son iguales retorno el mismo monto
			if($de==$a) return $monto;
			// si ambas divisas son diferentes calculo conversion
			$monto	= ( $monto * $tasa );
			// retorno monto calculado
			return $monto;
		}
		
		/* funcion para dar formato al monto de la moneda 
		 * ej.
		 * % = 1,000.00
		 * %i = PEN 1,000.00
		 * %n = S/ 1,000.00
		 * %$ = S/ 1,000.00 PEN
		 */
		public static function formato_moneda($formato, $numero, $divisa = 'PEN'){
			$number		= $numero;
			$positive	= true;
            if ($number < 0) {
                $positive = false;
                $number *= -1;
            }
			$number = sprintf('%.2f', $number);
			$simbolo= _mysql_obtener_reg('ygemoneda', "divisa='$divisa'", "simbolo");

			while (true) { 
				$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);

				if ($replaced != $number) {
					$number = $replaced;
				} else {
					break;
				}
			}
		
			$prefix = $suffix = '';
			switch(true){
				case '%i':
					$prefix = $divisa;
					break;
				case '%n':
					$prefix = $simbolo;
					break;
				case '%$':
					$prefix = $simbolo;
					$suffix = $divisa;
					break;
			}
				return $prefix.' '.$number.' '.$suffix;
		}
		
		function money_format($format, $number) {
			$regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' .
					'(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
			if (setlocale(LC_MONETARY, 0) == 'C') {
				setlocale(LC_MONETARY, '');
			}
			$locale = localeconv();
			preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
			foreach ($matches as $fmatch) {
				$value = floatval($number);
				$flags = array(
					'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ?
							$match[1] : ' ',
					'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
					'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
							$match[0] : '+',
					'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
					'isleft' => preg_match('/\-/', $fmatch[1]) > 0
				);
				$width = trim($fmatch[2]) ? (int) $fmatch[2] : 0;
				$left = trim($fmatch[3]) ? (int) $fmatch[3] : 0;
				$right = trim($fmatch[4]) ? (int) $fmatch[4] : $locale['int_frac_digits'];
				$conversion = $fmatch[5];

				$positive = true;
				if ($value < 0) {
					$positive = false;
					$value *= -1;
				}
				$letter = $positive ? 'p' : 'n';

				$prefix = $suffix = $cprefix = $csuffix = $signal = '';

				$signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
				switch (true) {
					case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
						$prefix = $signal;
						break;
					case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
						$suffix = $signal;
						break;
					case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
						$cprefix = $signal;
						break;
					case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
						$csuffix = $signal;
						break;
					case $flags['usesignal'] == '(':
					case $locale["{$letter}_sign_posn"] == 0:
						$prefix = '(';
						$suffix = ')';
						break;
				}
				if (!$flags['nosimbol']) {
					$currency = $cprefix .
							($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
							$csuffix;
				} else {
					$currency = $cprefix .$csuffix;
				}
				$space = $locale["{$letter}_sep_by_space"] ? ' ' : '';

				$value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
				$value = @explode($locale['mon_decimal_point'], $value);

				$n = strlen($prefix) + strlen($currency) + strlen($value[0]);
				if ($left > 0 && $left > $n) {
					$value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
				}
				$value = implode($locale['mon_decimal_point'], $value);
				if ($locale["{$letter}_cs_precedes"]) {
					$value = $prefix . $currency . $space . $value . $suffix;
				} else {
					$value = $prefix . $value . $space . $currency . $suffix;
				}
				if ($width > 0) {
					$value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
									STR_PAD_RIGHT : STR_PAD_LEFT);
				}

				$format = str_replace($fmatch[0], $value, $format);
			}
			return $format;
		}
		
		/*
		 * funcion para obtener el inverso de divisa 
		 * ej yDivisa::obt( 'PEN' );
		 * retorna 0.30303
		 */
		public static function obt( $moneda = 'pen', $divisa = 'usd' ){
			$short	 	= strtoupper( $moneda );
			$divisa 	= strtoupper( $divisa );
			
			$json		= json_decode( self::obtTabla( $short ) );
			$inverso	= isset( $json->$divisa ) ? $json->$divisa : 0.30303;
			
			return $inverso;
		}
		
		public static function obtTabla( $divisa = 'pen', $assoc = false ){
			$divisa = strtolower( $divisa );
			
			// evitar problemas de codificación
				//header('Content-Type: text/html; charset=utf-8');   
			// url
				$urlCT		= "https://es.fxexchangerate.com/$divisa/";
			// cURL
				$ch	= curl_init($urlCT);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$cl	= curl_exec($ch);
			// Los elementos Dom de la página que vas a reccorrer
				$dom		= new DOMDocument();
				@$dom->loadHTML($cl);
			// La ruta del elemento
				$xpath		= new DOMXpath($dom);
				$resultado	= array();
			// Listo resultados
				$trs = $dom->getElementsByTagName("tr");
				foreach ( $trs as $tr )
				{
						// Cada TD
						$nombre = ( isset( $tr->getElementsByTagName("td")->item(0)->nodeValue ) ) ? $tr->getElementsByTagName("td")->item(0)->nodeValue : '';
						$divisa = ( isset( $tr->getElementsByTagName("td")->item(1)->nodeValue ) ) ? $tr->getElementsByTagName("td")->item(1)->nodeValue : '';
						$valor = ( isset( $tr->getElementsByTagName("td")->item(2)->nodeValue ) ) ? $tr->getElementsByTagName("td")->item(2)->nodeValue : '';
				 
						//echo $title . "\t" . $value."<br>";
						$resultado[$divisa] = $valor;
				}
				
			return ( $assoc ) ? $resultado : json_encode($resultado);
			
		}
		
		/*
		 * funcion para obtener el inverso de divisa 
		 * ej yDivisa::obtInverso( 'PEN', 'USD' );
		 * retorna 1.52
		 */
		public static function obtInverso( $moneda = 'pen', $divisa = 'usd' ){
			$short	 	= strtoupper( $moneda );
			$divisa 	= strtoupper( $divisa );
			
			$json		= json_decode( self::obtTabla( $short ) );
			
			$inverso	= isset( $json->$divisa ) ? $json->$divisa : 0.30303;
			$inverso	= ( 1 / $inverso );
			
			return $inverso;
		}
		
		public static function tipo_cambio( $de = 'pen', $a = 'usd' ){
			$de = strtoupper($de);
			$a	= strtoupper($a);
			
			// evitar problemas de codificación
				//header('Content-Type: text/html; charset=utf-8');   
			// url
				//$urlCT		= "https://es.fxexchangerate.com/" . $de . "/" . $a . ".html";
				$urlCT = 'https://es.exchange-rates.org/converter/'.$de.'/'.$a.'/1';
			// cURL
				$ch	= curl_init($urlCT);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$cl	= curl_exec($ch); //return $cl;
			// Los elementos Dom de la página que vas a reccorrer
				$dom		= new DOMDocument();
				@$dom->loadHTML($cl);
			// La ruta del elemento
				$xpath		= new DOMXpath($dom);
				$resultado	= array();
			// Listo resultados
				$trs = $dom->getElementsByTagName("small");
				foreach ( $trs as $tr )
				{
					//echo ( isset( $tr->getElementsByTagName("span")->item(0)->nodeValue ) ) ? $tr->getElementsByTagName("span")->item(0)->nodeValue . '<br>' : '-';
					$dat2[] = ( isset( $tr->getElementsByTagName("span")->item(0)->nodeValue ) ) ? $tr->getElementsByTagName("span")->item(0)->nodeValue : '';
				}
			// -- obtengo resultados del primer array
			$tasa	= (isset($dat2[0])) ? explode('=',$dat2[0]) : false;
			// solo dejo el valor numerico
			$tasa	= (isset($tasa[1])) ? trim( str_replace(strtoupper($a),'',$tasa[1]) ) : 0;
			// cambio como por punto
			$tasa	= str_replace(',','.',$tasa);
			// creo el inverso ej. 3.73
			$inverso= (1/$tasa);
			// creo JSON con datos
			$rspta = '{"de":"' . strtoupper($de) . '","tasa":"' . $tasa . '","inverso":"' . $inverso . '","a":"' . strtoupper($a) . '","tasa_str":"1 ' . $de . '","inverso_str":"' . number_format($inverso,5) . ' ' . $a . '"}';
			return $rspta;
			
		}
		
	}
	
		
		/*$x = 0;
		$convDivisa = $xpath->query( '//div[1]/div[4]/div[1]/div/div[6]/table/tbody/tr[1]/td[3]' );
		$convDivisa2 = $xpath->query( '//div[1]/div[4]/div[1]/div/div[6]/table/tbody/tr[1]/td[4]/a' );
		$tabla = $xpath->query( '//div[1]/div[4]/div[1]/div/div[6]/table/tbody' );
		$divisa = $convDivisa->item($x)->nodeValue;
		$iso = $convDivisa2->item($x)->nodeValue;
		echo $divisa . ' - ' . $iso;*/
		
	
?>