<?php
if ( !defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

function mobile_api_is_licensed() {
	if ( str_contains( home_url(), 'tastewp.com' ) )
		return true;

	$license = get_option( 'mobile_api_license' );
	$is_licensed = maybe_unserialize( get_option( 'mobile_api_is_licensed' ) );

	if ( empty( $license ) )
		return false;

	if ( !empty( $is_licensed ) && $is_licensed['status'] == 'true' && $is_licensed['date'] == gmdate( 'Y-m-d' ) )
		return true;

	$response = wp_remote_post(
		'https://api.commotion.online/license.php',
		array(
			'body' => wp_json_encode( array( 'id' => $license ) ),
			'headers' => array( 'Content-Type' => 'application/json' ),
			'timeout' => 5,
			'redirection' => 5
		)
	);

	if ( is_wp_error( $response ) )
		return false;

	$body = wp_remote_retrieve_body( $response );

	if ( trim( $body ) === 'true' ) :
		$is_licensed = array( 'status' => 'true', 'date' => gmdate( 'Y-m-d' ) );
		update_option( 'mobile_api_is_licensed', $is_licensed );
		return true;
	endif;

	return false;
}

function mobile_api_request( $url ) {
	$username = get_option( 'mobile_api_username' );
	$password = get_option( 'mobile_api_password' );
	$locale = get_locale();
	$languages = explode( '_', $locale );
	$language = reset( $languages );

	$response = wp_remote_get(
		$url,
		array(
			'timeout'   => 10,
			'redirection' => 10,
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( $username.':'.$password ),
				'Accept' => 'application/vnd.de.mobile.api+json',
				'Accept-Language' => $language,
			),
		)
	);

	if ( is_wp_error( $response ) )
		return false;

	$body = wp_remote_retrieve_body( $response );
	$json = json_decode( $body );

	return $json;
}

function mobile_api_create_vehicle( $json ) {
	if ( property_exists( $json, 'category' ) ) :
		$category = get_term_by( 'name', mobile_api_translate_data_value( $json->category ), 'mobile_api_vehicle_category', ARRAY_A );
		if ( !$category )
			$category = wp_insert_term( mobile_api_translate_data_value( $json->category ), 'mobile_api_vehicle_category' );
	endif;

	if ( property_exists( $json, 'make' ) ) :
		$brand = get_term_by( 'name', $json->make, 'mobile_api_vehicle_category', ARRAY_A );
		if ( !$brand )
			$brand = wp_insert_term( $json->make, 'mobile_api_vehicle_category' );
	endif;

	if ( property_exists( $json, 'model' ) ) :
		$model = get_term_by( 'name', $json->model, 'mobile_api_vehicle_category', ARRAY_A );
		if ( !$model ) :
			$model = wp_insert_term( $json->model, 'mobile_api_vehicle_category',
				array(
					'description' => '',
					'slug' => strtolower( $json->model ),
					'parent' => $brand['term_id'] ?? 0
				)
			);
		endif;
	endif;

	$fuel = property_exists( $json, 'fuel' ) ? $json->fuel : '';
	$emissions = property_exists( $json, 'emissions' ) ? $json->emissions : '';
	$consumptions = property_exists( $json, 'consumptions' ) ? $json->consumptions : '';

	$post_category = array();
	if ( !empty( $category ) && is_array( $category ) && array_key_exists( 'term_id', $category ) )
		$post_category[] = $category['term_id'];
	if ( !empty( $brand ) && is_array( $brand ) && array_key_exists( 'term_id', $brand ) )
		$post_category[] = $brand['term_id'];
	if ( !empty( $model ) && is_array( $model ) && array_key_exists( 'term_id', $model ) )
		$post_category[] = $model['term_id'];

	$args = array(
		'post_title'     => $json->modelDescription,
		// 'post_name'      => sanitize_title( $json->modelDescription.'-'.$json->mobileAdId ),
		// 'post_name'      => wp_unique_post_slug( sanitize_title( $json->modelDescription ), 0, 'publish', 'mobile-api-vehicle', 0 ),
		'post_content'   => mobile_api_render_vehicle_content( mobile_api_description_to_html( $json->description ), $fuel, $emissions, $consumptions ),
		'post_excerpt'   => mobile_api_render_vehicle_content( $json->plainTextDescription, $fuel, $emissions, $consumptions, true ),
		'post_category'  => $post_category,
		'post_status'    => 'publish',
		'post_type'      => 'mobile-api-vehicle',
		// 'post_date'      => gmdate( 'Y-m-d H:i:s', strtotime( $json->creationDate ) ),
		// 'post_modified'  => gmdate( 'Y-m-d H:i:s', strtotime( $json->modificationDate ) ),
		'comment_status' => 'closed'
	);
	$post_id = wp_insert_post( $args );

	if ( is_wp_error( $post_id ) )
		echo esc_html( $post_id->get_error_message() );

	// Set categories
	wp_set_post_terms( $post_id, $post_category, 'mobile_api_vehicle_category' );

	// Import image
	$imagesArray = (array) $json->images;
	$image = end( reset( $imagesArray ) ); // First and biggest image
	mobile_api_import_vehicle_image( $image, $post_id, $json->modelDescription );

	// Set meta
	foreach ( $json AS $key => $value )
		add_post_meta( $post_id, 'mobile_api_'.$key, maybe_serialize( $value ) );

	// Log
	mobile_api_log( $json->mobileAdId, $post_id, 'CREATE' );

	return $post_id;
}

function mobile_api_update_vehicle( $json, $post_id ) {
	$fuel = property_exists( $json, 'fuel' ) ? $json->fuel : '';
	$emissions = property_exists( $json, 'emissions' ) ? $json->emissions : '';
	$consumptions = property_exists( $json, 'consumptions' ) ? $json->consumptions : '';

	wp_update_post( array(
		'ID'            => $post_id, 
		'post_title'    => $json->modelDescription,
		'post_content'  => mobile_api_render_vehicle_content( mobile_api_description_to_html( $json->description ), $fuel, $emissions, $consumptions ),
		'post_excerpt'  => mobile_api_render_vehicle_content( $json->plainTextDescription, $fuel, $emissions, $consumptions, true ),
		'post_date'     => gmdate( 'Y-m-d H:i:s', strtotime( $json->creationDate ) ),
		'post_modified' => gmdate( 'Y-m-d H:i:s', strtotime( $json->modificationDate ) )
	) );

	// Import image
	$imagesArray = (array) $json->images;
	$image = end( reset( $imagesArray ) ); // First and biggest image
	mobile_api_import_vehicle_image( $image, $post_id, $json->modelDescription );

	// Set meta
	foreach ( $json AS $key => $value )
		update_post_meta( $post_id, 'mobile_api_'.$key, maybe_serialize( $value ) );

	// Log
	mobile_api_log( $json->mobileAdId, $post_id, 'UPDATE' );
}

function mobile_api_import_vehicle_image( $image, $post_id, $title = '' ) {
	require_once( ABSPATH.'wp-admin/includes/media.php' );
	require_once( ABSPATH.'wp-admin/includes/file.php' );
	require_once( ABSPATH.'wp-admin/includes/image.php' );

	// Delete old image
	if ( has_post_thumbnail( $post_id ) )
		wp_delete_attachment( get_post_thumbnail_id( $post_id ), true );

	// Import new image
	$media_id = media_sideload_image( $image, $post_id, $title.' '.__( 'Image', 'ad-integration-for-mobile-de-api' ), 'id' );
	if ( !is_wp_error( $media_id ) ) :
		// Rename image
		require_once ABSPATH.'wp-admin/includes/file.php';
		WP_Filesystem(); // initialisieren
		global $wp_filesystem;

		$old_file = get_attached_file( $media_id );
		$info = pathinfo( $old_file );
		$dirname = untrailingslashit( $info['dirname'] );
		$ext = isset( $info['extension'] ) ? $info['extension'] : '';

		$new_basename = wp_unique_filename( $dirname, sanitize_title( $title ) . ( $ext ? '.' . $ext : '' ) );
		$new_file = $dirname.'/'.$new_basename;

		$moved = false;
		if ( is_object( $wp_filesystem ) && method_exists( $wp_filesystem, 'move' ) )
			$moved = $wp_filesystem->move( $old_file, $new_file, true );

		if ( $moved ) {
			update_attached_file( $media_id, $new_file );
			$metadata = wp_generate_attachment_metadata( $media_id, $new_file );

			if ( !is_wp_error( $metadata ) && $metadata )
				wp_update_attachment_metadata( $media_id, $metadata );

			$uploads = wp_get_upload_dir();
			$new_url = str_replace( $uploads['basedir'], $uploads['baseurl'], $new_file );
			wp_update_post( array(
				'ID'   => $media_id,
				'guid' => $new_url
			) );
		}

    	// Set thumbnail
		set_post_thumbnail( $post_id, $media_id );

		// Set meta data
		update_post_meta( $media_id, '_wp_attachment_image_alt', $title );
		wp_update_post( array(
			'ID'           => $media_id,
			'post_title'   => $title,
			// translators: %s is the title of the vehicle retrieved via json
			'post_excerpt' => sprintf( __( 'Image of "%s", retrieved via the mobile.de API', 'ad-integration-for-mobile-de-api' ), $title ), // Subtitle
			// translators: %s is the title of the vehicle retrieved via json
			'post_content' => sprintf( __( 'Image of "%s", retrieved via the mobile.de API', 'ad-integration-for-mobile-de-api' ), $title ), // Description
		) );
	endif;
}

function mobile_api_description_to_html( $raw ) {
    $text = html_entity_decode( (string) $raw, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
    $text = str_replace( ["\r\n", "\r"], "\n", $text );

    // -------------------------------------------------
    // 1) Listenmarker zuerst sichern – VOR der **-Verarbeitung
    //    damit \* **Text** → <li><strong>Text</strong></li>
    //    und nicht zu <li> + <h3> wird
    // -------------------------------------------------
    $text = preg_replace('/\\\\+\*(?!\*)/', "\n%%LI_STAR%%", $text);
    $text = preg_replace('/\\\\+-(?!-)/',   "\n%%LI_DASH%%", $text);

    // -------------------------------------------------
    // 2a) **Text:** oder **Text:\** → %%H3%%
    //     Kein Newline im Inhalt erlaubt
    // -------------------------------------------------
    $text = preg_replace('/\*\*([^*\n]+?)\\\\?\*\*/', "\n%%H3%%$1\n", $text);

    // -------------------------------------------------
    // 2b) Verbleibende \** → Zeilenumbruch + **
    // -------------------------------------------------
    $text = preg_replace('/\\\\+(\*\*)/', "\n$1", $text);

    // -------------------------------------------------
    // 3) Trennlinien: \---- → %%HR%%
    // -------------------------------------------------
    $text = preg_replace('/\\\\-{3,}/', "\n%%HR%%\n", $text);

    // -------------------------------------------------
    // 4) Backslash-Absatz-/Zeilenlogik
    // -------------------------------------------------
    $text = preg_replace('/([.!?])\\\\{2,}(?=\S)/', "$1\n\n", $text);
    $text = preg_replace('/\\\\{3,}/', "\n\n", $text);
    $text = preg_replace('/\\\\{2}/',  "\n",   $text);
    $text = preg_replace('/\\\\/',     "\n",   $text);

    // -------------------------------------------------
    // 5) Verbleibende **text** klassifizieren
    // -------------------------------------------------
    $lines_pre = explode("\n", $text);
    $lines_pre = array_map(function( $line ) {
        if ( strpos(trim($line), '%%H3%%') === 0 ) {
            return $line;
        }
        $trimmed = trim($line);
        if ( preg_match('/^\*\*([^*]+?)\*\*$/', $trimmed, $m) ) {
            return "\n%%H3%%" . trim($m[1]) . "\n";
        }
        $line = preg_replace('/\*\*([^*\n]+?)\*\*/', '%%BOLD_START%%$1%%BOLD_END%%', $line);
        return $line;
    }, $lines_pre);
    $text = implode("\n", $lines_pre);

    // Platzhalter auflösen
    $text = str_replace('%%LI_STAR%%', '* ', $text);
    $text = str_replace('%%LI_DASH%%',  '- ', $text);

    // -------------------------------------------------
    // 6) Restliche Backslashes + verwaiste ** entfernen
    // -------------------------------------------------
    $text = str_replace('\\', '', $text);
    $text = str_replace('**', '',  $text);

    // -------------------------------------------------
    // 7) Aufräumen
    // -------------------------------------------------
    $text = preg_replace("/\n{3,}/", "\n\n", $text);
    $text = trim($text);

    // -------------------------------------------------
    // 8) Zeilen zu HTML rendern
    // -------------------------------------------------
    $lines   = explode("\n", $text);
    $html    = '';
    $in_list = false;

    foreach ( $lines as $line ) {
        $line = trim($line);
        if ( $line === '' ) {
            if ( $in_list ) { $html .= "</ul>\n"; $in_list = false; }
            continue;
        }
        if ( $line === '%%HR%%' ) {
            if ( $in_list ) { $html .= "</ul>\n"; $in_list = false; }
            $html .= "<hr>\n";
            continue;
        }
        if ( strpos($line, '%%H3%%') === 0 ) {
            if ( $in_list ) { $html .= "</ul>\n"; $in_list = false; }
            $title = trim(substr($line, 6));
            $html .= "<h3>" . mobile_api_apply_inline_markup($title) . "</h3>\n";
            continue;
        }
        if ( preg_match('/^[-*]\s+(.+)$/', $line, $m) ) {
            if ( !$in_list ) { $html .= "<ul>\n"; $in_list = true; }
            $html .= "<li>" . mobile_api_apply_inline_markup(trim($m[1])) . "</li>\n";
            continue;
        }
        if ( $in_list ) { $html .= "</ul>\n"; $in_list = false; }
        $html .= "<p>" . mobile_api_apply_inline_markup($line) . "</p>\n";
    }

    if ( $in_list ) $html .= "</ul>\n";
    return $html;
}

function mobile_api_apply_inline_markup( $text ) {
	$text = esc_html($text);
	$text = str_replace('%%BOLD_START%%', '<strong>', $text);
	$text = str_replace('%%BOLD_END%%',   '</strong>', $text);
	$text = str_replace('%%BR%%',         '<br>',     $text);
	return $text;
}

function mobile_api_render_vehicle_content( $description, $fuel = '', $emissions = '', $consumptions = '', $short = false ) {
	$start = $short ? ', ' : '<p>';
	$end = $short ? '' : '</p>';
	$separator = $short ? ', ' : '<br>';

	$content = $description;

	if ( !$short )
		$content .= '<h4>'.__( 'Emission values', 'ad-integration-for-mobile-de-api' ).'</h4>';

	if ( !empty( $emissions ) && property_exists( $emissions, 'combined' ) ) {
		$combined = $emissions->combined;

		if ( !empty( $combined ) && property_exists( $combined, 'co2' ) ) {
			$content .= $start.__( 'CO₂ emissions (combined):', 'ad-integration-for-mobile-de-api' ).' '.$combined->co2.' g/km'.$separator;

			if ( !empty( $combined ) && property_exists( $combined, 'co2Class' ) )
				$separator.__( 'CO₂ class (combined):', 'ad-integration-for-mobile-de-api' ).' '.$combined->co2Class;

			$content .= $end;
		}
	}

	if ( !empty( $consumptions ) ) {
		foreach ( $consumptions AS $consumption ) {
			if ( !empty( $consumption ) && property_exists( $consumption, 'combined' ) )
				$content .= $start.'<strong>'.number_format_i18n( $consumption->combined, 1 ).' '.mobile_api_translate_consumption_unit( $fuel ).' '.__( 'combined', 'ad-integration-for-mobile-de-api' ).'</strong>'.$separator.number_format_i18n( $consumption->city, 1 ).' '.mobile_api_translate_consumption_unit( $fuel ).' '.__( 'City', 'ad-integration-for-mobile-de-api' ).$separator.number_format_i18n( $consumption->suburban, 1 ).' '.mobile_api_translate_consumption_unit( $fuel ).' '.__( 'Suburban', 'ad-integration-for-mobile-de-api' ).$separator.number_format_i18n( $consumption->rural, 1 ).' '.mobile_api_translate_consumption_unit( $fuel ).' '.__( 'Rural', 'ad-integration-for-mobile-de-api' ).$separator.number_format_i18n( $consumption->highway, 1 ).' '.mobile_api_translate_consumption_unit( $fuel ).' '.__( 'Highway', 'ad-integration-for-mobile-de-api' ).$end;
		}
	}

	if ( !$short )
		$content .= mobile_api_get_wltp_hint().mobile_api_get_emissions_hint();

	return $content;
}

function mobile_api_get_available_meta_options( $meta_key, $post_type = 'mobile-api-vehicle', $post_status = 'publish' ) {
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	return $wpdb->get_col(
		$wpdb->prepare(
			"SELECT DISTINCT meta_value 
			FROM {$wpdb->postmeta} pm
			JOIN {$wpdb->posts} p ON p.ID = pm.post_id
			WHERE pm.meta_key = %s
			AND p.post_type = %s
			AND p.post_status = %s",
			'mobile_api_'.$meta_key,
			$post_type,
			$post_status
		)
	);
}

function mobile_api_get_meta_exclude() {
	$meta_exclude = array( 'mobileAdId', 'mobileSellerId', 'creationDate', 'modificationDate', 'vehicleClass', 'modelDescription', 'wltpValues', 'consumptionUnit', 'envkvCompliant', 'envkvPetrolType', 'description', 'plainTextDescription', 'images', 'detailPageUrl', 'kba', 'seller', 'deliveryDate', 'price', 'priceRating' );
	return $meta_exclude;
}

function mobile_api_translate_data( $data ) {
	$data_descriptions = array(
		'category' => __( 'Vehicle Category', 'ad-integration-for-mobile-de-api' ),
		'make' => __( 'Brand', 'ad-integration-for-mobile-de-api' ),
		'model' => __( 'Model', 'ad-integration-for-mobile-de-api' ),
		'condition' => __( 'Condition', 'ad-integration-for-mobile-de-api' ),
		'usageType' => __( 'Usage Type', 'ad-integration-for-mobile-de-api' ),
		'firstRegistration' => __( 'First Registration', 'ad-integration-for-mobile-de-api' ),
		'mileage' => __( 'Mileage', 'ad-integration-for-mobile-de-api' ),
		'vin' => __( 'VIN', 'ad-integration-for-mobile-de-api' ),
		'internalNumber' => __( 'Vehicle Number', 'ad-integration-for-mobile-de-api' ),
		'cubicCapacity' => __( 'Trunk Volume', 'ad-integration-for-mobile-de-api' ),
		'power' => __( 'Power', 'ad-integration-for-mobile-de-api' ),
		'gearbox' => __( 'Gear', 'ad-integration-for-mobile-de-api' ),
		'weight' => __( 'Weight', 'ad-integration-for-mobile-de-api' ),
		'cylinder' => __( 'Cylinder', 'ad-integration-for-mobile-de-api' ),
		'fuelTankVolume' => __( 'Tank Volume', 'ad-integration-for-mobile-de-api' ),
		'battery' => __( 'Battery', 'ad-integration-for-mobile-de-api' ),
		'batteryCapacity' => __( 'Battery Capacity', 'ad-integration-for-mobile-de-api' ),
		'batteryWarranty' => __( 'Battery Warranty', 'ad-integration-for-mobile-de-api' ),
		'range' => __( 'Range', 'ad-integration-for-mobile-de-api' ),
		'equivalentAllElectricRange' => __( 'Electric Range (EAER)', 'ad-integration-for-mobile-de-api' ),
		'driveType' => __( 'Drive Type', 'ad-integration-for-mobile-de-api' ),
		'trailerCouplingType' => __( 'Trailer Coupling Type', 'ad-integration-for-mobile-de-api' ),
		'trailerLoadBraked' => __( 'Braked Trailer Load', 'ad-integration-for-mobile-de-api' ),
		'trailerLoadUnbraked' => __( 'Unbraked Trailer Load', 'ad-integration-for-mobile-de-api' ),
		'fuel' => __( 'Fuel', 'ad-integration-for-mobile-de-api' ),
		'consumptions' => __( 'Consumptions', 'ad-integration-for-mobile-de-api' ),
		'emissions' => __( 'Emissions', 'ad-integration-for-mobile-de-api' ),
		'emissionSticker' => __( 'Emission Sticker', 'ad-integration-for-mobile-de-api' ),
		'emissionClass' => __( 'Emission Class', 'ad-integration-for-mobile-de-api' ),
		'wltpValues' => __( 'WLTP Values', 'ad-integration-for-mobile-de-api' ),
		'costModel' => __( 'Costs', 'ad-integration-for-mobile-de-api' ),
		'exteriorColor' => __( 'Exterior Color', 'ad-integration-for-mobile-de-api' ),
		'manufacturerColorName' => __( 'Manufacturer Color Name', 'ad-integration-for-mobile-de-api' ),
		'doors' => __( 'Doors', 'ad-integration-for-mobile-de-api' ),
		'seats' => __( 'Seats', 'ad-integration-for-mobile-de-api' ),
		'interiorColor' => __( 'Interior Color', 'ad-integration-for-mobile-de-api' ),
		'interiorType' => __( 'Interior Type', 'ad-integration-for-mobile-de-api' ),
		'numberOfPreviousOwners' => __( 'Previous Owners', 'ad-integration-for-mobile-de-api' ),
		'airbag' => __( 'Airbag', 'ad-integration-for-mobile-de-api' ),
		'radio' => __( 'Radio', 'ad-integration-for-mobile-de-api' ),
		'countryVersion' => __( 'Country Version', 'ad-integration-for-mobile-de-api' ),
		'climatisation' => __( 'Climatisation', 'ad-integration-for-mobile-de-api' ),
		'parkingAssistants' => __( 'Parking Assistants', 'ad-integration-for-mobile-de-api' ),
		'speedControl' => __( 'Speed Control', 'ad-integration-for-mobile-de-api' ),
		'headlightType' => __( 'Headlight Type', 'ad-integration-for-mobile-de-api' ),
		'bendingLightsType' => __( 'Bending Lights Type', 'ad-integration-for-mobile-de-api' ),
		'daytimeRunningLamps' => __( 'Daytime running lights', 'ad-integration-for-mobile-de-api' ),
		'modelRange' => __( 'Model', 'ad-integration-for-mobile-de-api' ),
		'trimLine' => __( 'Trim Line', 'ad-integration-for-mobile-de-api' ),
		'axles' => __( 'Axles', 'ad-integration-for-mobile-de-api' ),
		'constructionYear' => __( 'Construction Year', 'ad-integration-for-mobile-de-api' ),
		'dimension' => __( 'Dimension', 'ad-integration-for-mobile-de-api' ),
		'licensedWeight' => __( 'Licensed Weight', 'ad-integration-for-mobile-de-api' ),
		'numberOfBunks' => __( 'Bunks', 'ad-integration-for-mobile-de-api' ),
		'heating' => __( 'Heating', 'ad-integration-for-mobile-de-api' ),
		'seatbeltSeats' => __( 'Seatbelt Seats', 'ad-integration-for-mobile-de-api' ),
		'deliveryPeriod' => __( 'Delivery Period', 'ad-integration-for-mobile-de-api' ),
		'lastMaintenanceDate' => __( 'Last Maintenance (Date)', 'ad-integration-for-mobile-de-api' ),
		'generalInspection' => __( 'General Inspection', 'ad-integration-for-mobile-de-api' ),
		'maxNoseWeight' => __( 'Max. Nose Weight', 'ad-integration-for-mobile-de-api' )
	);

	if ( array_key_exists( $data, $data_descriptions ) )
		return $data_descriptions[$data];

	return $data;
}

function mobile_api_translate_data_value( $value ) {
	// Documentation: https://services.mobile.de/docs/search-api.html

	$data_values = array(
		// Category: Car
		'Cabrio' => __( 'Cabrio', 'ad-integration-for-mobile-de-api' ),
		'EstateCar' => __( 'Estate Car', 'ad-integration-for-mobile-de-api' ),
		'Limousine' => __( 'Limousine', 'ad-integration-for-mobile-de-api' ),
		'OffRoad' => __( 'Offroad', 'ad-integration-for-mobile-de-api' ),
		'SmallCar' => __( 'Small Car', 'ad-integration-for-mobile-de-api' ),
		'SportsCar' => __( 'Sports Car', 'ad-integration-for-mobile-de-api' ),
		'Van' => __( 'Van', 'ad-integration-for-mobile-de-api' ),
		'OtherCar' => __( 'Other Car', 'ad-integration-for-mobile-de-api' ),

		// Category: Motorbike
		'ChopperAndCruiser' => __( 'Chopper / Cruiser', 'ad-integration-for-mobile-de-api' ),
		'CombinationAndSidecar' => __( 'Combination / Sidecar', 'ad-integration-for-mobile-de-api' ),
		'DirtBike' => __( 'Dirt Bike', 'ad-integration-for-mobile-de-api' ),
		'EnduroAndTouringEnduro' => __( 'Enduro / Touring Enduro', 'ad-integration-for-mobile-de-api' ),
		'LightweightMotorcycleAndMotorbike' => __( 'Lightweight Motorcycle / Motorbike', 'ad-integration-for-mobile-de-api' ),
		'MotorAssistedBicycleAndSmallMoped' => __( 'Motor Assisted Bicycle / Small Moped', 'ad-integration-for-mobile-de-api' ),
		'Motorcycle' => __( 'Motorcycle', 'ad-integration-for-mobile-de-api' ),
		'NakedBike' => __( 'Naked Bike', 'ad-integration-for-mobile-de-api' ),
		'Pocketbike' => __( 'Pocket Bike', 'ad-integration-for-mobile-de-api' ),
		'Quad' => __( 'Quad', 'ad-integration-for-mobile-de-api' ),
		'Racing' => __( 'Racing', 'ad-integration-for-mobile-de-api' ),
		'RallyAndCross' => __( 'Rallye / Cross', 'ad-integration-for-mobile-de-api' ),
		'Roadster' => __( 'Roadster', 'ad-integration-for-mobile-de-api' ),
		'Scooter' => __( 'Scooter', 'ad-integration-for-mobile-de-api' ),
		'SportTouringMotorcycle' => __( 'Sport Touring Motorcycle', 'ad-integration-for-mobile-de-api' ),
		'SportsAndSuperSportsBike' => __( 'Sports / Super Sports Bike', 'ad-integration-for-mobile-de-api' ),
		'Streetfighter' => __( 'Streetfighter', 'ad-integration-for-mobile-de-api' ),
		'SuperMoto' => __( 'Super Moto', 'ad-integration-for-mobile-de-api' ),
		'Tourer' => __( 'Tourer', 'ad-integration-for-mobile-de-api' ),
		'Trike' => __( 'Trike', 'ad-integration-for-mobile-de-api' ),
		'OtherMotorbike' => __( 'Other Motorbike', 'ad-integration-for-mobile-de-api' ),

		// Category: Motorhome
		'Alcoves' => __( 'Alcoves', 'ad-integration-for-mobile-de-api' ),
		'CabinMotorhome' => __( 'Cabin Motorhome', 'ad-integration-for-mobile-de-api' ),
		'Caravan' => __( 'Caravan', 'ad-integration-for-mobile-de-api' ),
		'Integrated' => __( 'Integrated Motorhome', 'ad-integration-for-mobile-de-api' ),
		'MobileHome' => __( 'Mobile Home', 'ad-integration-for-mobile-de-api' ),
		'MotorHomesAndPickup' => __( 'Motorhome Pickup', 'ad-integration-for-mobile-de-api' ),
		'PartlyIntegrated' => __( 'Partly Integrated Motorhome', 'ad-integration-for-mobile-de-api' ),
		'VanMotorhome' => __( 'Van', 'ad-integration-for-mobile-de-api' ),
		'OtherMotorhome' => __( 'Other Motorhome', 'ad-integration-for-mobile-de-api' ),
		'MotorHomesAndOther' => __( 'Other Motorhome', 'ad-integration-for-mobile-de-api' ),

		// Airbags
		'DRIVER_AIRBAG' => __( 'Driver Airbag', 'ad-integration-for-mobile-de-api' ),
		'FRONT_AIRBAGS' => __( 'Front Airbags', 'ad-integration-for-mobile-de-api' ),
		'FRONT_AND_SIDE_AIRBAGS' => __( 'Front and Side Airbags', 'ad-integration-for-mobile-de-api' ),
		'FRONT_AND_SIDE_AND_MORE_AIRBAGS' => __( 'Front, Side and more Airbags', 'ad-integration-for-mobile-de-api' ),

		// Battery
		'BATTERY_PURCHASED' => __( 'Battery included', 'ad-integration-for-mobile-de-api' ),
		'BATTERY_RENTED' => __( 'Battery rented', 'ad-integration-for-mobile-de-api' ),
		'BATTERY_MISSING' => __( 'Battery missing', 'ad-integration-for-mobile-de-api' ),

		// Breakdown services
		'SPARE_WHEEL' => __( 'Spare Wheel', 'ad-integration-for-mobile-de-api' ),
		'EMERGENCY_WHEEL' => __( 'Emergency Wheel', 'ad-integration-for-mobile-de-api' ),
		'REPAIR_KIT' => __( 'Repair Kit', 'ad-integration-for-mobile-de-api' ),

		// Condition
		'NEW' => __( 'New', 'ad-integration-for-mobile-de-api' ),
		'USED' => __( 'Used', 'ad-integration-for-mobile-de-api' ),

		// Colors
		'BLACK' => __( 'Black', 'ad-integration-for-mobile-de-api' ),
		'GREY' => __( 'Gray', 'ad-integration-for-mobile-de-api' ),
		'BEIGE' => __( 'Beige', 'ad-integration-for-mobile-de-api' ),
		'BROWN' => __( 'Brown', 'ad-integration-for-mobile-de-api' ),
		'RED' => __( 'Red', 'ad-integration-for-mobile-de-api' ),
		'GREEN' => __( 'Green', 'ad-integration-for-mobile-de-api' ),
		'BLUE' => __( 'Blue', 'ad-integration-for-mobile-de-api' ),
		'PURPLE' => __( 'Purple', 'ad-integration-for-mobile-de-api' ),
		'GOLD' => __( 'Gold', 'ad-integration-for-mobile-de-api' ),
		'WHITE' => __( 'White', 'ad-integration-for-mobile-de-api' ),
		'ORANGE' => __( 'Orange', 'ad-integration-for-mobile-de-api' ),
		'SILVER' => __( 'Silver', 'ad-integration-for-mobile-de-api' ),
		'YELLOW' => __( 'Yellow', 'ad-integration-for-mobile-de-api' ),
		'OTHER_INTERIOR_COLOR' => __( 'Other Interior Color', 'ad-integration-for-mobile-de-api' ),

		// Climatisation
		'NO_CLIMATISATION' => __( 'No Climatisation', 'ad-integration-for-mobile-de-api' ),
		'MANUAL_CLIMATISATION' => __( 'Climatisation', 'ad-integration-for-mobile-de-api' ),
		'AUTOMATIC_CLIMATISATION' => __( 'Automatic Climatisation', 'ad-integration-for-mobile-de-api' ),
		'AUTOMATIC_CLIMATISATION_2_ZONES' => __( 'Automatic Climatisation (2 zones)', 'ad-integration-for-mobile-de-api' ),
		'AUTOMATIC_CLIMATISATION_3_ZONES' => __( 'Automatic Climatisation (3 zones)', 'ad-integration-for-mobile-de-api' ),
		'AUTOMATIC_CLIMATISATION_4_ZONES' => __( 'Automatic Climatisation (4 zones)', 'ad-integration-for-mobile-de-api' ),

		// Doors
		'TWO_OR_THREE' => '2/3',
		'FOUR_OR_FIVE' => '4/5',
		'SIX_OR_SEVEN' => '6/7',

		// Drive
		'FRONT' => __( 'Front Wheel Drive', 'ad-integration-for-mobile-de-api' ),
		'REAR' => __( 'Rear Wheel Drive', 'ad-integration-for-mobile-de-api' ),
		'ALL_WHEEL' => __( 'All Wheel Drive', 'ad-integration-for-mobile-de-api' ),

		// Driving cab
		'DOUBLE_CABIN' => __( 'Double Cabin', 'ad-integration-for-mobile-de-api' ),
		'SLEEPING_BERTH' => __( 'Sleeping Berth', 'ad-integration-for-mobile-de-api' ),
		'LOCAL_TRAFFIC' => __( 'Local Traffic', 'ad-integration-for-mobile-de-api' ),
		'LONG_DISTANCE_TRAFFIC' => __( 'Long Distance Traffic', 'ad-integration-for-mobile-de-api' ),

		// Emissionsticker
		'EMISSIONSSTICKER_NONE' => __( '1 (None)', 'ad-integration-for-mobile-de-api' ),
		'EMISSIONSSTICKER_RED' => __( '2 (Red)', 'ad-integration-for-mobile-de-api' ),
		'EMISSIONSSTICKER_YELLOW' => __( '3 (Yellow)', 'ad-integration-for-mobile-de-api' ),
		'EMISSIONSSTICKER_GREEN' => __( '4 (Green)', 'ad-integration-for-mobile-de-api' ),

		// Fuel
		'ELECTRICITY' => __( 'Electricity', 'ad-integration-for-mobile-de-api' ),
		'HYBRID' => __( 'Hybrid (Petrol/Electricity)', 'ad-integration-for-mobile-de-api' ),
		'HYBRID_DIESEL' => __( 'Hybrid (Diesel/Electricity)', 'ad-integration-for-mobile-de-api' ),
		'PETROL' => __( 'Petrol', 'ad-integration-for-mobile-de-api' ),
		'DIESEL' => __( 'Diesel', 'ad-integration-for-mobile-de-api' ),
		'GAS' => __( 'Gas', 'ad-integration-for-mobile-de-api' ),
		'LPG' => __( 'LPG', 'ad-integration-for-mobile-de-api' ),
		'CNG' => __( 'CNG', 'ad-integration-for-mobile-de-api' ),
		'HYDROGENIUM' => __( 'Hydrogenium', 'ad-integration-for-mobile-de-api' ),
		'ETHANOL' => __( 'Ethanol', 'ad-integration-for-mobile-de-api' ),
		'WOOD' => __( 'Wood', 'ad-integration-for-mobile-de-api' ),
		'OTHER' => __( 'Other', 'ad-integration-for-mobile-de-api' ),

		// Gearbox
		'AUTOMATIC_GEAR' => __( 'Automatic Gear', 'ad-integration-for-mobile-de-api' ),
		'SEMIAUTOMATIC_GEAR' => __( 'Semiautomatic Gear', 'ad-integration-for-mobile-de-api' ),
		'MANUAL_GEAR' => __( 'Manual Gear', 'ad-integration-for-mobile-de-api' ),

		// Interior
		'ALCANTARA' => __( 'Alcantara', 'ad-integration-for-mobile-de-api' ),
		'VELOUR' => __( 'Velour', 'ad-integration-for-mobile-de-api' ),
		'FABRIC' => __( 'Fabric', 'ad-integration-for-mobile-de-api' ),
		'IMITATION_LEATHER' => __( 'Imitation Leather', 'ad-integration-for-mobile-de-api' ),
		'PARTIAL_LEATHER' => __( 'Partial Leather', 'ad-integration-for-mobile-de-api' ),
		'LEATHER' => __( 'Leather', 'ad-integration-for-mobile-de-api' ),
		'OTHER_INTERIOR_TYPE' => __( 'Other Interior Type', 'ad-integration-for-mobile-de-api' ),

		// Lights
		'DAYTIME_RUNNING_LIGHTS' => __( 'Daytime Running Lights', 'ad-integration-for-mobile-de-api' ),
		'LED_RUNNING_LIGHTS' => __( 'LED Running Lights', 'ad-integration-for-mobile-de-api' ),

		'LED_HEADLIGHTS' => __( 'LED Headlights', 'ad-integration-for-mobile-de-api' ),
		'XENON_HEADLIGHTS' => __( 'Xenon Headlights', 'ad-integration-for-mobile-de-api' ),
		'BI_XENON_HEADLIGHTS' => __( 'Bi-Xenon Headlights', 'ad-integration-for-mobile-de-api' ),
		'LASER_HEADLIGHTS' => __( 'Laser Headlights', 'ad-integration-for-mobile-de-api' ),

		'BENDING_LIGHTS' => __( 'Bending Lights', 'ad-integration-for-mobile-de-api' ),
		'ADAPTIVE_BENDING_LIGHTS' => __( 'Adaptive Bending Lights', 'ad-integration-for-mobile-de-api' ),

		// Parking
		'FRONT_SENSORS' => __( 'Front Sensors', 'ad-integration-for-mobile-de-api' ),
		'REAR_SENSORS' => __( 'Rear Sensors', 'ad-integration-for-mobile-de-api' ),
		'REAR_VIEW_CAM' => __( 'Rear View Cam', 'ad-integration-for-mobile-de-api' ),
		'CAM_360_DEGREES' => __( 'Cam 360°', 'ad-integration-for-mobile-de-api' ),
		'AUTOMATIC_PARKING' => __( 'Automatic Parking', 'ad-integration-for-mobile-de-api' ),

		// Radio
		'TUNER' => __( 'Tuner', 'ad-integration-for-mobile-de-api' ),
		'DAB_RADIO' => __( 'DAB Radio', 'ad-integration-for-mobile-de-api' ),

		// Speed controls
		'CRUISE_CONTROL' => __( 'Cruise Control', 'ad-integration-for-mobile-de-api' ),
		'ADAPTIVE_CRUISE_CONTROL' => __( 'Adaptive Cruise Control (ACC)', 'ad-integration-for-mobile-de-api' ),

		// Trailer coupling
		'TRAILER_COUPLING_PREPARATION' => __( 'Trailer Coupling Preparation', 'ad-integration-for-mobile-de-api' ),
		'TRAILER_COUPLING_FIX' => __( 'Fixed Trailer Coupling', 'ad-integration-for-mobile-de-api' ),
		'TRAILER_COUPLING_DETACHABLE' => __( 'Detachable Trailer Coupling', 'ad-integration-for-mobile-de-api' ),
		'TRAILER_COUPLING_SWIVELING' => __( 'Swiveling Trailer Coupling', 'ad-integration-for-mobile-de-api' ),

		// Usage type
		'PRE_REGISTRATION' => __( 'Pre Registration', 'ad-integration-for-mobile-de-api' ),
		'EMPLOYEES_CAR' => __( 'Employees Car', 'ad-integration-for-mobile-de-api' ),
		'CLASSIC' => __( 'Classic', 'ad-integration-for-mobile-de-api' ),
		'DEMONSTRATION' => __( 'Demonstration', 'ad-integration-for-mobile-de-api' ),

		// Driving modes
		'FULLY_SUSPENDED_DRIVE' => __( 'Fully Suspended Drive', 'ad-integration-for-mobile-de-api' ),
		'CHAIN_DRIVE' => __( 'Chain Drive', 'ad-integration-for-mobile-de-api' ),
		'BELT_DRIVE' => __( 'Belt Drive', 'ad-integration-for-mobile-de-api' ),

		// Wheel base
		'SHORT' => __( 'Short', 'ad-integration-for-mobile-de-api' ),
		'MIDDLE' => __( 'Middle', 'ad-integration-for-mobile-de-api' ),
		'LONG' => __( 'Long', 'ad-integration-for-mobile-de-api' ),
		'EXTRA_LONG' => __( 'Extra Long', 'ad-integration-for-mobile-de-api' ),

		// Wheel drive
		'WHEEL_DRIVE_4x2' => '4x2',
		'WHEEL_DRIVE_4x4' => '4x4',
		'WHEEL_DRIVE_6x2' => '6x2',
		'WHEEL_DRIVE_6x4' => '6x4',
		'WHEEL_DRIVE_6x6' => '6x6',
		'WHEEL_DRIVE_8x4' => '8x4',
		'WHEEL_DRIVE_8x6' => '8x6',
		'WHEEL_DRIVE_8x8' => '8x8',
		'WHEEL_DRIVE_8x2' => '8x2'
	);

	if ( array_key_exists( $value, $data_values ) )
		return $data_values[$value];

	return $value;
}

function mobile_api_translate_consumption_title( $fuel ) {
	$consumption_unit = __( 'Fuel consumption with a discharged battery:', 'ad-integration-for-mobile-de-api' );

	if ( $fuel == 'ELECTRICITY' || $fuel == 'power' )
		$consumption_unit = __( 'Power consumption with purely electric drive:', 'ad-integration-for-mobile-de-api' );

	return $consumption_unit;
}

function mobile_api_translate_consumption_unit( $fuel ) {
	$consumption_unit = 'l/100km';

	if ( $fuel == 'ELECTRICITY' || $fuel == 'power' || $fuel == 'weightedCombinedPower' )
		$consumption_unit = 'kWh/100km';

	return $consumption_unit;
}

function mobile_api_get_emission_class_image( $classes ) {
	$class = implode( '-', $classes );
	$path = plugin_dir_url( __DIR__ ).'assets/img/';
	$img = $path.'co2class-'.$class.'.jpg';

	return $img;
}

function mobile_api_get_wltp_hint() {
	// translators: %s is the url to the guide
	$html = '<p>'.sprintf( __( 'This information is provided in accordance with the German Car Energy Consumption Labeling Regulation (Car Energy Labeling Ordinance). The stated values were determined using the prescribed WLTP (Worldwide Harmonized Light-Duty Vehicles Test Procedure) measurement method. A car\'s fuel consumption and CO₂ emissions depend not only on the car\'s efficient use of fuel, but also on driving style and other non-technical factors. CO₂ is the greenhouse gas primarily responsible for global warming. Further information on official fuel consumption and official specific CO₂ emissions, and, if applicable, on the power consumption of new cars, can be found in the "Guide to Official Fuel Consumption, Official Specific CO₂ Emissions, and Official Power Consumption of New Cars“, which is available free of charge at all sales outlets where new cars are displayed or offered, from "Deutsche Automobil Treuhand GmbH" and online. <a href="%s" target="_blank" rel="nofollow">Guide</a>', 'ad-integration-for-mobile-de-api' ), 'https://www.dat.de/co2/' ).'</p>';

	return $html;
}

function mobile_api_get_emissions_hint() {
	$html = '<p>'.__( 'Only the CO₂ emissions generated by the operation of the car are reported. CO₂ emissions generated or avoided by the production and provision of the car, as well as the fuel or energy sources, are not taken into account when determining CO₂ emissions according to the WLTP.', 'ad-integration-for-mobile-de-api' ).'</p>';

	return $html;
}

function mobile_api_get_data_hints( $data ) {
	$hints = array(
		'consumptions' => mobile_api_get_wltp_hint(),
		'wltpValues' => mobile_api_get_wltp_hint(),
		'costModel' => mobile_api_get_wltp_hint(),
		'range' => mobile_api_get_wltp_hint(),
		'equivalentAllElectricRange' => mobile_api_get_wltp_hint(),

		'emissions' => mobile_api_get_emissions_hint(),

		'condition' => __( 'Damaged vehicles are vehicles with unrepaired, significant damage, e.g., due to a traffic accident, fire, hail, water, engine, or transmission damage. This does not include: 1.) normal wear and tear; 2.) minor damage; 3.) a previously accident-damaged but since repaired vehicle. Furthermore, a vehicle is only considered accident-free if it has never suffered significant accident damage. This includes all damage that goes beyond minor damage (e.g., scratches in the paint). Even if the damage has been properly repaired, the vehicle is no longer considered accident-free. Finally, "roadworthy" means that the vehicle is technically capable of being driven (no engine damage, etc.). This does not refer to aspects of road safety or the vehicle\'s other roadworthiness.', 'ad-integration-for-mobile-de-api' ),
		// translators: %s is the url to more information
		'co2Costs' => sprintf( __( 'Due to CO₂ pricing, future increases in fuel costs are possible. Future CO₂ price developments are uncertain, so potential CO₂ costs are calculated based on three assumed CO₂ prices for the period from 2025 to 2034. Actual CO₂ prices may be higher or lower than those assumed in the model calculations used here. CO₂ costs are included in fuel costs when refueling. <a href="%s" target="_blank" rel="nofollow">More information</a>', 'ad-integration-for-mobile-de-api' ), 'https://www.alternativ-mobil.info/' ),
		'emissionClass' => __( 'The emissions class (or emission standard) evaluates a vehicle\'s pollutant emissions (e.g., Euro 4, 5, or 6; the higher the number, the fewer pollutants). The emissions class also determines the vehicle\'s environmental sticker: Only low emissions earn a green sticker. A good emissions class is worthwhile for the owner, because the fewer pollutants emitted, the lower the vehicle tax.', 'ad-integration-for-mobile-de-api' ),
		'emissionSticker' => __( 'The environmental badge evaluates a vehicle\'s pollutant emissions using a color scale: green (low emissions), yellow (medium), and red (high). A green badge is required to drive in urban environmental zones; driving without one risks a fine. Low pollutant emissions also pay off financially: the lower the emissions, the lower the vehicle tax.', 'ad-integration-for-mobile-de-api' )

	);

	if ( array_key_exists( $data, $hints ) )
		return $hints[$data];

	return false;
}

function mobile_api_get_button_classes() {
	$classes = 'button btn btn-primary et_pb_button wp-block-button__link wp-element-button wc-block-components-product-button__button';
	return esc_attr( $classes );
}

function mobile_api_log( $ad_key, $post_id, $action ) {
	global $wpdb;
	$table_name = $wpdb->prefix.'mobile_api_logs';
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) ) ) == $table_name ) {
		$wpdb->insert( $table_name,
			array( 'ad_key' => $ad_key, 'post_id' => $post_id, 'action' => $action ),
			array( '%d', '%d', '%s' )
		);
	}
}
