<?php

// round time to nearest precision = time_space
function round_time($timestamp, $precision) {
	$timestamp = strtotime($timestamp);
	$precision = 60 * $precision;
	return date('H:i', ceil($timestamp / $precision) * $precision);
}

function update_post_meta_action() {
    check_ajax_referer('update_post_meta_nonce', 'nonce');
    if (isset($_POST['post_id']) && isset($_POST['meta_key']) && isset($_POST['meta_value'])) {
        $post_id = $_POST['post_id'];
        $meta_key = $_POST['meta_key'];
        $meta_value = wp_unslash($_POST['meta_value']);
        
        update_post_meta($post_id, $meta_key, $meta_value);
        wp_cache_delete($post_id, 'post_meta');
    }
    wp_die(); // Always remember to exit
}
add_action('wp_ajax_update_post_meta_action', 'update_post_meta_action');
add_action('wp_ajax_nopriv_update_post_meta_action', 'update_post_meta_action');

// discord
function sendToDiscordAlexis($value){
    $config = GocarsConfig::get_instance();

    if (!$config->has('DISCORD_WEBHOOK_TOKEN') || !$config->has('DISCORD_WEBHOOK_ID')) {
        error_log('Gocars functions.php: Discord webhook not configured - ' . $value);
        return;
    }

    $json_data = json_encode([
        "content" => json_encode($value),
        "username" => $_SERVER['HTTP_HOST'] . ' functions',
        "tts" => false,
        "embeds" => []
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    $webhook_id = $config->get('DISCORD_WEBHOOK_ID');
    $webhook_token = $config->get('DISCORD_WEBHOOK_TOKEN');
    $webhook_url = "https://discord.com/api/webhooks/{$webhook_id}/{$webhook_token}";

    $ch = curl_init($webhook_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        error_log('Gocars Discord Error (functions.php): ' . curl_error($ch));
    }
    
    curl_close($ch);
}

/**
 * Check if response was blocked by Imunify360 and notify Discord.
 * Returns true if blocked (caller should return []), false otherwise.
 */
function gocars_check_imunify_block($response, $req_url = '') {
    if (!is_array($response)) {
        return false;
    }
    $body = wp_remote_retrieve_body($response);
    if (stripos($body, 'Imunify360') !== false || stripos($body, 'Imunify') !== false) {
        sendToDiscordAlexis('Imunify360 BLOCKED: Access denied by Imunify360 bot-protection. IPs used for automation should be whitelisted.');
        return true;
    }
    return false;
}

/**
 * Canonical domain meta key for grouping shortcodes that share one Gocars subdomain.
 *
 * @param mixed $slug Raw post meta "domain".
 * @return string Lowercased trimmed slug, empty if invalid.
 */
function gocars_normalize_domain_slug( $slug ) {
	if ( ! is_string( $slug ) ) {
		return '';
	}
	return strtolower( trim( $slug ) );
}

/**
 * Detach cloned graph for per-post mutations (locations / descriptions) without corrupting shared prefetch.
 *
 * @param mixed $data Object, array, or scalar from json_decode().
 * @return mixed
 */
function gocars_deep_clone_for_sync( $data ) {
	if ( null === $data ) {
		return null;
	}
	if ( ! is_object( $data ) && ! is_array( $data ) ) {
		return $data;
	}
	$json = wp_json_encode( $data );
	if ( false === $json ) {
		return $data;
	}
	$cloned = json_decode( $json );
	return null === $cloned ? $data : $cloned;
}

/**
 * Whether URL should use optional transient-backed HTTP cache (*.gocars.gr API responses).
 *
 * @param string $url
 * @return bool
 */
function gocars_should_cache_remote_url( $url ) {
	if ( ! is_string( $url ) ) {
		return false;
	}
	return strpos( $url, 'gocars.gr' ) !== false;
}

/**
 * Wraps wp_safe_remote_get() with optional transient body cache for gocars.gr URLs.
 *
 * Filters:
 * - gocars_http_transient_enabled (bool) Default true — set false from tests / custom flows.
 * - gocars_http_cache_ttl_seconds (int) TTL in seconds — default aligns with spaced WP-Cron (see admin settings).
 *
 * Cached entries store response body strings only for HTTP 200 and skip obvious Imunify blocks.
 *
 * @param string $url  Request URL.
 * @param array  $args wp_remote_* args (timeout, headers, …).
 * @return array|WP_Error
 */
function gocars_wp_safe_remote_get_cached( $url, array $args = array() ) {
	if ( ! gocars_should_cache_remote_url( $url )
		|| false === apply_filters( 'gocars_http_transient_enabled', true, $url, $args ) ) {
		return wp_safe_remote_get( $url, $args );
	}

	$transient_name = 'gocars_http_' . md5( $url );
	$cached          = get_transient( $transient_name );

	if ( is_string( $cached ) ) {
		return array(
			'headers'       => array(),
			'body'          => $cached,
			'response'      => array(
				'code'    => 200,
				'message' => get_status_header_desc( 200 ),
			),
			'cookies'       => array(),
			'filename'      => null,
			'http_response' => null,
		);
	}

	$response_json = wp_safe_remote_get( $url, $args );

	if ( is_wp_error( $response_json ) ) {
		return $response_json;
	}

	$code = wp_remote_retrieve_response_code( $response_json );
	$body = wp_remote_retrieve_body( $response_json );

	if ( 200 === (int) $code && '' !== $body && ! gocars_check_imunify_block( $response_json, $url ) ) {
		$default_ttl = 45 * MINUTE_IN_SECONDS;
		$ttl         = (int) apply_filters( 'gocars_http_cache_ttl_seconds', $default_ttl, $url, $args );
		if ( $ttl > 0 ) {
			set_transient( $transient_name, $body, $ttl );
		}
	}

	return $response_json;
}

/**
 * Invalidate all transient bodies created by {@see gocars_wp_safe_remote_get_cached()} (whole site — site-specific prefixes).
 *
 * Called after manual shortcode refresh or save-driven API rebuild so admins always see fresh payloads.
 *
 * @return void
 */
function gocars_flush_gocars_http_cache() {
	global $wpdb;
	$wpdb->query(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_gocars_http_%' OR option_name LIKE '_transient_timeout_gocars_http_%'"
	);
}

function replaceCustomCharacters($string) {
    $description = preg_replace(array('/\n/', '/\r/'), "<br>", $string);
                
    // Replace multiple consecutive <br> tags with single <br>
    $description = preg_replace('/(<br\s*\/?>){2,}/', '<br>', $description);
    
    // Replace Unicode non-breaking space \u00a0 with regular space
    $description = str_replace('\u00a0', ' ', $description);
    
    // Decode any remaining Unicode escape sequences
    $description = json_decode('"' . $description . '"');

    return $description;
}
        
function dates_options($domain = null) {
    if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/dates/";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url);

    // Continuing if we got a result
    if (is_wp_error($response_json)) {
        // Handle error...
        return [];
    }

	// Try/catch for json_decode operation
    try {
        // Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));

        return $response_object;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }
}

// locations
function getGcLocations($lang = 1, $domain = null) {
    if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/locations/?lang=$lang";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url, [
        'timeout' => 15,
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ],
    ]);
    	
    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
	
	// Try/catch for json_decode operation
    try {
		// Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));
		if (is_array($response_object)) {
            $response_object = (object) $response_object;
        }
        return $response_object;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }
}

// options
function getGcOptions($domain = null) {
    if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/options/";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url, [
        'timeout' => 15,
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ],
    ]);

    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
    if (gocars_check_imunify_block($response_json, $req_url)) {
        return [];
    }
	
	// Try/catch for json_decode operation
    try {
		// Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));
		if (is_array($response_object->i18n)) {
            $response_object->i18n = (object) $response_object->i18n;
        }
        return $response_object;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }
}

// multilingual options
function getI18nOptions($lang = 1, $domain = null){
    if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }	
    $req_url = "https://$domain.gocars.gr/api/v1/options/?lang=$lang";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url, [
        'timeout' => 15,
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ],
    ]);
    
    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
	
	// Try/catch for json_decode operation
    try {
		// Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));
        if (is_array($response_object->i18n)) {
            $response_object->i18n = (object) $response_object->i18n;
        }
		
        // Check if the response was successfully decoded
        if ($response_object !== null) {
            // Check if 'i18n' key exists
            if (is_object($response_object) && property_exists($response_object, 'i18n') && is_object($response_object->i18n) && property_exists($response_object->i18n, $lang)) {
                $response_object = $response_object->i18n->$lang;
                return $response_object;
            }
        }

        return [];
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }
}

// age groups 
function getGcAgeGroups($domain = null) {
    if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/age-groups/";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url, [
        'timeout' => 15,
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ],
    ]);
    
    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
	
	// Try/catch for json_decode operation
    try {
		// Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));
		
        return $response_object;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }

}

// one model from every type
function getGcCarModels($lang = 1, $domain = null) {
	if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/models/?lang=$lang";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url);
    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
	
	// Try/catch for json_decode operation
    try {
		// Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));

        // Check for duplicates based on type_name
        $filtered_response = [];
        $type_names = [];

        foreach ($response_object as $item) {
            $type_name = $item->type_name;

            // Check if type_name already exists
            if (!in_array($type_name, $type_names)) {
                // Clean the model_description field
                if (isset($item->model_description)) {
                    $item->model_description = replaceCustomCharacters($item->model_description);
                }
                
                // Add to the filtered list
                $filtered_response[] = $item;

                // Add type_name to the list
                $type_names[] = $type_name;
            }
        }

        return $filtered_response;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }
}

// all models from every type
function getAllGcCarModels($lang = 1, $domain = null) {
	if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/models/?lang=$lang";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url, [
        'timeout' => 15,
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ],
    ]);
    
    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
	
	// Try/catch for json_decode operation
    try {


        $response_object = json_decode(wp_remote_retrieve_body($response_json)); 
        
        foreach ($response_object as $vehicle) {
            if (isset($vehicle->model_description)) {
                $vehicle->model_description = replaceCustomCharacters($vehicle->model_description);
            }
        }
        
		
        return $response_object;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }

}

// all models from a specific type
function getGcCarModelsByType($type_name = null, $lang = 1, $domain = null) {
	if ($domain == null || $type_name == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/models/?lang=$lang";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url, [
        'timeout' => 15,
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ],
    ]);
    
    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
	
	// Try/catch for json_decode operation
    try {
		// Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));
		
        // Filter entries based on the provided type name
        $filtered_response = [];
        foreach ($response_object as $item) {
            if ($item->type_name === $type_name) {
                // Clean the model_description field
                if (isset($item->model_description)) {
                    $item->model_description = replaceCustomCharacters($item->model_description);
                }
                $filtered_response[] = $item;
            }
        }

        return $filtered_response;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }

}

/**
 * HTTP: decoded vehicles from getModelsDataForPlugin for one language ID.
 *
 * @return array<int, object>
 */
function gocars_fetch_models_payload_for_lang( $domain_slug, $lang_id ) {
	if ( empty( $domain_slug ) ) {
		return array();
	}
	$req_url       = 'https://' . $domain_slug . '.gocars.gr/api/v1/models/?lang=' . intval( $lang_id );
	$response_json = gocars_wp_safe_remote_get_cached(
		$req_url,
		array(
			'timeout' => 15,
			'headers' => array(
				'Accept'       => 'application/json',
				'Content-Type' => 'application/json; charset=utf-8',
			),
		)
	);
	if ( is_wp_error( $response_json ) ) {
		return array();
	}
	try {
		$response_object = json_decode( wp_remote_retrieve_body( $response_json ) );
		if ( ! is_array( $response_object ) && ! is_object( $response_object ) ) {
			return array();
		}
		return array_values( (array) $response_object );
	} catch ( Exception $e ) {
		return array();
	}
}

/**
 * HTTP: decoded vehicles from getModelsDataForPlugin without lang query.
 *
 * @return array<int, object>
 */
function gocars_fetch_models_payload_no_lang( $domain_slug ) {
	if ( empty( $domain_slug ) ) {
		return array();
	}
	$req_url       = 'https://' . $domain_slug . '.gocars.gr/api/v1/models/';
	$response_json = gocars_wp_safe_remote_get_cached(
		$req_url,
		array(
			'timeout' => 15,
			'headers' => array(
				'Accept'       => 'application/json',
				'Content-Type' => 'application/json; charset=utf-8',
			),
		)
	);
	if ( is_wp_error( $response_json ) ) {
		return array();
	}
	try {
		$response_object = json_decode( wp_remote_retrieve_body( $response_json ) );
		if ( ! is_array( $response_object ) && ! is_object( $response_object ) ) {
			return array();
		}
		return array_values( (array) $response_object );
	} catch ( Exception $e ) {
		return array();
	}
}

/**
 * @param array<int, object> $vehicles Mutable list — applies replaceCustomCharacters per item.
 */
function gocars_models_apply_descriptions_all( $vehicles ) {
	foreach ( $vehicles as $vehicle ) {
		if ( isset( $vehicle->model_description ) ) {
			$vehicle->model_description = replaceCustomCharacters( $vehicle->model_description );
		}
	}
	return $vehicles;
}

/**
 * One vehicle per distinct type_name — same rules as getGcCarModels.
 *
 * @param array<int, object> $vehicles
 * @return array<int, object>
 */
function gocars_models_dedupe_first_per_type_name( $vehicles ) {
	$filtered   = array();
	$type_names = array();
	foreach ( $vehicles as $item ) {
		if ( ! isset( $item->type_name ) ) {
			continue;
		}
		$tn = $item->type_name;
		if ( ! in_array( $tn, $type_names, true ) ) {
			$filtered[]   = $item;
			$type_names[] = $tn;
		}
	}
	return $filtered;
}

/**
 * @param array<int, object> $vehicles
 * @return array<int, object>
 */
function gocars_models_filter_by_vehicle_type( $vehicles, $vehicle_type ) {
	$filtered = array();
	foreach ( $vehicles as $item ) {
		if ( isset( $item->vehicle_type ) && $item->vehicle_type === $vehicle_type ) {
			$filtered[] = $item;
		}
	}
	return $filtered;
}

/**
 * @param array<int, object> $vehicles
 * @return array<string, array<int, object>>
 */
function gocars_models_group_by_type_name( $vehicles ) {
	$out = array();
	foreach ( $vehicles as $vehicle ) {
		if ( ! isset( $vehicle->type_name ) ) {
			continue;
		}
		$tn = $vehicle->type_name;
		if ( ! isset( $out[ $tn ] ) ) {
			$out[ $tn ] = array();
		}
		$out[ $tn ][] = $vehicle;
	}
	return $out;
}

/**
 * Map language id (from Gocars) to key on language_locale JSON (e.g. en, el).
 */
function gocars_admin_language_code_for_lang_id( $post_id, $lang_id ) {
	$locale_raw = get_post_meta( $post_id, 'language_locale', true );
	if ( '' === $locale_raw || false === $locale_raw ) {
		return null;
	}
	$locales = json_decode( wp_unslash( $locale_raw ) );
	if ( ! is_object( $locales ) ) {
		return null;
	}
	foreach ( $locales as $code => $info ) {
		if ( is_object( $info ) && isset( $info->id ) && (int) $info->id === (int) $lang_id ) {
			return $code;
		}
	}
	return null;
}

/**
 * Turn getGcLocations-shaped payloads (sequential array, numeric-key object, or single location) into a list of objects.
 *
 * @param mixed $locations
 * @return object[]
 */
function gocars_normalize_locations_to_list( $locations ) {
	if ( null === $locations || false === $locations || '' === $locations ) {
		return array();
	}
	if ( is_array( $locations ) ) {
		$out = array();
		foreach ( $locations as $item ) {
			if ( is_object( $item ) && isset( $item->id ) ) {
				$out[] = $item;
			}
		}
		return $out;
	}
	if ( is_object( $locations ) ) {
		if ( isset( $locations->id ) ) {
			return array( $locations );
		}
		$out = array();
		foreach ( $locations as $item ) {
			if ( is_object( $item ) && isset( $item->id ) ) {
				$out[] = $item;
			}
		}
		return $out;
	}
	return array();
}

/**
 * Human-readable location label from API/meta object.
 *
 * @param object $loc
 * @return string
 */
function gocars_location_display_name( $loc ) {
	if ( ! is_object( $loc ) || ! isset( $loc->id ) ) {
		return '';
	}
	if ( isset( $loc->location_name ) && $loc->location_name !== '' ) {
		return $loc->location_name;
	}
	if ( isset( $loc->name ) && $loc->name !== '' ) {
		return $loc->name;
	}
	if ( isset( $loc->locationName ) && $loc->locationName !== '' ) {
		return $loc->locationName;
	}
	return (string) $loc->id;
}

/**
 * Locations list for lang id when stored on post (locations_data meta).
 *
 * @return array|object|null Raw branch like getGcLocations, or null if missing — caller runs gocars_normalize_locations_to_list.
 */
function gocars_admin_locations_from_meta( $post_id, $lang_id ) {
	$code = gocars_admin_language_code_for_lang_id( $post_id, $lang_id );
	if ( null === $code ) {
		return null;
	}
	$raw = get_post_meta( $post_id, 'locations_data', true );
	if ( '' === $raw || false === $raw ) {
		return null;
	}
	$root = json_decode( wp_unslash( $raw ) );
	if ( ! is_object( $root ) || ! isset( $root->$code ) ) {
		return null;
	}
	return $root->$code;
}

/**
 * Branch of all_vehicles_data (or similar) for one language — from post meta.
 *
 * @return array<int, object>|null
 */
function gocars_admin_vehicle_models_branch_from_meta( $post_id, $lang_id, $meta_key = 'all_vehicles_data' ) {
	$code = gocars_admin_language_code_for_lang_id( $post_id, $lang_id );
	$raw  = get_post_meta( $post_id, $meta_key, true );
	if ( '' === $raw || false === $raw ) {
		return null;
	}
	$root = json_decode( wp_unslash( $raw ) );
	if ( ! is_object( $root ) ) {
		return null;
	}
	if ( null !== $code && isset( $root->$code ) ) {
		$branch = $root->$code;
		return is_array( $branch ) ? $branch : array( $branch );
	}
	if ( isset( $root->en ) ) {
		$branch = $root->en;
		return is_array( $branch ) ? $branch : array( $branch );
	}
	return null;
}

// vehicle types
function getGcVehicleTypes( $domain = null, $preloaded_options = null, $preloaded_models_no_lang = null ) {
    if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }

	$response_object = $preloaded_options;
	if ( $response_object === null ) {
		$req_url       = "https://$domain.gocars.gr/api/v1/options/";
		$response_json = gocars_wp_safe_remote_get_cached($req_url);
		if (is_wp_error($response_json)) {
			return [];
		}
		try {
			$response_object = json_decode(wp_remote_retrieve_body($response_json));
		} catch (Exception $e) {
			return [];
		}
	}

	try {
		if ( ! is_object( $response_object ) ) {
			return [];
		}

		if (isset($response_object->i18n) && is_array($response_object->i18n)) {
            $response_object->i18n = (object) $response_object->i18n;
        }

		foreach ($response_object as $key => $item) {
			if ($key == 'o_show_vehicle_type' && $item == 0) {
				return [];
			}
	    }

		if ( null !== $preloaded_models_no_lang ) {
			$decoded = $preloaded_models_no_lang;
			if ( ! is_array( $decoded ) || empty( $decoded ) ) {
				return [];
			}
		} else {
			$req_url = "https://$domain.gocars.gr/api/v1/models/";

			$response_json = gocars_wp_safe_remote_get_cached($req_url, [
				'timeout' => 15,
				'headers' => [
					'Accept' => 'application/json',
					'Content-Type' => 'application/json; charset=utf-8',
				],
			]);

			if (is_wp_error($response_json)) {
				return [];
			}

			try {
				$decoded = json_decode(wp_remote_retrieve_body($response_json));
				$decoded = ( is_array( $decoded ) || is_object( $decoded ) ) ? array_values( (array) $decoded ) : [];
			} catch (Exception $e) {
				return [];
			}
		}

			$vehicle_types = [];
			foreach ($decoded as $item) {
				if (! isset( $item->vehicle_type ) ) {
					continue;
				}
				$vehicle_type = $item->vehicle_type;
				if (!in_array($vehicle_type, $vehicle_types, true)) {
					$vehicle_types[] = $vehicle_type;
				}
			}

			return $vehicle_types;

    } catch (Exception $e) {
        return [];
    }

}

// all models per vehicle type 
function getGcCarModelsByVehicleType($vehicle_type = null, $lang = 1, $domain = null) {
	if ($domain == null || $vehicle_type == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }
	$req_url = "https://$domain.gocars.gr/api/v1/models/?lang=$lang";

	// Fetching JSON
	$response_json = gocars_wp_safe_remote_get_cached($req_url, [
        'timeout' => 15,
        'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ],
    ]);

    // Continuing if we got a result
    if (is_wp_error($response_json)) {
		// Handle error...
        return [];
    }
	
	// Try/catch for json_decode operation
    try {
		// Decoding
        $response_object = json_decode(wp_remote_retrieve_body($response_json));
		
        // Filter entries based on the provided type name
        $filtered_response = [];
        foreach ($response_object as $item) {
            if ($item->vehicle_type === $vehicle_type) {
                // Clean the model_description field
                if (isset($item->model_description)) {
                    $item->model_description = replaceCustomCharacters($item->model_description);
                }
                $filtered_response[] = $item;
            }
        }

        return $filtered_response;
    } catch (Exception $e) {
        // Handle JSON parse error...
        return [];
    }
}

// attempts
function getGcAttempts( $domain = null, $preloaded_options = null ) {
    if ($domain == null) {
        return;
    }
    if (is_numeric($domain)) {
        $shortcode_id = $domain;
        $domain = get_post_meta( $shortcode_id, 'domain', true );
    }

	$response_object = $preloaded_options;
	if ( $response_object === null ) {
		$req_url       = "https://$domain.gocars.gr/api/v1/options/";
		$response_json = gocars_wp_safe_remote_get_cached($req_url, [
			'timeout' => 15,
			'headers' => [
				'Accept' => 'application/json',
				'Content-Type' => 'application/json; charset=utf-8',
			],
		]);

		if (is_wp_error($response_json)) {
			return [];
		}

		try {
			$response_object = json_decode(wp_remote_retrieve_body($response_json));
		} catch (Exception $e) {
			return [];
		}
	}

	try {
		if ( ! is_object( $response_object ) ) {
			return [];
		}

        if (isset($response_object->i18n) && is_array($response_object->i18n)) {
            $response_object->i18n = (object) $response_object->i18n;
        }
        
		foreach ($response_object as $key => $item) {
		    if (!property_exists($response_object, 'o_last_search') || $response_object->o_last_search != '1') {
                return [];
            }
        }
		$req_url = "https://$domain.gocars.gr/api/v1/attempts/";

		$response_json = gocars_wp_safe_remote_get_cached($req_url, [
            'timeout' => 15,
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json; charset=utf-8',
            ],
        ]);

		if (is_wp_error($response_json)) {
			return [];
		}

		try {
			$response_object = json_decode(wp_remote_retrieve_body($response_json));

            date_default_timezone_set('Europe/Athens');
            $current_date = new DateTime();
            $pickup_date = new DateTime($response_object->datetime_from);
            $dropoff_date = new DateTime($response_object->datetime_to);

            if ($pickup_date->getTimestamp() < $current_date->getTimestamp() || $dropoff_date->getTimestamp() < $current_date->getTimestamp()) {
                return [];
            }
			return $response_object;

		} catch (Exception $e) {
			return [];
    	}
    } catch (Exception $e) {
        return [];
    }
}

function get_post_meta_without_cache($post_id, $meta_key) {
    global $wpdb;

    // Clear the cache for this post meta key
    wp_cache_delete($post_id, 'post_meta');

    $result = $wpdb->get_var($wpdb->prepare(
        "SELECT meta_value FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s",
        $post_id,
        $meta_key
    ));

    // If the meta value was serialized, maybe_unserialize it.
    return maybe_unserialize($result);
}
