<?php
defined('BASEPATH') OR exit('No direct script access allowed');

	if (!function_exists('convert_to_webp')) {
		function convert_to_webp($source, $destination, $quality = 80) {
			$image_info = getimagesize($source);
			$mime = $image_info['mime'];

			switch ($mime) {
				case 'image/jpeg':
					$image = imagecreatefromjpeg($source);
					break;
				case 'image/png':
					$image = imagecreatefrompng($source);
					imagepalettetotruecolor($image); // For better compression
					imagealphablending($image, true);
					imagesavealpha($image, true);
					break;
				case 'image/gif':
					$image = imagecreatefromgif($source);
					break;
				default:
					return false; // Unsupported image type
			}

			$result = imagewebp($image, $destination, $quality);
			imagedestroy($image); // Free memory

			return $result;
		}
    }
	// if (!function_exists('inputJson')) {
	// 	function inputJson(){
	// 		$inputJSON = file_get_contents('php://input');
	// 		$inputJSON = preg_replace('/,(\s*[\}\]])/', '$1', $inputJSON);
	// 		$input = json_decode($inputJSON, true);

	// 		if (json_last_error() !== JSON_ERROR_NONE || !is_array($input)) {
	// 			outputJSON(400, 'error', 'Invalid JSON input.');
	// 			return;
	// 		}
	// 		return array_map('trim', $input); 
	// 	}
	// }

	if (!function_exists('inputJson')) {
		function inputJson(){
			$inputJSON = file_get_contents('php://input');
			$inputJSON = preg_replace('/,(\s*[\}\]])/', '$1', $inputJSON);
			$input = json_decode($inputJSON, true);

			if (json_last_error() !== JSON_ERROR_NONE || !is_array($input)) {
				outputJSON(400, 'error', 'Invalid JSON input.');
				return;
			}
			
			return array_map(function($value) {
				return is_string($value) ? trim($value) : $value;
			}, $input);
		}
	}

	
	if (!function_exists('checkValidation')) {
		 function checkValidation($input,$rules){
			$CI = &get_instance();
			if (!isset($CI->form_validation)) {
				$CI->load->library('form_validation');
			}
			$CI->form_validation->set_data($input);
			$CI->form_validation->set_rules($rules);

			if (!$CI->form_validation->run()) {
				outputJSON(400, 'error', 'Validation failed.', $CI->form_validation->error_array());
				return;
			}
		}
	}
	 
	 if (!function_exists('outputJSON')) {
		function outputJSON($statusCode, $status, $message, $data = null)
		{
			$CI = &get_instance();
			$response = array(
				'status' => $status,
				'status_code' => $statusCode,
				'message' => $message,
			);
			if (!empty($data)) {
				$response['data'] = $data;
			}else{
				$response['data'] = null;
			}
			$CI->output
				->set_content_type('application/json')
				->set_status_header($statusCode)
				->set_output(json_encode($response))
				->_display();
			exit;
		}
	}

if (!function_exists('calculateDistance')) {
	function calculateDistance($lat1, $lon1, $lat2, $lon2){
		$speed = 30;
		$earth_radius = 6371; // Radius of the Earth in km

		$dLat = deg2rad($lat2 - $lat1);
		$dLon = deg2rad($lon2 - $lon1);

		$a = sin($dLat / 2) * sin($dLat / 2) +
			 cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
			 sin($dLon / 2) * sin($dLon / 2);

		$c = 2 * atan2(sqrt($a), sqrt(1 - $a));

		$distance = $earth_radius * $c; // Distance in km
		$distance = round($distance, 2);

		return  strval($distance);
	}

}

if (!function_exists('travel_time')) {
	function travel_time($total_distance){
		$total_time = round(($total_distance / avg_speed) * 60); // Time in minutes
		if ($total_time >= 60) {
			$hours = floor($total_time / 60);
			$minutes = $total_time % 60;
			$timeDisplay = "{$hours} hour" . ($hours > 1 ? "s" : "") . " {$minutes} minute" . ($minutes > 1 ? "s" : "");
		} else {
			$timeDisplay = "{$total_time} minute" . ($total_time > 1 ? "s" : "");
		}
		return $timeDisplay;
	}

}