<?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;
        }

        // FIX: Trim only string values
        return array_map(function ($v) {
            return is_string($v) ? trim($v) : $v;
        }, $input);
    }
}

	
	function inputJsonNew() {
    $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;
    }

    foreach ($input as $key => $val) {
        if (is_string($val)) {
            $input[$key] = trim($val);
        }
    }

    return $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;
			// }
			$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);

			// Calculate estimated time in hours
			$timeInHours = ($speed > 0) ? $distance / $speed : 0;
			$timeInMinutes = round($timeInHours * 60); // Convert time to minutes

			// Determine if the time should be shown in hours or minutes
			if ($timeInMinutes >= 60) {
				$hours = floor($timeInMinutes / 60);
				$minutes = $timeInMinutes % 60;
				$timeDisplay = "{$hours} h" . ($hours > 1 ? "s" : "") . " {$minutes} min" . ($minutes > 1 ? "s" : "");
			} else {
				$timeDisplay = "{$timeInMinutes} min" . ($timeInMinutes > 1 ? "s" : "");
			}

			return [
				'distance' => strval($distance),
				'time' => $timeDisplay
			];
		}

	}

