<?php
function route() {
	return App\Contract\Route::route();
}
function uf($date, $async = false) {
	if (is_string($date)) {
		$date = Carbon\Carbon::parse($date, config('app.timezone'));
	}
	$next_m_9 = Carbon\Carbon::today(config('app.timezone'))->copy()->endOfMonth()->addDays(9);
	if ($date->greaterThanOrEqualTo($next_m_9)) {
		return (object) ['total' => 0];
	}
	$url = 'http://' . config('locations.money') . '/api/uf/value/' . $date->format('Y-m-d');
	$client = new \Goutte\Client();
	$client->setHeader('Accept', 'application/json');
	$client->request('GET', $url);

	$response = $client->getResponse();
	if (!$response) {
		return (object) ['total' => 0];
	}
	$status = $response->getStatusCode();
	if ($status >= 200 and $status < 300) {
		$data = json_decode($response->getContent());
		return $data;
	}
	return (object) ['total' => 0];
}
function format($tipo, $valor, $format = null, $print = false) {
	if (strtolower($tipo) == 'localdate') {
		$d = \Carbon\Carbon::parse($valor);
		$d->locale('es_ES');
		if ($format == null) {
			$format = 'DD [de] MMMM [de] YYYY';
		}
		return $d->isoFormat($format);
	}
	if (method_exists('\App\Helper\Format', $tipo)) {
		if ($print) {
			return \App\Helper\Format::$tipo($valor, $print);
		} else {
			return \App\Helper\Format::$tipo($valor);
		}
	} else {
		switch ($tipo) {
			case 'localDate':
				if (isset($format)) {
					$intl = new IntlDateFormatter('es_ES', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT, 'America/Santiago');
					$intl->setPattern($format);
					return ucwords($intl->format($valor));
				}
			case 'percent':
				return \App\Helper\Format::number($valor, 2);
			case 'rut':
				return \App\Helper\Format::number($valor, 0);
		}
	}
}
function model(string $class_name) {
	return \Model::factory($class_name);
}
function correctNumber($number) {
	if (strpos($number, ',') !== false) {
		return str_replace(',', '.', str_replace('.', '', $number));
	} elseif (substr_count($number, '.') > 1) {
		return str_replace('.', '', $number);
	}
	return $number;
}
function parseRanges($range, $numeric = true, $negatives = true) {
	$rns = preg_split('/[,;]+/', $range);
	$data = [];
	foreach ($rns as $p) {
		if (!$negatives) {
			if (strpos($p, '-') !== false) {
				list($ini, $end) = explode('-', $p);
				$data = array_merge($data, range($ini, $end));
				continue;
			}
		}
		if ($numeric) {
			$data []= (float) $p;
			continue;
		}
		$data []= $p;
	}
	return $data;
}
function nUrl($p, $a = null, $data = null) {
	$query = ['p' => $p];
	if ($a != null) {
		$query['a'] = $a;
		if ($data != null) {
			$query = array_merge($query, $data);
		}
	}
	return url('', $query);
}
function doLog($user, $action, $variables) {
	App\Service\Register::log($user, $action, $variables);
}
?>
