<?php

namespace SHServ;

class Utils {
	public function redirect(String $url) {
		header("Location: {$url}");
		exit;
	}

	public function table_row_is_exists(\Fury\Modules\ThinBuilder\ThinBuilder $tb_instance, String $tablename, String $field_name, String $value): Bool {
		return $tb_instance -> count($tablename, [ [$field_name, "=", $value] ]) ? true : false;
	}

	public function response_error(String $error_alias, Array $failed_fields = [], Array $extra = [], Int $status_code = 400) {
		http_response_code($status_code);
		header("Content-Type: application/json");
		return json_encode(array_merge([
			"status" => false,
			"error_alias" => $error_alias,
			"failed_fields" => $failed_fields,
			"msg" => $this -> get_msg_by_alias($error_alias)
		], $extra));
	}

	public function response_success(Array $resp_data = []) {
		header("Content-Type: application/json");
		return json_encode([ 
			"status" => true,
			"data" => $resp_data
		]);
	}

	public function get_msg_by_alias(String $alias){
		return FCONF['text_msgs'][$alias];
	}

	public function compress_image(String $source, String $destination, Int $quality) {
		$info = getimagesize($source);

		if ($info['mime'] == 'image/jpeg') 
			$image = imagecreatefromjpeg($source);
		elseif ($info['mime'] == 'image/gif') 
			$image = imagecreatefromgif($source);
		elseif ($info['mime'] == 'image/png') 
			$image = imagecreatefrompng($source);

		imagejpeg($image, $destination, $quality);

		return $destination;
	}

	public function image_resize(String $file_name, String $output, Int $quality, Int $width, $height = 0) {
		list($wid, $ht) = \getimagesize($file_name);
		$r = $wid / $ht;
		$height = $height ? $height : $width / $r;

		if ($width / $height > $r) {
			$new_width = $height * $r;
			$new_height = $height;
		} else {
			$new_height = $width / $r;
			$new_width = $width;
		}
		
		$source = \imagecreatefromjpeg($file_name);
		$dst = \imagecreatetruecolor($new_width, $new_height);
		\imagecopyresampled($dst, $source, 0, 0, 0, 0, $new_width, $new_height, $wid, $ht);
		\imagejpeg($dst, $output, $quality);
	}

	public function get_current_page_num(): Int {
		return max(1, intval(isset($_GET["pn"]) ? $_GET["pn"] : 0));
	}

	public function get_limits_for_select_query(Int $per_page): Array {
		$current_page = $this -> get_current_page_num();
		$from = ($current_page - 1) * $per_page;
		return [$from, $per_page];
	}

	public function get_default_val_for_type(String $type) {
		$default_val = null;
		$types_default_vals = [
			"Int" => 0,
			"String" => "",
			"JSON" => "{}",
			"Float" => 0
		];

		return $types_default_vals[$type];
	}

	public function link_is_active(String $action, Array $params = []) {
		return app() -> routes -> urlto($action, $params) == app() -> router -> uri;
	}

	public function formatted_timestamp(String $timestamp, $with_clock = false): String {
		if($with_clock) {
			return date("d.m.Y H:i", strtotime($timestamp));
		}

		return date("d.m.Y", strtotime($timestamp));
	}

	public function convert_png_to_jpg($png_data) {
		$png_image = imagecreatefromstring($png_data);
		$jpg_image = imagecreatetruecolor(imagesx($png_image), imagesy($png_image));

		imagecopy($jpg_image, $png_image, 0, 0, 0, 0, imagesx($png_image), imagesy($png_image));

		ob_start();
		imagejpeg($jpg_image, NULL, 100);
		$jpg_data = ob_get_contents();
		ob_end_clean();

		imagedestroy($png_image);
		imagedestroy($jpg_image);

		return $jpg_data;
	}

	public function dayname_translate(String $dayname, String $lang = "ru"): ?String {
		$days = [
			["en" => "monday", "ru" => "понедельник", "uk" => "понеділок"],
			["en" => "tuesday", "ru" => "вторник", "uk" => "вівторок"],
			["en" => "wednesday", "ru" => "среда", "uk" => "середа"],
			["en" => "thursday", "ru" => "четверг", "uk" => "четвер"],
			["en" => "friday", "ru" => "пятница", "uk" => "п'ятниця"],
			["en" => "saturday", "ru" => "суббота", "uk" => "субота"],
			["en" => "sunday", "ru" => "воскресенье", "uk" => "неділя"]
		];

		$dayname = strtolower($dayname);

		foreach($days as $day) {
			if($day["en"] == $dayname) {
				return $day[$lang];
			}
		}

		return null;
	}

	public function generate_token(int $length = 16): String {
    $bytes = random_bytes((int)ceil($length / 2));
    $token = bin2hex($bytes);

    return substr($token, 0, $length);
	}

	public function fast_ping_tcp(string $host, int $port = 80, float $timeout = 0.2): bool {
		$start = microtime(true);

		$fp = @fsockopen($host, $port, $errno, $errstr, $timeout);

		if (!$fp) {
			return false;
		}

		fclose($fp);

		return (microtime(true) - $start) < $timeout;
	}
}