<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://www.eurostocks.com
 * @since      1.0.0
 *
 * @package    Eurostocks
 * @subpackage Eurostocks/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Eurostocks
 * @subpackage Eurostocks/admin
 * @author     EuroStocks <info@eurostocks.com>
 */
class Eurostocks_Admin
{

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct($plugin_name, $version)
	{

		$this->plugin_name = $plugin_name;
		$this->version = $version;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{

		wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/eurostocks-admin.css', array(), $this->version, 'all');
		wp_enqueue_style($this->plugin_name . '-select2', plugin_dir_url(__FILE__) . 'css/select2.css', array(), $this->version, 'all');
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts()
	{

		$ajax_nonce = wp_create_nonce("eurostocks_nonce");
		wp_enqueue_media();
		wp_enqueue_script('jquery-ui-sortable');
		wp_enqueue_script($this->plugin_name . '-select2', plugin_dir_url(__FILE__) . 'js/select2.min.js', array('jquery'), $this->version, true);

		wp_enqueue_script($this->plugin_name . '-admin', plugin_dir_url(__FILE__) . 'js/eurostocks-admin.js', array('jquery'), $this->version, true);
		wp_localize_script(
			$this->plugin_name . '-admin',
			'validajax',
			array(
				'admin_url' => admin_url('admin-ajax.php'),
				'security'  => $ajax_nonce,
			)
		);

		wp_localize_script(
			$this->plugin_name . '-admin',
			'eurostocksAdminL10n',
			array(
				'locale' => get_locale(),
				'apiStats' => array(
					'fillBothDates'       => __('Please fill in both From and To.', 'eurostocks'),
					'invalidDateFormat'   => __('Use format yyyy-mm-dd.', 'eurostocks'),
					'missingCredentials'  => __('Please enter valid API credentials first.', 'eurostocks'),
					'fetchError'          => __('Could not fetch statistics.', 'eurostocks'),
					'rangeLabelPrefix'    => __('Current period:', 'eurostocks'),
				),
			)
		);
	}

	public function add_plugin_admin_menu()
	{
		/*
		* Add a settings page for this plugin to the Settings menu.
		*/
		add_menu_page(
			__('EuroStocks', 'eurostocks'),
			'EuroStocks',
			'manage_options',
			'eurostocks',
			'',
			'dashicons-car',
			90
		);

		add_submenu_page(
			'eurostocks',
			'Settings',
			__('Settings', 'eurostocks'),
			'manage_options',
			'eurostocks',
			array($this, 'display_settings_callback')
		);

		// check if options eurostocks_transmissions is set
		if (get_option('eurostocks_transmissions')) {
			add_submenu_page(
				'eurostocks',
				'Makes',
				__('Makes', 'eurostocks'),
				'manage_options',
				'eurostocks-merken',
				array($this, 'display_makes_callback')
			);

			add_submenu_page(
				'eurostocks',
				__('Plugin statistics', 'eurostocks'),
				__('Plugin statistics', 'eurostocks'),
				'manage_options',
				'eurostocks-analytics',
				array($this, 'display_analytics_callback')
			);

			add_submenu_page(
				'eurostocks',
				__('API statistics', 'eurostocks'),
				__('API statistics', 'eurostocks'),
				'manage_options',
				'eurostocks-api-statistics',
				array($this, 'display_api_statistics_callback')
			);

			add_submenu_page(
				'eurostocks',
				'Anti spam',
				__('Anti spam', 'eurostocks'),
				'manage_options',
				'eurostocks-anti-spam',
				array($this, 'display_ip_log_callback')
			);

			add_submenu_page(
				'eurostocks',
				'IP visit log',
				__('IP visit log', 'eurostocks'),
				'manage_options',
				'eurostocks-ip-visit-log',
				array($this, 'display_ip_visit_log_callback')
			);

			add_submenu_page(
				'eurostocks',
				'Price breakdown',
				__('Price breakdown', 'eurostocks'),
				'manage_options',
				'eurostocks-price-structure',
				array($this, 'display_price_structure_callback')
			);
		}
	}

	public function display_ip_log_callback()
	{
		$results = $this->get_ip_visit_statistics();
		$verification_entries = Eurostocks_Email_Verification::get_all_status_entries();
		$verification_entries_by_ip = array();

		foreach ($verification_entries as $entry) {
			$ip = isset($entry['ip']) ? $entry['ip'] : '';
			if ('' === $ip) {
				continue;
			}
			if (!isset($verification_entries_by_ip[$ip])) {
				$verification_entries_by_ip[$ip] = array();
			}
			$verification_entries_by_ip[$ip][] = $entry;
		}

		$ip_metadata = Eurostocks_Anti_Spam_Settings::get_ip_metadata();
		$verification_required_rows = array();
		$options = Eurostocks_Anti_Spam_Settings::get_options();
		$blocked_ips = Eurostocks_Anti_Spam_Settings::get_blocked_ips($options);
		$verification_cutoff = time() - DAY_IN_SECONDS;
		foreach ($ip_metadata as $ip => $meta) {
			$status = isset($meta['status']) ? $meta['status'] : '';
			if ('verify_email' !== $status) {
				continue;
			}

			// Skip if there is an active verification entry (email already submitted/pending).
			if (isset($verification_entries_by_ip[$ip]) && !empty($verification_entries_by_ip[$ip])) {
				continue;
			}
			$updated_at = isset($meta['updated_at']) ? (int) $meta['updated_at'] : 0;

			// Hide stale or cleared entries: skip if not blocked and last update older than 24h (or unknown).
			if (!in_array($ip, $blocked_ips, true)) {
				if (0 === $updated_at || $updated_at < $verification_cutoff) {
					continue;
				}
			}

			$verification_required_rows[] = array(
				'ip'           => $ip,
				'reason_key'   => isset($meta['reason_key']) ? $meta['reason_key'] : '',
				'reason_label' => Eurostocks_Anti_Spam_Settings::get_reason_label(isset($meta['reason_key']) ? $meta['reason_key'] : ''),
				'page_type'    => isset($meta['page_type']) ? $meta['page_type'] : '',
				'updated_at'   => $updated_at,
				'details'      => isset($meta['details']) ? $meta['details'] : array(),
			);
		}
		$blocked_ip_rows = Eurostocks_Anti_Spam_Settings::get_blocked_ip_rows();

		include_once('partials/eurostocks-admin-ipdashboard-display.php');
	}

	public function display_ip_visit_log_callback() {
		$results = $this->get_ip_visit_statistics();

		include_once('partials/eurostocks-admin-ip-visit-log.php');
	}

	public function display_price_structure_callback() {
		$vehicle = null;
		$vehicle_id = '';
		$lookup_value = '';
		$error_message = '';
		$co2_value = '';
		$price_fields = array();
		$vehicle_image = '';

		if (
			isset($_POST['eurostocks_price_lookup_nonce']) &&
			check_admin_referer('eurostocks_price_lookup', 'eurostocks_price_lookup_nonce')
		) {
			$lookup_value = isset($_POST['mobile_id']) ? sanitize_text_field(wp_unslash($_POST['mobile_id'])) : '';
			$vehicle_id = $this->extract_mobile_de_id($lookup_value);

			if ('' === $vehicle_id) {
				$error_message = __('Please enter a valid mobile.de ID or URL.', 'eurostocks');
			} else {
				$login = get_option($this->plugin_name);
				if (
					!is_array($login) ||
					!isset($login['username'], $login['password'], $login['api_key']) ||
					'' === $login['username'] ||
					'' === $login['password'] ||
					'' === $login['api_key']
				) {
					$error_message = __('Please configure the Eurostocks API credentials in Settings first.', 'eurostocks');
				} else {
					$lang_data = eurostocks_get_language_details();
					$lang = isset($lang_data['default_lang']) ? $lang_data['default_lang'] : 'nl';

					$client = new Eurostocks_Request($login['username'], $login['password'], $login['api_key']);
					$data = $client->getVehicleDetails($vehicle_id, $lang);

					if (404 === $data) {
						$error_message = __('Vehicle not found on mobile.de.', 'eurostocks');
					} elseif (429 === $data) {
						$error_message = __('Request limit reached, please try again later.', 'eurostocks');
					} elseif (is_string($data)) {
						$error_message = $data;
					} elseif (is_array($data) && isset($data['vehicle'])) {
						$vehicle = $data['vehicle'];
						$co2_value = $this->resolve_vehicle_co2_value($vehicle);
						$price_fields = $this->build_price_structure_fields($vehicle, $co2_value);
						$vehicle_image = $this->get_vehicle_first_image($vehicle);

						$this->log_price_structure_request($vehicle, $vehicle_id);
					} else {
						$error_message = __('Unknown error while fetching vehicle data.', 'eurostocks');
					}
				}
			}
		}

		include_once('partials/eurostocks-admin-price-structure.php');
	}

	public function display_api_statistics_callback() {
		$default_period = 'current_month';
		$has_credentials = $this->has_api_credentials();

		$default_range = $this->calculate_api_statistics_range($default_period);
		if (is_wp_error($default_range)) {
			$default_range = array('from' => '', 'to' => '');
		}

		$statistics_totals = array(
			'TotalRequests'       => null,
			'TotalListRequests'   => null,
			'TotalDetailRequests' => null,
			'TotalSearchRequests' => null,
		);

		include_once('partials/eurostocks-admin-api-statistics.php');
	}

	private function has_api_credentials() {
		$login = get_option($this->plugin_name);
		if (!is_array($login)) {
			return false;
		}

		return isset($login['username'], $login['password'], $login['api_key'])
			&& '' !== $login['username']
			&& '' !== $login['password']
			&& '' !== $login['api_key'];
	}

	private function get_api_credentials() {
		if (!$this->has_api_credentials()) {
			return null;
		}

		$login = get_option($this->plugin_name);

		return array(
			'username' => $login['username'],
			'password' => $login['password'],
			'api_key'  => $login['api_key'],
		);
	}

	private function calculate_api_statistics_range($period, $custom_from = '', $custom_to = '') {
		$timezone = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone(wp_timezone_string());
		$today = new DateTimeImmutable('now', $timezone);
		$today = $today->setTime(0, 0, 0);

		switch ($period) {
			case 'today':
				$from = $today;
				$to = $today;
				break;
			case 'yesterday':
				$from = $today->modify('-1 day');
				$to = $from;
				break;
			case 'current_month':
				$from = new DateTimeImmutable('first day of this month', $timezone);
				$from = $from->setTime(0, 0, 0);
				$to = $today;
				break;
			case 'previous_month':
				$from = new DateTimeImmutable('first day of last month', $timezone);
				$from = $from->setTime(0, 0, 0);
				$to = new DateTimeImmutable('last day of last month', $timezone);
				$to = $to->setTime(0, 0, 0);
				break;
			case 'custom':
				$from = DateTimeImmutable::createFromFormat('Y-m-d', $custom_from, $timezone);
				$to = DateTimeImmutable::createFromFormat('Y-m-d', $custom_to, $timezone);

				if (!$from || $from->format('Y-m-d') !== $custom_from) {
					return new WP_Error('invalid_from_date', __('Please provide a valid start date (yyyy-mm-dd).', 'eurostocks'));
				}

				if (!$to || $to->format('Y-m-d') !== $custom_to) {
					return new WP_Error('invalid_to_date', __('Please provide a valid end date (yyyy-mm-dd).', 'eurostocks'));
				}

				if ($from > $to) {
					return new WP_Error('invalid_range', __('The start date must be before or the same as the end date.', 'eurostocks'));
				}
				break;
			default:
				return new WP_Error('invalid_period', __('Please select a valid period.', 'eurostocks'));
		}

		return array(
			'from' => $from->format('Y-m-d'),
			'to'   => $to->format('Y-m-d'),
		);
	}

	public function fetch_api_statistics() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('You are not allowed to view these statistics.', 'eurostocks')));
		}

		if (! check_ajax_referer('eurostocks_nonce', 'security', false)) {
			wp_send_json_error(array('message' => __('Security check failed.', 'eurostocks')));
		}

		$period = isset($_POST['period']) ? sanitize_key(wp_unslash($_POST['period'])) : 'current_month';
		$custom_from = isset($_POST['fromDate']) ? sanitize_text_field(wp_unslash($_POST['fromDate'])) : '';
		$custom_to = isset($_POST['toDate']) ? sanitize_text_field(wp_unslash($_POST['toDate'])) : '';

		$date_range = $this->calculate_api_statistics_range($period, $custom_from, $custom_to);
		if (is_wp_error($date_range)) {
			wp_send_json_error(array('message' => $date_range->get_error_message()));
		}

		$credentials = $this->get_api_credentials();
		if (null === $credentials) {
			wp_send_json_error(array('message' => __('Please configure the Eurostocks API credentials in Settings first.', 'eurostocks')));
		}

		$client = new Eurostocks_Request($credentials['username'], $credentials['password'], $credentials['api_key']);
		$response = $client->get_api_statistics($date_range['from'], $date_range['to']);

		if (is_wp_error($response)) {
			$this->log_api_statistics_error('Eurostocks API statistics request failed', $response->get_error_data());
			$message = $response->get_error_message();
			if ('' === $message) {
				$message = __('Could not fetch statistics.', 'eurostocks');
			}
			wp_send_json_error(array('message' => $message));
		}

		if (!is_array($response)) {
			$this->log_api_statistics_error('Unexpected Eurostocks API statistics response', array('response' => $response));
			wp_send_json_error(array('message' => __('Could not fetch statistics.', 'eurostocks')));
		}

		$result_key = isset($response['Result']) ? 'Result' : (isset($response['result']) ? 'result' : null);
		if (null === $result_key || !isset($response[$result_key]) || !is_array($response[$result_key])) {
			$this->log_api_statistics_error('Eurostocks API statistics response missing result', array('response' => $response));
			wp_send_json_error(array('message' => __('Could not fetch statistics.', 'eurostocks')));
		}

		$totals_raw = $response[$result_key];
		$totals = array(
			'TotalRequests'       => isset($totals_raw['TotalRequests']) ? (int) $totals_raw['TotalRequests'] : 0,
			'TotalListRequests'   => isset($totals_raw['TotalListRequests']) ? (int) $totals_raw['TotalListRequests'] : 0,
			'TotalDetailRequests' => isset($totals_raw['TotalDetailRequests']) ? (int) $totals_raw['TotalDetailRequests'] : 0,
			'TotalSearchRequests' => isset($totals_raw['TotalSearchRequests']) ? (int) $totals_raw['TotalSearchRequests'] : 0,
		);

		wp_send_json_success(array(
			'fromDate' => $date_range['from'],
			'toDate'   => $date_range['to'],
			'totals'   => $totals,
		));
	}

	private function log_api_statistics_error($message, $context = array()) {
		if (!defined('WP_DEBUG') || true !== WP_DEBUG) {
			return;
		}

		$context_string = '';
		if (!empty($context)) {
			$context_string = ' ' . wp_json_encode($context);
		}

		error_log('[Eurostocks API Stats] ' . $message . $context_string); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
	}

	/**
	 * Get IP visit statistics from the database.
	 * 
	 * Queries the database for IP visits in the last 24 hours, groups them by
	 * IP address and page type, and calculates visit ratios and statistics.
	 * 
	 * @return array Processed IP visit statistics sorted by total visits (descending).
	 */
	private function get_ip_visit_statistics() {
		global $wpdb;
		$options = Eurostocks_Anti_Spam_Settings::get_options();
		$ratio_threshold = Eurostocks_Anti_Spam_Settings::get_ratio_min_detail_requests($options);
		$ratio_percent_limit = Eurostocks_Anti_Spam_Settings::get_ratio_percent_limit($options);
		$table_name = $wpdb->prefix . 'eurostocks_ip';
		$raw_results = $wpdb->get_results($wpdb->prepare("SELECT remote_addr, page_type, blocked, COUNT(*) as visits FROM %i WHERE registration_date > (NOW() - INTERVAL 24 HOUR) GROUP BY remote_addr, page_type, blocked ORDER BY remote_addr ASC, visits DESC", $table_name));
		$results = array();
		if ($raw_results) {
			foreach ($raw_results as $row) {
				$ip = $row->remote_addr;
				if (!isset($results[$ip])) {
					$results[$ip] = array(
						'remote_addr' => $ip,
						'total'         => 0,
						'allowed_total' => 0,
						'blocked_total' => 0,
						'page_types'    => array(),
					);
				}
				$page_type = $row->page_type !== '' ? $row->page_type : __('unknown', 'eurostocks');
				$status_key = (int) $row->blocked === 1 ? 'blocked' : 'allowed';

				if (!isset($results[$ip]['page_types'][$page_type])) {
					$results[$ip]['page_types'][$page_type] = array(
						'allowed' => 0,
						'blocked' => 0,
						'total'   => 0,
					);
				}

				$results[$ip]['page_types'][$page_type][$status_key] = (int) $row->visits;
				$results[$ip]['page_types'][$page_type]['total'] = (int) $results[$ip]['page_types'][$page_type]['allowed'] + (int) $results[$ip]['page_types'][$page_type]['blocked'];

				$results[$ip]['total'] += (int) $row->visits;
				if ('blocked' === $status_key) {
					$results[$ip]['blocked_total'] += (int) $row->visits;
				} else {
					$results[$ip]['allowed_total'] += (int) $row->visits;
				}
			}
			foreach ($results as $ip => $row) {
				$detail_requests = isset($row['page_types']['vehicle_detail']['total']) ? (int) $row['page_types']['vehicle_detail']['total'] : 0;
				$search_requests = isset($row['page_types']['vehicle_list']['total']) ? (int) $row['page_types']['vehicle_list']['total'] : 0;
				$results[$ip]['detail_requests'] = $detail_requests;
				$results[$ip]['search_requests'] = $search_requests;
				$results[$ip]['ratio'] = Eurostocks_Anti_Spam_Settings::calculate_detail_to_search_ratio($detail_requests, $search_requests);
				$results[$ip]['ratio_threshold'] = $ratio_threshold;
				$results[$ip]['ratio_percent_limit'] = $ratio_percent_limit;
			}
			usort($results, function ($a, $b) {
				return $b['total'] <=> $a['total'];
			});
		}
		return $results;
	}

	private function extract_mobile_de_id($input) {
		if ('' === $input) {
			return '';
		}

		if (preg_match('/(\\d{6,})/', $input, $matches)) {
			return $matches[1];
		}

		return '';
	}

	private function resolve_vehicle_co2_value($vehicle) {
		$attributes = isset($vehicle['attributes']) && is_array($vehicle['attributes']) ? $vehicle['attributes'] : array();
		$co2_keys = array('co2EmissionWltpWeighted', 'co2EmissionWltp', 'co2Emission');

		foreach ($co2_keys as $co2_key) {
			if (isset($attributes[$co2_key]) && '' !== $attributes[$co2_key] && null !== $attributes[$co2_key]) {
				return $attributes[$co2_key];
			}
		}

		return '';
	}

	private function build_price_structure_fields($vehicle, $co2_value) {
		$price_info = isset($vehicle['priceInfo']) && is_array($vehicle['priceInfo']) ? $vehicle['priceInfo'] : array();

		$fields = array(
			array(
				'key'         => 'PriceMobiledeBruto',
				'label'       => __('German price (gross)', 'eurostocks'),
				'description' => __('Gross listing price on mobile.de, including German VAT when applicable.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'IsVatable',
				'label'       => __('VAT / Margin', 'eurostocks'),
				'description' => __('Indicates whether the vehicle is VAT-deductible or margin. VAT is reclaimable for VAT vehicles.', 'eurostocks'),
				'type'        => 'text',
			),
			array(
				'key'         => 'PriceMobiledeNetto',
				'label'       => __('German price (net)', 'eurostocks'),
				'description' => __('Net price in Germany. Only applicable when VAT is reclaimable.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'VatRateMobilede',
				'label'       => __('VAT rate Germany', 'eurostocks'),
				'description' => __('The applicable VAT percentage in Germany.', 'eurostocks'),
				'type'        => 'percent',
			),
			array(
				'key'         => 'VatMobilede',
				'label'       => __('VAT Germany', 'eurostocks'),
				'description' => __('The German VAT amount. Only applicable for VAT vehicles.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'VatRateNl',
				'label'       => __('VAT rate Netherlands', 'eurostocks'),
				'description' => __('The current VAT percentage in the Netherlands.', 'eurostocks'),
				'type'        => 'percent',
			),
			array(
				'key'         => 'VatNl',
				'label'       => __('VAT Netherlands', 'eurostocks'),
				'description' => __('Dutch VAT amount, calculated on the German net price.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'PriceMobiledeBrutoNlVat',
				'label'       => __('German price with NL VAT', 'eurostocks'),
				'description' => __('German price recalculated with the Dutch VAT rate.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'ImportCosts',
				'label'       => __('Fixed import costs', 'eurostocks'),
				'description' => __('Fixed import costs that apply to all vehicles. Configurable by Eurostocks.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'TransportCosts',
				'label'       => __('Transport costs', 'eurostocks'),
				'description' => __('Transport costs to the Netherlands based on the German postal area. Configurable by Eurostocks.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'ImportMargin',
				'label'       => __('Sales margin', 'eurostocks'),
				'description' => __('Margin applied to the total price, fixed or variable based on the German gross price.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'ImportMarginPercentage',
				'label'       => __('Sales margin percentage', 'eurostocks'),
				'description' => __('Percentage used for a variable sales margin. Tiers are configurable by Eurostocks.', 'eurostocks'),
				'type'        => 'percent',
			),
			array(
				'key'         => 'ImportMarginFixed',
				'label'       => __('Import margin fixed/variable', 'eurostocks'),
				'description' => __('Indicates whether a fixed or variable sales margin is used.', 'eurostocks'),
				'type'        => 'text',
			),
			array(
				'key'         => 'ImportMarginNlVat',
				'label'       => __('Import margin incl. NL VAT', 'eurostocks'),
				'description' => __('Sales margin including 21% Dutch VAT.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'co2_user_input',
				'label'       => __('Provided CO2 emissions', 'eurostocks'),
				'description' => __('CO2 emissions provided by the advertiser in grams per kilometer. Always verify the correct value.', 'eurostocks'),
				'type'        => 'co2',
			),
			array(
				'key'         => 'RestBpmCo2',
				'label'       => __('Residual BPM', 'eurostocks'),
				'description' => __('Indicative residual BPM based on the provided CO2 emissions. Verify before quoting.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'PriceNlWithVatNl',
				'label'       => __('Consumer price incl. NL VAT', 'eurostocks'),
				'description' => __('Total consumer price in the Netherlands including all costs and margins, calculated with NL VAT.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'PriceNlWithVatMobilede',
				'label'       => __('Consumer price incl. DE VAT', 'eurostocks'),
				'description' => __('Total consumer price in the Netherlands including all costs and margins, calculated with DE VAT.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'FallbackCO2emission',
				'label'       => __('Fallback CO2 emissions', 'eurostocks'),
				'description' => __('Estimated CO2 emissions when no CO2 value is provided. Indicative.', 'eurostocks'),
				'type'        => 'co2',
			),
			array(
				'key'         => 'FallBackRestBPM',
				'label'       => __('Fallback residual BPM', 'eurostocks'),
				'description' => __('Indicative residual BPM calculated using the estimated CO2 emissions.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'FallbackPriceNlWithVatNl',
				'label'       => __('Fallback consumer price incl. NL VAT', 'eurostocks'),
				'description' => __('Total consumer price incl. NL VAT, calculated with estimated CO2 emissions.', 'eurostocks'),
				'type'        => 'currency',
			),
			array(
				'key'         => 'FallbackPriceNlWithVatMobilede',
				'label'       => __('Fallback consumer price incl. DE VAT', 'eurostocks'),
				'description' => __('Total consumer price incl. DE VAT, calculated with estimated CO2 emissions.', 'eurostocks'),
				'type'        => 'currency',
			),
		);

		$structured_fields = array();
		foreach ($fields as $field) {
			$key = isset($field['key']) ? $field['key'] : '';
			$value = '';

			if ('co2_user_input' === $key) {
				$value = $co2_value;
			} elseif (isset($price_info[$key])) {
				$value = $price_info[$key];
			}
			$value = $this->normalize_price_structure_value($key, $value);

			$structured_fields[] = array(
				'label'       => isset($field['label']) ? $field['label'] : '',
				'description' => isset($field['description']) ? $field['description'] : '',
				'value'       => $this->format_price_structure_value($value, isset($field['type']) ? $field['type'] : 'text'),
			);
		}

		return $structured_fields;
	}

	private function normalize_price_structure_value($key, $value) {
		if ('IsVatable' === $key) {
			$flag = $this->normalize_yes_no_value($value);
			if (true === $flag) {
				return __('VAT', 'eurostocks');
			}
			if (false === $flag) {
				return __('Margin', 'eurostocks');
			}
		}

		if ('ImportMarginFixed' === $key) {
			$flag = $this->normalize_yes_no_value($value);
			if (true === $flag) {
				return __('Fixed', 'eurostocks');
			}
			if (false === $flag) {
				return __('Variable', 'eurostocks');
			}
		}

		return $value;
	}

	private function normalize_yes_no_value($value) {
		if (is_bool($value)) {
			return $value;
		}

		if (is_numeric($value)) {
			return 1 === (int) $value;
		}

		$normalized = strtolower(trim((string) $value));
		if ('' === $normalized) {
			return null;
		}

		$yes_values = array('1', 'true', 'ja', 'yes', 'y');
		if (in_array($normalized, $yes_values, true)) {
			return true;
		}

		$no_values = array('0', 'false', 'nee', 'no', 'n');
		if (in_array($normalized, $no_values, true)) {
			return false;
		}

		return null;
	}

	private function format_price_structure_value($value, $type = 'text') {
		if ('' === $value || null === $value) {
			return '-';
		}

		if ('currency' === $type) {
			if (is_numeric($value)) {
				return '€ ' . number_format((float) $value, 0, ',', '.');
			}
			return (string) $value;
		}

		if ('percent' === $type) {
			if (is_numeric($value)) {
				$number = (float) $value;
				$number = round($number, 2);
				$formatted = number_format($number, 2, ',', '.');
				$formatted = rtrim(rtrim($formatted, '0'), ',');
				return $formatted . '%';
			}
			return (string) $value;
		}

		if ('co2' === $type) {
			if (is_numeric($value)) {
				return number_format((float) $value, 0, ',', '.') . ' g/km';
			}
			$raw = trim((string) $value);
			$normalized = str_replace(',', '.', $raw);
			if (preg_match('/-?\\d+(\\.\\d+)?/', $normalized, $matches)) {
				return number_format((float) $matches[0], 0, ',', '.') . ' g/km';
			}
			return $raw;
		}

		return (string) $value;
	}

	private function resolve_plugin_hybrid_value($vehicle) {
		$fuel_type = isset($vehicle['fuelType']) ? strtolower($vehicle['fuelType']) : '';
		$is_hybrid = (false !== strpos($fuel_type, 'hybrid')) || (false !== strpos($fuel_type, 'hybride'));
		$is_hybrid_petrol = (false !== strpos($fuel_type, 'benzine')) || (false !== strpos($fuel_type, 'petrol'));
		$is_hybrid_diesel = (false !== strpos($fuel_type, 'diesel'));

		if (!$is_hybrid || (!$is_hybrid_petrol && !$is_hybrid_diesel)) {
			return __('N/A', 'eurostocks');
		}

		$hybrid_plugin = '';
		if (isset($vehicle['attributes']['hybridPlugin'])) {
			$hybrid_plugin = $vehicle['attributes']['hybridPlugin'];
		}

		if ('' === $hybrid_plugin) {
			return __('No', 'eurostocks');
		}

		$normalized = strtolower((string) $hybrid_plugin);
		$truthy_values = array('1', 'true', 'ja', 'yes', 'y');

		return in_array($normalized, $truthy_values, true) ? __('Yes', 'eurostocks') : __('No', 'eurostocks');
	}

	private function get_vehicle_first_image($vehicle) {
		if (!isset($vehicle['images']) || !is_array($vehicle['images']) || empty($vehicle['images'])) {
			return '';
		}

		foreach ($vehicle['images'] as $image) {
			if (!isset($image['images']) || !is_array($image['images'])) {
				continue;
			}

			$key_xl = array_search('XL', array_column($image['images'], 'size'));
			if (false !== $key_xl && isset($image['images'][$key_xl]['url']) && '' !== $image['images'][$key_xl]['url']) {
				return $image['images'][$key_xl]['url'];
			}

			foreach ($image['images'] as $variant) {
				if (isset($variant['url']) && '' !== $variant['url']) {
					return $variant['url'];
				}
			}
		}

		return '';
	}

	private function log_price_structure_request($vehicle, $vehicle_id) {
		if (!class_exists('Eurostocks_Analytics')) {
			return;
		}

		$make = isset($vehicle['make']) ? sanitize_text_field($vehicle['make']) : '';
		$model = '';
		if (isset($vehicle['model'])) {
			$model = sanitize_text_field($vehicle['model']);
		} elseif (isset($vehicle['modelDescription'])) {
			$model = sanitize_text_field($vehicle['modelDescription']);
		}

		$analytics = new Eurostocks_Analytics('price_structure', 'price_structure', $make, $model, $vehicle_id);
		$analytics->register_visit();
	}

	public function display_analytics_callback()
	{

		$acceptable_periods = array('today', 'yesterday', 'week', 'month', 'year', 'all');

		if (isset($_GET['analytics_period']) && !empty($_GET['analytics_period'])) {
			$analytics_period = sanitize_text_field($_GET['analytics_period']);
			if (!in_array($analytics_period, $acceptable_periods)) {
				$analytics_period = 'week';
			}
		} else {
			$analytics_period = 'week';
		}

		$special = false;
		$analytics_period_i = 'WEEK';
		switch ($analytics_period) {
			case 'today':
				$analytics_period_i = 'DAY';
				break;
			case 'yesterday':
				$analytics_period_i = 'DAY';
				$special = true;
				break;
			case 'week':
				$analytics_period_i = 'WEEK';
				break;
			case 'month':
				$analytics_period_i = 'MONTH';
				break;
			case 'year':
				$analytics_period_i = 'YEAR';
				break;
			case 'all':
				$analytics_period_i = 'YEAR';
				$special = true;
				break;
		}

		global $wpdb;

		$table_name = $wpdb->prefix . 'eurostocks_requests';
		if (!$special) {
			if ('today' === $analytics_period) {
				$query = $wpdb->prepare("SELECT page_action, user_action, blocked, COUNT(*) as visits FROM %1\$s WHERE page_action = 'pageview' AND DATE(registration_date) = CURDATE() GROUP BY user_action, blocked ORDER BY 2 DESC", $table_name);
				$query_contactform = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'contactform' AND DATE(registration_date) = CURDATE() ORDER BY 2 DESC", $table_name);
				$query_price_structure = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'price_structure' AND DATE(registration_date) = CURDATE() ORDER BY 2 DESC", $table_name);
			} else {
				$query = $wpdb->prepare("SELECT page_action, user_action, blocked, COUNT(*) as visits FROM %1\$s WHERE page_action = 'pageview' AND DATE(registration_date) >= DATE_SUB(CURDATE(), INTERVAL 1 {$analytics_period_i}) GROUP BY user_action, blocked ORDER BY 2 DESC", $table_name);
				$query_contactform = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'contactform' AND DATE(registration_date) >= DATE_SUB(CURDATE(), INTERVAL 1 {$analytics_period_i}) ORDER BY 2 DESC", $table_name);
				$query_price_structure = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'price_structure' AND DATE(registration_date) >= DATE_SUB(CURDATE(), INTERVAL 1 {$analytics_period_i}) ORDER BY 2 DESC", $table_name);
			}
		} else {
			if ($analytics_period_i == 'YEAR') {
				// all
				$query = $wpdb->prepare("SELECT page_action, user_action, blocked, COUNT(*) as visits FROM %1\$s WHERE page_action = 'pageview' GROUP BY user_action, blocked", $table_name);
				$query_contactform = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'contactform'", $table_name);
				$query_price_structure = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'price_structure'", $table_name);
			} else {
				// yesterday
				$query = $wpdb->prepare("SELECT page_action, user_action, blocked, COUNT(*) as visits FROM %1\$s WHERE page_action = 'pageview' AND DATE(registration_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY) GROUP BY user_action, blocked ORDER BY 2 DESC", $table_name);
				$query_contactform = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'contactform' AND DATE(registration_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)  ORDER BY 2 DESC", $table_name);
				$query_price_structure = $wpdb->prepare("SELECT page_action, COUNT(*) as visits FROM %1\$s WHERE page_action = 'price_structure' AND DATE(registration_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY) ORDER BY 2 DESC", $table_name);
			}
		}
		$pageviews = $wpdb->get_results($query);
		$contact_submissions = $wpdb->get_results($query_contactform);
		$price_structure_requests = $wpdb->get_results($query_price_structure);

		include_once('partials/eurostocks-admin-analytics-display.php');
	}

	public function display_settings_callback()
	{
		$makes = get_option('eurostocks_makes');
		include_once('partials/eurostocks-admin-display.php');
	}
	public function display_makes_callback()
	{
		$makes = get_option('eurostocks_makes');
		include_once('partials/eurostocks-admin-cars.php');
	}

	// MAKES
	public function eurostocks_request_makes($username, $password, $api_key)
	{

		$client = new Eurostocks_Request($username, $password, $api_key);
		$makes = eurostocks_normalize_makes_list($client->getVehicleMakes());

		$accepted_languages = array('nl', 'de', 'en', 'fr', 'es');

		$lang_data      = eurostocks_get_language_details();
		$language_codes = $lang_data['language_codes'];
		$default_lang   = $lang_data['default_lang'];
		$accepted_langs = array();

		// check if languages are all accepted
		if ($language_codes && count($language_codes) > 0) {
			$all_accepted_langs = true;
			foreach ($language_codes as $lang) {
				if (!in_array($lang, $accepted_languages)) {
					$all_accepted_langs = false;
				} else {
					// create accepted array
					$accepted_langs[] = $lang;
				}
			}
		} else {
			$all_accepted_langs = false;
		}

		if (count($accepted_langs) > 0) {

			foreach ($accepted_langs as $language_iso_code) {
				$transmissions = $client->getTransmissions($language_iso_code);
				if ($transmissions) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_transmissions', $transmissions);
					} else {
						update_option('eurostocks_transmissions_' . esc_html($language_iso_code), $transmissions);
					}
				} else {
					// return an error
					wp_send_json_error();
					wp_die();
				}

				$categories = $client->getCategories($language_iso_code);
				if ($categories) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_categories', $categories);
					} else {
						update_option('eurostocks_categories_' . esc_html($language_iso_code), $categories);
					}
				}

				$headlighttypes = $client->getHeadlightTypes($language_iso_code);
				if ($headlighttypes) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_headlight_types', $headlighttypes);
					} else {
						update_option('eurostocks_headlight_types_' . esc_html($language_iso_code), $headlighttypes);
					}
				}

				$fueltypes = $client->getFuelTypes($language_iso_code);
				if ($fueltypes) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_fuel_types', $fueltypes);
					} else {
						update_option('eurostocks_fuel_types_' . esc_html($language_iso_code), $fueltypes);
					}
				}

				$doorcounts = $client->getDoorCounts($language_iso_code);
				if ($doorcounts) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_door_counts', $doorcounts);
					} else {
						update_option('eurostocks_door_counts_' . esc_html($language_iso_code), $doorcounts);
					}
				}

				$exteriorcolors = $client->getExteriorColors($language_iso_code);
				if ($exteriorcolors) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_exterior_colors', $exteriorcolors);
					} else {
						update_option('eurostocks_exterior_colors_' . esc_html($language_iso_code), $exteriorcolors);
					}
				}

				$climatisations = $client->getClimatisations($language_iso_code);
				if ($climatisations) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_climatisations', $climatisations);
					} else {
						update_option('eurostocks_climatisations_' . esc_html($language_iso_code), $climatisations);
					}
				}

				$interiortypes = $client->getInteriorTypes($language_iso_code);
				if ($interiortypes) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_interior_types', $interiortypes);
					} else {
						update_option('eurostocks_interior_types_' . esc_html($language_iso_code), $interiortypes);
					}
				}

				$parkingassistant = $client->getParkingAssistant($language_iso_code);
				if ($parkingassistant) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_parking_assistant', $parkingassistant);
					} else {
						update_option('eurostocks_parking_assistant_' . esc_html($language_iso_code), $parkingassistant);
					}
				}

				$speedcontrols = $client->getSpeedControls($language_iso_code);
				if ($speedcontrols) {
					if ($language_iso_code == $default_lang) {
						update_option('eurostocks_speed_controls', $speedcontrols);
					} else {
						update_option('eurostocks_speed_controls_' . esc_html($language_iso_code), $speedcontrols);
					}
				}
			}
		} else {
			$transmissions = $client->getTransmissions($default_lang);
			if ($transmissions) {
				update_option('eurostocks_transmissions', $transmissions);
			} else {
				/** @disregard wp_json_error */
				wp_json_error();
				wp_die();
			}

			$categories = $client->getCategories($default_lang);
			if ($categories) {
				update_option('eurostocks_categories', $categories);
			}

			$headlighttypes = $client->getHeadlightTypes($default_lang);
			if ($headlighttypes) {
				update_option('eurostocks_headlight_types', $headlighttypes);
			}

			$fueltypes = $client->getFuelTypes($default_lang);
			if ($fueltypes) {
				update_option('eurostocks_fuel_types', $fueltypes);
			}

			$doorcounts = $client->getDoorCounts($default_lang);
			if ($doorcounts) {
				update_option('eurostocks_door_counts', $doorcounts);
			}

			$exteriorcolors = $client->getExteriorColors($default_lang);
			if ($exteriorcolors) {
				update_option('eurostocks_exterior_colors', $exteriorcolors);
			}

			$climatisations = $client->getClimatisations($default_lang);
			if ($climatisations) {
				update_option('eurostocks_climatisations', $climatisations);
			}

			$interiortypes = $client->getInteriorTypes($default_lang);
			if ($interiortypes) {
				update_option('eurostocks_interior_types', $interiortypes);
			}

			$parkingassistant = $client->getParkingAssistant($default_lang);
			if ($parkingassistant) {
				update_option('eurostocks_parking_assistant', $parkingassistant);
			}

			$speedcontrols = $client->getSpeedControls($default_lang);
			if ($speedcontrols) {
				update_option('eurostocks_speed_controls', $speedcontrols);
			}
		}




		if (!empty($makes)) {
			// Save makes as option
			update_option('eurostocks_makes', $makes);
			return $makes;
		}

		return new WP_Error(
			'eurostocks_invalid_makes',
			__('Something went wrong, check if the data is correct.', 'eurostocks')
		);
	}

	// MODELS
	public function eurostocks_request_models($make_key)
	{
		$login = get_option($this->plugin_name);

		$client = new Eurostocks_Request($login['username'], $login['password'], $login['api_key']);
		$models = $client->getVehicleModels($make_key);
		return $models;

		wp_die();
	}

	public function validate_eurostocks_key()
	{

		if (! check_ajax_referer('eurostocks_nonce', 'security', false)) {
			wp_send_json_error(array(
				'message' => __('Security check failed.', 'eurostocks'),
			));
		}

		if (! current_user_can('manage_options')) {
			wp_send_json_error(array(
				'message' => __('You are not allowed to perform this action.', 'eurostocks'),
			), 403);
		}
		if (!isset($_POST['eurostocks'])) {
			wp_send_json_error(array(
				'message' => __('Something went wrong, check if the data is correct.', 'eurostocks'),
			));
		}

		if ((isset($_POST['eurostocks']['username']) && (isset($_POST['eurostocks']['password'])) && (isset($_POST['eurostocks']['api_key'])))) {
			$username = sanitize_text_field(wp_unslash($_POST['eurostocks']['username']));
			$password = sanitize_text_field(wp_unslash($_POST['eurostocks']['password']));
			$api_key = sanitize_text_field(wp_unslash($_POST['eurostocks']['api_key']));

			$result = $this->eurostocks_request_makes($username, $password, $api_key);
			if (is_wp_error($result)) {
				wp_send_json_error(array(
					'message' => $result->get_error_message(),
				));
			}

			wp_send_json_success(array(
				'count' => count($result),
			));
		}

		wp_send_json_error(array(
			'message' => __('Something went wrong, check if the data is correct.', 'eurostocks'),
		));
	}


	public function get_models()
	{
		// AJAX request
		if (! check_ajax_referer('eurostocks_nonce', 'security')) {
			wp_send_json_error();
			wp_die();
		}

		if (isset($_POST['eurostocks_cars']['select_make']) && !empty($_POST['eurostocks_cars']['select_make'])) {
			$result = $this->eurostocks_update_model_scheduler_handle();
			wp_send_json($result);
		} else {
			wp_send_json_error();
		}

		wp_die();
	}

	public function get_eurostocks_models_ajax()
	{
		if (! check_ajax_referer('eurostocks_nonce', 'security')) {
			wp_send_json_error();
			wp_die();
		}
		if (!isset($_POST['eurostocks_cars'])) {
			echo "no post data";
			wp_die();
		}

		$action = $this->eurostocks_update_model_scheduler_handle();
		return $action;
	}

	public function remove_ip_block() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('You are not allowed to perform this action.', 'eurostocks')));
		}

		if (! check_ajax_referer('eurostocks_nonce', 'security', false)) {
			wp_send_json_error(array('message' => __('Security check failed.', 'eurostocks')));
		}

		$single_ip = isset($_POST['ip']) ? sanitize_text_field(wp_unslash($_POST['ip'])) : '';
		$ips = array();
		if ('' !== $single_ip) {
			$ips[] = $single_ip;
		}

		if (isset($_POST['ips'])) {
			$raw_ips = wp_unslash($_POST['ips']);
			if (is_array($raw_ips)) {
				foreach ($raw_ips as $raw_ip) {
					$clean_ip = sanitize_text_field($raw_ip);
					if ('' !== $clean_ip) {
						$ips[] = $clean_ip;
					}
				}
			}
		}

		$ips = array_values(array_unique(array_filter($ips, static function ($ip) {
			return '' !== $ip;
		})));

		if (empty($ips)) {
			wp_send_json_error(array('message' => __('No IP address provided.', 'eurostocks')));
		}

		$removed = array();
		foreach ($ips as $ip) {
			if ($this->unblock_ip_address($ip)) {
				$removed[] = $ip;
			}
		}

		if (empty($removed)) {
			wp_send_json_error(array('message' => __('IP address could not be removed or was not blocked.', 'eurostocks')));
		}

		wp_send_json_success(array(
			'removed' => $removed,
			'ip'      => count($removed) === 1 ? $removed[0] : '',
		));
	}

	public function remove_verification_entry() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('You are not allowed to perform this action.', 'eurostocks')));
		}

		if (! check_ajax_referer('eurostocks_nonce', 'security', false)) {
			wp_send_json_error(array('message' => __('Security check failed.', 'eurostocks')));
		}

		$hash = isset($_POST['hash']) ? sanitize_text_field(wp_unslash($_POST['hash'])) : '';
		$ip = isset($_POST['ip']) ? sanitize_text_field(wp_unslash($_POST['ip'])) : '';
		$unblock = isset($_POST['unblock']) ? (int) $_POST['unblock'] : 0;

		$result = $this->process_verification_entry_removal($hash, $ip, $unblock);
		if (is_wp_error($result)) {
			wp_send_json_error(array('message' => $result->get_error_message()));
		}

		wp_send_json_success($result);
	}

	private function unblock_ip_address($ip) {
		$ip = trim($ip);
		if ('' === $ip) {
			return false;
		}

		$options = get_option('eurostocks-anti-spam');
		if (!is_array($options)) {
			$options = array();
		}

		$iplist = isset($options['iplist']) ? $options['iplist'] : '';
		$ips = Eurostocks_Anti_Spam_Settings::get_blocked_ips($options);

		if (empty($ips) || !in_array($ip, $ips, true)) {
			return false;
		}

		$filtered = array_values(array_filter($ips, static function($existing_ip) use ($ip) {
			return $existing_ip !== $ip;
		}));

		$options['iplist'] = implode("\n", $filtered);
		update_option('eurostocks-anti-spam', $options);
		Eurostocks_Anti_Spam_Settings::remove_ip_metadata($ip);

		return true;
	}

	public function block_ip_address_admin() {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('You are not allowed to perform this action.', 'eurostocks')));
		}

		if (! check_ajax_referer('eurostocks_nonce', 'security', false)) {
			wp_send_json_error(array('message' => __('Security check failed.', 'eurostocks')));
		}

		$ip = isset($_POST['ip']) ? sanitize_text_field(wp_unslash($_POST['ip'])) : '';
		if ('' === $ip) {
			wp_send_json_error(array('message' => __('No IP address provided.', 'eurostocks')));
		}

		$options = get_option('eurostocks-anti-spam');
		if (!is_array($options)) {
			$options = array();
		}

		$iplist = isset($options['iplist']) ? $options['iplist'] : '';
		$ips = Eurostocks_Anti_Spam_Settings::get_blocked_ips($options);

		if (!in_array($ip, $ips, true)) {
			$ips[] = $ip;
			$options['iplist'] = implode("\n", $ips);
			update_option('eurostocks-anti-spam', $options);
		}

		Eurostocks_Anti_Spam_Settings::record_ip_event($ip, array(
			'status'     => 'blocked',
			'reason_key' => 'manual',
			'page_type'  => 'manual',
			'details'    => array('source' => 'admin_block_button'),
		));

		wp_send_json_success(array('ip' => $ip));
	}

	private function process_verification_entry_removal($hash, $ip, $unblock = 0) {
		if ('' === $hash) {
			return new WP_Error('missing_hash', __('No verification entry specified.', 'eurostocks'));
		}

		$deleted = Eurostocks_Email_Verification::delete_status_by_hash($hash);
		if (!$deleted) {
			return new WP_Error('delete_failed', __('Verification entry could not be removed or no longer exists.', 'eurostocks'));
		}

		if ('' !== $ip) {
			Eurostocks_Email_Verification::delete_tokens_for_ip($ip);
			Eurostocks_Email_Verification::clear_ip_block_flag($ip);
		}

		$ip_unblocked = false;
		if ($unblock && '' !== $ip) {
			$ip_unblocked = $this->unblock_ip_address($ip);
		}

		return array(
			'hash' => $hash,
			'ip'   => $ip,
			'ip_unblocked' => (bool) $ip_unblocked,
		);
	}

	public function options_update()
	{
		register_setting($this->plugin_name, $this->plugin_name, array($this, 'validate'));
		register_setting($this->plugin_name . '_cars', 'eurostocks_cars', array($this, 'cars_validate'));
		register_setting('eurostocks-anti-spam', 'eurostocks-anti-spam', array($this, 'bl_validate'));
	}

	public function bl_validate($input)
	{
		$valid = array();
		$existing_options = Eurostocks_Anti_Spam_Settings::get_options();
		$existing_ips = Eurostocks_Anti_Spam_Settings::get_blocked_ips($existing_options);
		$current_metadata = Eurostocks_Anti_Spam_Settings::get_ip_metadata($existing_options);
		
		if (!wp_doing_ajax()) {
			if (! isset($_POST['eurostocks-anti-spam_nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['eurostocks-anti-spam_nonce'])), 'eurostocks-anti-spam')) {
				return;
			}
		}
			if (isset($input['iplist'])) {
				$valid['iplist'] = sanitize_textarea_field($input['iplist']);
			} else {
				$valid['iplist'] = '';
			}

			$valid['ip_metadata'] = $current_metadata;
			$new_ips = Eurostocks_Anti_Spam_Settings::get_blocked_ips(array('iplist' => $valid['iplist']));
			$removed_ips = array_diff($existing_ips, $new_ips);
			$added_ips = array_diff($new_ips, $existing_ips);

			if (!empty($removed_ips)) {
				foreach ($removed_ips as $removed_ip) {
					unset($valid['ip_metadata'][$removed_ip]);
				}
			}

			if (!empty($added_ips)) {
				foreach ($added_ips as $added_ip) {
					$valid['ip_metadata'][$added_ip] = Eurostocks_Anti_Spam_Settings::prepare_ip_metadata_entry(array(
						'reason_key' => 'manual',
						'page_type'  => 'manual',
						'status'     => 'blocked',
						'details'    => array('source' => 'manual'),
					));
				}
			}

			if (isset($input['allow_countries'])) {
				$valid['allow_countries'] = array_map('strip_tags', $input['allow_countries']);
			}
			if(isset($input['autoban']) && !empty($input['autoban'])){
				$valid['autoban'] = (int)$input['autoban'];
			}else{
				$valid['autoban'] = 100;
			}

			if (isset($input['request_ratio_min_detail']) && $input['request_ratio_min_detail'] !== '') {
				$valid['request_ratio_min_detail'] = max(0, (int) $input['request_ratio_min_detail']);
			} else {
				$valid['request_ratio_min_detail'] = Eurostocks_Anti_Spam_Settings::DEFAULT_RATIO_MIN_DETAIL_REQUESTS;
			}

			if (isset($input['request_ratio_percent']) && $input['request_ratio_percent'] !== '') {
				$valid['request_ratio_percent'] = max(0, (int) $input['request_ratio_percent']);
			} else {
				$valid['request_ratio_percent'] = Eurostocks_Anti_Spam_Settings::DEFAULT_RATIO_PERCENT_LIMIT;
			}

			$valid['per_page_limits'] = array();
			if (isset($input['per_page_limits']) && is_array($input['per_page_limits'])) {
				foreach ($input['per_page_limits'] as $row_key => $limit_row) {
					if (!is_array($limit_row)) {
						continue;
					}

					$slug = '';
					if (isset($limit_row['page_type'])) {
						$slug = sanitize_key($limit_row['page_type']);
					} elseif (is_string($row_key)) {
						$slug = sanitize_key($row_key);
					}

					if ('' === $slug) {
						continue;
					}

					$autoban_source = isset($limit_row['autoban']) ? $limit_row['autoban'] : (isset($limit_row['autoban_limit']) ? $limit_row['autoban_limit'] : null);
					$autoban_value = ($autoban_source !== null && $autoban_source !== '') ? max(0, (int) $autoban_source) : null;

					if (isset($limit_row['email_limit'])) {
						$email_source = $limit_row['email_limit'];
					} elseif (isset($limit_row['email_verification_limit'])) {
						$email_source = $limit_row['email_verification_limit'];
					} else {
						$email_source = null;
					}
					$email_value = ($email_source !== null && $email_source !== '') ? max(0, (int) $email_source) : null;

					if (null === $autoban_value && null === $email_value) {
						continue;
					}

					$entry = array();
					if (null !== $autoban_value) {
						$entry['autoban'] = $autoban_value;
					}
					if (null !== $email_value) {
						$entry['email_verification_limit'] = $email_value;
					}

					if (!empty($entry)) {
						$valid['per_page_limits'][$slug] = $entry;
					}
				}
			}

			$valid['texts'] = array();
			if (isset($input['texts']) && is_array($input['texts'])) {
				$default_texts = Eurostocks_Anti_Spam_Settings::get_default_texts();
				foreach ($input['texts'] as $text_key => $text_value) {
					if (!array_key_exists($text_key, $default_texts)) {
						continue;
					}

					$clean_value = sanitize_textarea_field($text_value);
					if ('' === $clean_value) {
						continue;
					}

					$valid['texts'][$text_key] = $clean_value;
				}
			}

		$valid['disable_ipfilter'] = (isset($input['disable_ipfilter']) && !empty($input['disable_ipfilter'])) ? 1 : 0;
		$valid['block_unknown'] = (isset($input['block_unknown']) && !empty($input['block_unknown'])) ? 1 : 0;
		$valid['use_cloudflare_ip'] = (isset($input['use_cloudflare_ip']) && !empty($input['use_cloudflare_ip'])) ? 1 : 0;
		
		return $valid;
	}
	public function cars_validate($input)
	{
		$valid = array();
		if (!wp_doing_ajax()) {
			if (! isset($_POST['eurostocks_cars_nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['eurostocks_cars_nonce'])), 'eurostocks_cars')) {
				return;
			}
		}
			if (isset($input['select_available_make'])) {
				$valid['select_available_make'] = array_map('strip_tags', $input['select_available_make']);
			}

			if (isset($input['select_makes'])) {
				$valid['select_makes'] = $this->eurostocks_sanitize_text_field_array($input['select_makes']);
			}

			if (isset($input['excluded_models'])) {
				$valid['excluded_models'] = sanitize_text_field($input['excluded_models']);
			}

			$valid['live_models'] = (isset($input['live_models']) && !empty($input['live_models'])) ? 1 : 0;
			$valid['make_only'] = (isset($input['make_only']) && in_array((int)$input['make_only'], [0, 1, 2])) ? (int)$input['make_only'] : 0;

			if (! wp_next_scheduled('eurostocks_update_model_scheduler', [])) {
				wp_schedule_event(time(), 'monthly', 'eurostocks_update_model_scheduler', []);
			}

			return $valid;
		
	}

	public function validate($input)
	{

		$valid = array();
		
			if (! isset($_POST['eurostocks_nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['eurostocks_nonce'])), 'eurostocks')) {
				// Nonce is not valid; do not save
				error_log('Nonce is not valid');
				return;
			}
			if (isset($input['username'])) {
				$valid['username'] = sanitize_text_field($input['username']);
			}
			if (isset($input['password'])) {
				$valid['password'] = sanitize_text_field($input['password']);
			}
			if (isset($input['api_key'])) {
				$valid['api_key'] = sanitize_text_field($input['api_key']);
			}
			$valid['hide_price'] = (isset($input['hide_price']) && !empty($input['hide_price'])) ? 1 : 0;
			$valid['hide_power'] = (isset($input['hide_power']) && !empty($input['hide_power'])) ? 1 : 0;
			$valid['hide_filter_parking'] = (isset($input['hide_filter_parking']) && !empty($input['hide_filter_parking'])) ? 1 : 0;
			$valid['hide_mileage'] = (isset($input['hide_mileage']) && !empty($input['hide_mileage'])) ? 1 : 0;
			$valid['hide_year'] = (isset($input['hide_year']) && !empty($input['hide_year'])) ? 1 : 0;
			$valid['hide_drive_type'] = (isset($input['hide_drive_type']) && !empty($input['hide_drive_type'])) ? 1 : 0;
			$valid['hide_seats'] = (isset($input['hide_seats']) && !empty($input['hide_seats'])) ? 1 : 0;
			$valid['hide_fuel_type'] = (isset($input['hide_fuel_type']) && !empty($input['hide_fuel_type'])) ? 1 : 0;
			$valid['hide_filter_options'] = (isset($input['hide_filter_options']) && !empty($input['hide_filter_options'])) ? 1 : 0;
			$valid['hide_transmission'] = (isset($input['hide_transmission']) && !empty($input['hide_transmission'])) ? 1 : 0;
			$valid['hide_speed_control'] = (isset($input['hide_speed_control']) && !empty($input['hide_speed_control'])) ? 1 : 0;
			$valid['hide_interior_type'] = (isset($input['hide_interior_type']) && !empty($input['hide_interior_type'])) ? 1 : 0;
			$valid['hide_climatisation'] = (isset($input['hide_climatisation']) && !empty($input['hide_climatisation'])) ? 1 : 0;
			$valid['hide_exterior_color'] = (isset($input['hide_exterior_color']) && !empty($input['hide_exterior_color'])) ? 1 : 0;
			$valid['hide_headlight_type'] = (isset($input['hide_headlight_type']) && !empty($input['hide_headlight_type'])) ? 1 : 0;
			$valid['hide_door_count'] = (isset($input['hide_door_count']) && !empty($input['hide_door_count'])) ? 1 : 0;
			$valid['hide_vat'] = (isset($input['hide_vat']) && !empty($input['hide_vat'])) ? 1 : 0;
			$valid['hide_category'] = (isset($input['hide_category']) && !empty($input['hide_category'])) ? 1 : 0;
			$valid['expand_filters'] = (isset($input['expand_filters']) && !empty($input['expand_filters'])) ? 1 : 0;
			$valid['use_as_iframe'] = (isset($input['use_as_iframe']) && !empty($input['use_as_iframe'])) ? 1 : 0;
			$valid['feature_warranty'] = (isset($input['feature_warranty']) && !empty($input['feature_warranty'])) ? 1 : 0;
			$valid['no_damage_history'] = (isset($input['no_damage_history']) && !empty($input['no_damage_history'])) ? 1 : 0;
			$valid['max_prev_owners'] = (isset($input['max_prev_owners']) && !empty($input['max_prev_owners'])) ? 1 : 0;
			$valid['maintenance_history'] = (isset($input['maintenance_history']) && !empty($input['maintenance_history'])) ? 1 : 0;
			$valid['hide_reviews'] = (isset($input['hide_reviews']) && !empty($input['hide_reviews'])) ? 1 : 0;
			$valid['hide_experts'] = (isset($input['hide_experts']) && !empty($input['hide_experts'])) ? 1 : 0;
			$valid['hide_kosten_left'] = (isset($input['hide_kosten_left']) && !empty($input['hide_kosten_left'])) ? 1 : 0;
			$valid['hide_kosten_right'] = (isset($input['hide_kosten_right']) && !empty($input['hide_kosten_right'])) ? 1 : 0;
			$valid['show_nav'] = (isset($input['show_nav']) && !empty($input['show_nav'])) ? 1 : 0;
			$valid['show_options_sep'] = (isset($input['show_options_sep']) && !empty($input['show_options_sep'])) ? 1 : 0;
			$valid['griddisplay'] = (isset($input['griddisplay']) && !empty($input['griddisplay'])) ? 1 : 0;
			$valid['txt_search_help_show'] = (isset($input['txt_search_help_show']) && !empty($input['txt_search_help_show'])) ? 1 : 0;
			$valid['co2_disclaimer_display'] = (isset($input['co2_disclaimer_display']) && !empty($input['co2_disclaimer_display'])) ? 1 : 0;
			$valid['co2_fallback_display'] = (isset($input['co2_fallback_display']) && !empty($input['co2_fallback_display'])) ? 1 : 0;

			$valid['hide_carlease'] = (isset($input['hide_carlease']) && !empty($input['hide_carlease'])) ? 1 : 0;

			$valid['hide_cartrade'] = (isset($input['hide_cartrade']) && !empty($input['hide_cartrade'])) ? 1 : 0;

			$valid['show_cta_cf'] = (isset($input['show_cta_cf']) && !empty($input['show_cta_cf'])) ? 1 : 0;
			$valid['show_cta_app'] = (isset($input['show_cta_app']) && !empty($input['show_cta_app'])) ? 1 : 0;
			$valid['show_cta_tel'] = (isset($input['show_cta_tel']) && !empty($input['show_cta_tel'])) ? 1 : 0;
			$valid['show_cta_fav'] = (isset($input['show_cta_fav']) && !empty($input['show_cta_fav'])) ? 1 : 0;



			$ctas = array_keys($this->eurostocks_get_available_ctas());
			// Accept string or array, handle missing key safely
			$raw_cta_order = isset($input['cta_order']) ? $input['cta_order'] : '';
			if (is_array($raw_cta_order)) {
				$input_cta_array = array_map('trim', $raw_cta_order);
			} else {
				$raw_cta_order = sanitize_text_field($raw_cta_order);
				$input_cta_array = array_filter(array_map('trim', explode(',', $raw_cta_order)));
			}
			// Only allow valid keys and preserve order; store as comma-separated string
			$filtered_cta = array_values(array_filter($input_cta_array, fn($k) => in_array($k, $ctas, true)));
			$valid['cta_order'] = implode(',', $filtered_cta);

			$valid['hide_sort'] = (isset($input['hide_sort']) && !empty($input['hide_sort'])) ? 1 : 0;
			$valid['hide_sort_price'] = (isset($input['hide_sort_price']) && !empty($input['hide_sort_price'])) ? 1 : 0;
			$valid['hide_sort_mileage'] = (isset($input['hide_sort_mileage']) && !empty($input['hide_sort_mileage'])) ? 1 : 0;
			$valid['hide_sort_registration'] = (isset($input['hide_sort_registration']) && !empty($input['hide_sort_registration'])) ? 1 : 0;
			$valid['hide_sort_creation'] = (isset($input['hide_sort_creation']) && !empty($input['hide_sort_creation'])) ? 1 : 0;
			if (isset($input['cta_url'])) {
				$valid['cta_url'] = sanitize_text_field($input['cta_url']);
			}

			if (isset($input['replacement_img'])) {
				$valid['replacement_img'] = sanitize_text_field($input['replacement_img']);
			}

			if (isset($input['show_powered_by']) && !empty($input['show_powered_by'])) {
				$valid['show_powered_by'] = sanitize_text_field($input['show_powered_by']);
			};

			if (isset($input['min_bouwjaar'])) {
				$valid['min_bouwjaar'] = sanitize_text_field($input['min_bouwjaar']);
			}

			if (isset($input['max_kmstand'])) {
				$valid['max_kmstand'] = sanitize_text_field($input['max_kmstand']);
			}

			if (isset($input['dealers'])) {
				$valid['dealers'] = sanitize_text_field($input['dealers']);
			}
			if (isset($input['country'])) {
				$valid['country'] = sanitize_text_field($input['country']);
			}

			if (isset($input['email'])) {
				$valid['email'] = sanitize_text_field($input['email']);
			}
			if (isset($input['reviews_url'])) {
				$valid['reviews_url'] = sanitize_text_field($input['reviews_url']);
			}
			if (isset($input['review_img'])) {
				$valid['review_img'] = sanitize_text_field($input['review_img']);
			}
			if (isset($input['logo'])) {
				$valid['logo'] = sanitize_text_field($input['logo']);
			}
			$accepted_languages = array('nl', 'de', 'en', 'fr', 'es');
			$lang_data      = eurostocks_get_language_details();
			$language_codes = $lang_data['language_codes'];
			$accepted_langs = array();

			// check if languages are all accepted
			if ($language_codes && count($language_codes) > 0) {
				$all_accepted_langs = true;
				foreach ($language_codes as $lang) {
					if (!in_array($lang, $accepted_languages)) {
						$all_accepted_langs = false;
					} else {
						$accepted_langs[] = $lang;
					}
				}
			} else {
				$all_accepted_langs = false;
			}


			foreach ($accepted_langs as $lang) {
				if (isset($input[esc_html($lang)])) {
					$lang_input = $input[esc_html($lang)];
					if (isset($lang_input['cta_url'])) {
						$valid[esc_html($lang)]['cta_url'] = sanitize_text_field($lang_input['cta_url']);
					}
					if (isset($lang_input['reviews_url'])) {
						$valid[esc_html($lang)]['reviews_url'] = sanitize_text_field($lang_input['reviews_url']);
					}

					if (isset($lang_input['reviews_one_name'])) {
						$valid[esc_html($lang)]['reviews_one_name'] = sanitize_text_field($lang_input['reviews_one_name']);
					}
					if (isset($lang_input['reviews_two_name'])) {
						$valid[esc_html($lang)]['reviews_two_name'] = sanitize_text_field($lang_input['reviews_two_name']);
					}
					if (isset($lang_input['reviews_one_place'])) {
						$valid[esc_html($lang)]['reviews_one_place'] = sanitize_text_field($lang_input['reviews_one_place']);
					}
					if (isset($lang_input['reviews_two_place'])) {
						$valid[esc_html($lang)]['reviews_two_place'] = sanitize_text_field($lang_input['reviews_two_place']);
					}
					if (isset($lang_input['reviews_one_stars'])) {
						$valid[esc_html($lang)]['reviews_one_stars'] = sanitize_text_field($lang_input['reviews_one_stars']);
					}
					if (isset($lang_input['reviews_two_stars'])) {
						$valid[esc_html($lang)]['reviews_two_stars'] = sanitize_text_field($lang_input['reviews_two_stars']);
					}
					if (isset($lang_input['reviews_one_title'])) {
						$valid[esc_html($lang)]['reviews_one_title'] = sanitize_text_field($lang_input['reviews_one_title']);
					}
					if (isset($lang_input['reviews_two_title'])) {
						$valid[esc_html($lang)]['reviews_two_title'] = sanitize_text_field($lang_input['reviews_two_title']);
					}
					if (isset($lang_input['reviews_one_text'])) {
						$valid[esc_html($lang)]['reviews_one_text'] = sanitize_textarea_field($lang_input['reviews_one_text']);
					}
					if (isset($lang_input['reviews_two_text'])) {
						$valid[esc_html($lang)]['reviews_two_text'] = sanitize_textarea_field($lang_input['reviews_two_text']);
					}
					if (isset($lang_input['txt_search_help'])) {
						$valid[esc_html($lang)]['txt_search_help'] = wp_kses_post($lang_input['txt_search_help']);
					}

					if (isset($lang_input['offerte_txt'])) {
						$valid[esc_html($lang)]['offerte_txt'] = wp_kses_post($lang_input['offerte_txt']);
					}

					if (isset($lang_input['txt_voordeel1'])) {
						$valid[esc_html($lang)]['txt_voordeel1'] = sanitize_text_field($lang_input['txt_voordeel1']);
					}
					if (isset($lang_input['txt_voordeel2'])) {
						$valid[esc_html($lang)]['txt_voordeel2'] = sanitize_text_field($lang_input['txt_voordeel2']);
					}
					if (isset($lang_input['txt_voordeel3'])) {
						$valid[esc_html($lang)]['txt_voordeel3'] = sanitize_text_field($lang_input['txt_voordeel3']);
					}
					if (isset($lang_input['txt_voordeel4'])) {
						$valid[esc_html($lang)]['txt_voordeel4'] = sanitize_text_field($lang_input['txt_voordeel4']);
					}

					if (isset($lang_input['offerte_title'])) {
						$valid[esc_html($lang)]['offerte_title'] = sanitize_text_field($lang_input['offerte_title']);
					}

					if (isset($lang_input['kosten_vraagprijs'])) {
						$valid[esc_html($lang)]['kosten_vraagprijs'] = sanitize_text_field($lang_input['kosten_vraagprijs']);
					}
					if (isset($lang_input['kosten_vraagprijs_tax'])) {
						$valid[esc_html($lang)]['kosten_vraagprijs_tax'] = sanitize_text_field($lang_input['kosten_vraagprijs_tax']);
					}
					if (isset($lang_input['kosten_vraagprijs_no_tax'])) {
						$valid[esc_html($lang)]['kosten_vraagprijs_no_tax'] = sanitize_text_field($lang_input['kosten_vraagprijs_no_tax']);
					}
					if (isset($lang_input['kosten_toelating'])) {
						$valid[esc_html($lang)]['kosten_toelating'] = sanitize_text_field($lang_input['kosten_toelating']);
					}
					if (isset($lang_input['kosten_transport'])) {
						$valid[esc_html($lang)]['kosten_transport'] = sanitize_text_field($lang_input['kosten_transport']);
					}
					if (isset($lang_input['kosten_transport2'])) {
						$valid[esc_html($lang)]['kosten_transport2'] = sanitize_text_field($lang_input['kosten_transport2']);
					}
					if (isset($lang_input['kosten_totaal'])) {
						$valid[esc_html($lang)]['kosten_totaal'] = sanitize_text_field($lang_input['kosten_totaal']);
					}
					if (isset($lang_input['details_top_txt'])) {
						$valid[esc_html($lang)]['details_top_txt'] = sanitize_text_field($lang_input['details_top_txt']);
					}
					if (isset($lang_input['txt_search_title'])) {
						$valid[esc_html($lang)]['txt_search_title'] = sanitize_text_field($lang_input['txt_search_title']);
					}
					if (isset($lang_input['txt_search'])) {
						$valid[esc_html($lang)]['txt_search'] = wp_kses_post($lang_input['txt_search']);
					}
					if (isset($lang_input['experts_one_name'])) {
						$valid[esc_html($lang)]['experts_one_name'] = sanitize_text_field($lang_input['experts_one_name']);
					}
					if (isset($lang_input['experts_one_function'])) {
						$valid[esc_html($lang)]['experts_one_function'] = sanitize_text_field($lang_input['experts_one_function']);
					}
					if (isset($lang_input['experts_one_tel'])) {
						$valid[esc_html($lang)]['experts_one_tel'] = sanitize_text_field($lang_input['experts_one_tel']);
					}
					if (isset($lang_input['experts_one_mail'])) {
						$valid[esc_html($lang)]['experts_one_mail'] = sanitize_text_field($lang_input['experts_one_mail']);
					}
					if (isset($lang_input['experts_two_name'])) {
						$valid[esc_html($lang)]['experts_two_name'] = sanitize_text_field($lang_input['experts_two_name']);
					}
					if (isset($lang_input['experts_two_function'])) {
						$valid[esc_html($lang)]['experts_two_function'] = sanitize_text_field($lang_input['experts_two_function']);
					}
					if (isset($lang_input['experts_two_tel'])) {
						$valid[esc_html($lang)]['experts_two_tel'] = sanitize_text_field($lang_input['experts_two_tel']);
					}
					if (isset($lang_input['experts_two_mail'])) {
						$valid[esc_html($lang)]['experts_two_mail'] = sanitize_text_field($lang_input['experts_two_mail']);
					}
					if (isset($lang_input['experts_two_img'])) {
						$valid[esc_html($lang)]['experts_two_img'] = sanitize_text_field($lang_input['experts_two_img']);
					}

					if (isset($lang_input['txt_more_reviews'])) {
						$valid[esc_html($lang)]['txt_more_reviews'] = sanitize_text_field($lang_input['txt_more_reviews']);
					}
					if (isset($lang_input['redirect'])) {
						$valid[esc_html($lang)]['redirect'] = sanitize_text_field($lang_input['redirect']);
					}
					if (isset($lang_input['tel'])) {
						$valid[esc_html($lang)]['tel'] = sanitize_text_field($lang_input['tel']);
					}
					if (isset($lang_input['filters_page'])) {
						$valid[esc_html($lang)]['filters_page'] = sanitize_text_field($lang_input['filters_page']);
					}
					if (isset($lang_input['details_page'])) {
						$valid[esc_html($lang)]['details_page'] = sanitize_text_field($lang_input['details_page']);
					}

					if (isset($lang_input['txt_price_help'])) {
						$valid[esc_html($lang)]['txt_price_help'] = sanitize_text_field($lang_input['txt_price_help']);
					}

					if (isset($lang_input['txt_price_helpp'])) {
						$valid[esc_html($lang)]['txt_price_helpp'] = sanitize_text_field($lang_input['txt_price_helpp']);
					}
					if (isset($lang_input['txt_kosten_diensten'])) {
						$valid[esc_html($lang)]['txt_kosten_diensten'] = sanitize_text_field($lang_input['txt_kosten_diensten']);
					}

					if (isset($lang_input['txt_experts'])) {
						$valid[esc_html($lang)]['txt_experts'] = sanitize_text_field($lang_input['txt_experts']);
					}

					if (isset($lang_input['txt_review'])) {
						$valid[esc_html($lang)]['txt_review'] = sanitize_text_field($lang_input['txt_review']);
					}
					if (isset($lang_input['kosten_one_title'])) {
						$valid[esc_html($lang)]['kosten_one_title'] = sanitize_text_field($lang_input['kosten_one_title']);
					}
					if (isset($lang_input['kosten_title'])) {
						$valid[esc_html($lang)]['kosten_title'] = sanitize_text_field($lang_input['kosten_title']);
					}
					if (isset($lang_input['kosten_restbpm'])) {
						$valid[esc_html($lang)]['kosten_restbpm'] = sanitize_text_field($lang_input['kosten_restbpm']);
					}
					if (isset($lang_input['kosten_one_txt'])) {
						$valid[esc_html($lang)]['kosten_one_txt'] = sanitize_textarea_field($lang_input['kosten_one_txt']);
					}
					if (isset($lang_input['kosten_two_title'])) {
						$valid[esc_html($lang)]['kosten_two_title'] = sanitize_text_field($lang_input['kosten_two_title']);
					}
					if (isset($lang_input['kosten_two_txt'])) {
						$valid[esc_html($lang)]['kosten_two_txt'] = sanitize_textarea_field($lang_input['kosten_two_txt']);
					}
					if (isset($lang_input['txt_disclaimer'])) {
						$valid[esc_html($lang)]['txt_disclaimer'] = sanitize_textarea_field($lang_input['txt_disclaimer']);
					}
					if (isset($lang_input['txt_co2_disclaimer'])) {
						$valid[esc_html($lang)]['txt_co2_disclaimer'] = sanitize_textarea_field($lang_input['txt_co2_disclaimer']);
					}
					if (isset($lang_input['txt_co2_disclaimer_fallback'])) {
						$valid[esc_html($lang)]['txt_co2_disclaimer_fallback'] = sanitize_textarea_field($lang_input['txt_co2_disclaimer_fallback']);
					}
					if (isset($lang_input['txt_btn'])) {
						$valid[esc_html($lang)]['txt_btn'] = wp_kses_post($lang_input['txt_btn']);
					}
					if (isset($lang_input['txt_btn_product'])) {
						$valid[esc_html($lang)]['txt_btn_product'] = wp_kses_post($lang_input['txt_btn_product']);
					}
					if (isset($lang_input['txt_srch_btn'])) {
						$valid[esc_html($lang)]['txt_srch_btn'] = wp_kses_post($lang_input['txt_srch_btn']);
					}
					if (isset($lang_input['txt_srch'])) {
						$valid[esc_html($lang)]['txt_srch'] = wp_kses_post($lang_input['txt_srch']);
					}

					if (isset($lang_input['txt_make'])) {
						$valid[esc_html($lang)]['txt_make'] = wp_kses_post($lang_input['txt_make']);
					}

					if (isset($lang_input['txt_priceonrequest'])) {
						$valid[esc_html($lang)]['txt_priceonrequest'] = wp_kses_post($lang_input['txt_priceonrequest']);
					}

					if (isset($lang_input['txt_model'])) {
						$valid[esc_html($lang)]['txt_model'] = wp_kses_post($lang_input['txt_model']);
					}

					if (isset($lang_input['txt_select_make'])) {
						$valid[esc_html($lang)]['txt_select_make'] = wp_kses_post($lang_input['txt_select_make']);
					}

					if (isset($lang_input['txt_select_model'])) {
						$valid[esc_html($lang)]['txt_select_model'] = wp_kses_post($lang_input['txt_select_model']);
					}

					if (isset($lang_input['contactcar'])) {
						$valid[esc_html($lang)]['contactcar'] = sanitize_textarea_field($lang_input['contactcar']);
					}
					if (isset($lang_input['contactmes'])) {
						$valid[esc_html($lang)]['contactmes'] = sanitize_textarea_field($lang_input['contactmes']);
					}
					if (isset($lang_input['contacttimes'])) {
						$valid[esc_html($lang)]['contacttimes'] = wp_kses_post($lang_input['contacttimes']);
					}
					if (isset($lang_input['contactaddress'])) {
						$valid[esc_html($lang)]['contactaddress'] = wp_kses_post($lang_input['contactaddress']);
					}
					
					if (isset($lang_input['html_experts'])) {
						$valid[esc_html($lang)]['html_experts'] = wp_kses_post($lang_input['html_experts']);
					}

					if (isset($lang_input['nonfav_opt_title'])) {
						$valid[esc_html($lang)]['nonfav_opt_title'] = sanitize_text_field($lang_input['nonfav_opt_title']);
					}

					if (isset($lang_input['fav_opt_title'])) {
						$valid[esc_html($lang)]['fav_opt_title'] = sanitize_text_field($lang_input['fav_opt_title']);
					}

					if (isset($lang_input['cta_app'])) {
						$valid[esc_html($lang)]['cta_app'] = sanitize_text_field($lang_input['cta_app']);
					}
					if (isset($lang_input['cta_app_app'])) {
						$valid[esc_html($lang)]['cta_app_app'] = sanitize_textarea_field($lang_input['cta_app_app']);
					}
					if (isset($lang_input['cta_tel'])) {
						$valid[esc_html($lang)]['cta_tel'] = sanitize_text_field($lang_input['cta_tel']);
					}
					if (isset($lang_input['cta_fav'])) {
						$valid[esc_html($lang)]['cta_fav'] = sanitize_text_field($lang_input['cta_fav']);
					}
					if (isset($lang_input['cta_fav_fav'])) {
						$valid[esc_html($lang)]['cta_fav_fav'] = sanitize_text_field($lang_input['cta_fav_fav']);
					}
					if (isset($lang_input['txt_404_title'])) {
						$valid[esc_html($lang)]['txt_404_title'] = sanitize_text_field($lang_input['txt_404_title']);
					}
					if (isset($lang_input['txt_404_btn'])) {
						$valid[esc_html($lang)]['txt_404_btn'] = sanitize_text_field($lang_input['txt_404_btn']);
					}
					if (isset($lang_input['txt_404_txt'])) {
						$valid[esc_html($lang)]['txt_404_txt'] = sanitize_text_field($lang_input['txt_404_txt']);
					}
				}
			}






			if (isset($input['reviews_one_name'])) {
				$valid['reviews_one_name'] = sanitize_text_field($input['reviews_one_name']);
			}
			if (isset($input['reviews_two_name'])) {
				$valid['reviews_two_name'] = sanitize_text_field($input['reviews_two_name']);
			}
			if (isset($input['reviews_one_place'])) {
				$valid['reviews_one_place'] = sanitize_text_field($input['reviews_one_place']);
			}
			if (isset($input['reviews_two_place'])) {
				$valid['reviews_two_place'] = sanitize_text_field($input['reviews_two_place']);
			}
			if (isset($input['reviews_one_stars'])) {
				$valid['reviews_one_stars'] = sanitize_text_field($input['reviews_one_stars']);
			}
			if (isset($input['reviews_two_stars'])) {
				$valid['reviews_two_stars'] = sanitize_text_field($input['reviews_two_stars']);
			}
			if (isset($input['reviews_one_title'])) {
				$valid['reviews_one_title'] = sanitize_text_field($input['reviews_one_title']);
			}
			if (isset($input['reviews_two_title'])) {
				$valid['reviews_two_title'] = sanitize_text_field($input['reviews_two_title']);
			}
			if (isset($input['reviews_one_text'])) {
				$valid['reviews_one_text'] = sanitize_textarea_field($input['reviews_one_text']);
			}
			if (isset($input['reviews_two_text'])) {
				$valid['reviews_two_text'] = sanitize_textarea_field($input['reviews_two_text']);
			}
			if (isset($input['txt_search_help'])) {
				$valid['txt_search_help'] = wp_kses_post($input['txt_search_help']);
			}


			if (isset($input['offerte_txt'])) {
				$valid['offerte_txt'] = wp_kses_post($input['offerte_txt']);
			}

			if (isset($input['txt_voordeel1'])) {
				$valid['txt_voordeel1'] = sanitize_text_field($input['txt_voordeel1']);
			}
			if (isset($input['txt_voordeel2'])) {
				$valid['txt_voordeel2'] = sanitize_text_field($input['txt_voordeel2']);
			}
			if (isset($input['txt_voordeel3'])) {
				$valid['txt_voordeel3'] = sanitize_text_field($input['txt_voordeel3']);
			}
			if (isset($input['txt_voordeel4'])) {
				$valid['txt_voordeel4'] = sanitize_text_field($input['txt_voordeel4']);
			}

			if (isset($input['offerte_title'])) {
				$valid['offerte_title'] = sanitize_text_field($input['offerte_title']);
			}

			if (isset($input['kosten_vraagprijs'])) {
				$valid['kosten_vraagprijs'] = sanitize_text_field($input['kosten_vraagprijs']);
			}
			if (isset($input['kosten_vraagprijs_tax'])) {
				$valid['kosten_vraagprijs_tax'] = sanitize_text_field($input['kosten_vraagprijs_tax']);
			}
			if (isset($input['kosten_vraagprijs_no_tax'])) {
				$valid['kosten_vraagprijs_no_tax'] = sanitize_text_field($input['kosten_vraagprijs_no_tax']);
			}
			if (isset($input['kosten_toelating'])) {
				$valid['kosten_toelating'] = sanitize_text_field($input['kosten_toelating']);
			}
			if (isset($input['kosten_transport'])) {
				$valid['kosten_transport'] = sanitize_text_field($input['kosten_transport']);
			}
			if (isset($input['kosten_transport2'])) {
				$valid['kosten_transport2'] = sanitize_text_field($input['kosten_transport2']);
			}
			if (isset($input['kosten_totaal'])) {
				$valid['kosten_totaal'] = sanitize_text_field($input['kosten_totaal']);
			}
			if (isset($input['details_top_txt'])) {
				$valid['details_top_txt'] = sanitize_text_field($input['details_top_txt']);
			}
			if (isset($input['txt_search_title'])) {
				$valid['txt_search_title'] = sanitize_text_field($input['txt_search_title']);
			}
			if (isset($input['txt_search'])) {
				$valid['txt_search'] = wp_kses_post($input['txt_search']);
			}
			if (isset($input['experts_one_name'])) {
				$valid['experts_one_name'] = sanitize_text_field($input['experts_one_name']);
			}
			if (isset($input['experts_one_function'])) {
				$valid['experts_one_function'] = sanitize_text_field($input['experts_one_function']);
			}
			if (isset($input['experts_one_tel'])) {
				$valid['experts_one_tel'] = sanitize_text_field($input['experts_one_tel']);
			}
			if (isset($input['experts_one_mail'])) {
				$valid['experts_one_mail'] = sanitize_text_field($input['experts_one_mail']);
			}
			if (isset($input['experts_two_name'])) {
				$valid['experts_two_name'] = sanitize_text_field($input['experts_two_name']);
			}
			if (isset($input['experts_two_function'])) {
				$valid['experts_two_function'] = sanitize_text_field($input['experts_two_function']);
			}
			if (isset($input['experts_two_tel'])) {
				$valid['experts_two_tel'] = sanitize_text_field($input['experts_two_tel']);
			}
			if (isset($input['experts_two_mail'])) {
				$valid['experts_two_mail'] = sanitize_text_field($input['experts_two_mail']);
			}
			if (isset($input['experts_two_img'])) {
				$valid['experts_two_img'] = sanitize_text_field($input['experts_two_img']);
			}

			if (isset($input['experts_one_img'])) {
				$valid['experts_one_img'] = sanitize_text_field($input['experts_one_img']);
			}
			if (isset($input['top_footer_img'])) {
				$valid['top_footer_img'] = sanitize_text_field($input['top_footer_img']);
			}
			if (isset($input['txt_more_reviews'])) {
				$valid['txt_more_reviews'] = sanitize_text_field($input['txt_more_reviews']);
			}
			if (isset($input['redirect'])) {
				$valid['redirect'] = sanitize_text_field($input['redirect']);
			}
			if (isset($input['tel'])) {
				$valid['tel'] = sanitize_text_field($input['tel']);
			}
			if (isset($input['filters_page'])) {
				$valid['filters_page'] = sanitize_text_field($input['filters_page']);
			}
			if (isset($input['details_page'])) {
				$valid['details_page'] = sanitize_text_field($input['details_page']);
			}

			if (isset($input['txt_price_help'])) {
				$valid['txt_price_help'] = sanitize_text_field($input['txt_price_help']);
			}

			if (isset($input['txt_price_helpp'])) {
				$valid['txt_price_helpp'] = sanitize_text_field($input['txt_price_helpp']);
			}
			if (isset($input['txt_kosten_diensten'])) {
				$valid['txt_kosten_diensten'] = sanitize_text_field($input['txt_kosten_diensten']);
			}

			if (isset($input['txt_experts'])) {
				$valid['txt_experts'] = sanitize_text_field($input['txt_experts']);
			}

			if (isset($input['txt_review'])) {
				$valid['txt_review'] = sanitize_text_field($input['txt_review']);
			}
			if (isset($input['kosten_one_title'])) {
				$valid['kosten_one_title'] = sanitize_text_field($input['kosten_one_title']);
			}
			if (isset($input['kosten_title'])) {
				$valid['kosten_title'] = sanitize_text_field($input['kosten_title']);
			}
			if (isset($input['kosten_restbpm'])) {
				$valid['kosten_restbpm'] = sanitize_text_field($input['kosten_restbpm']);
			}
			if (isset($input['kosten_one_txt'])) {
				$valid['kosten_one_txt'] = sanitize_textarea_field($input['kosten_one_txt']);
			}
			if (isset($input['kosten_two_title'])) {
				$valid['kosten_two_title'] = sanitize_text_field($input['kosten_two_title']);
			}
			if (isset($input['kosten_two_txt'])) {
				$valid['kosten_two_txt'] = sanitize_textarea_field($input['kosten_two_txt']);
			}
			if (isset($input['txt_disclaimer'])) {
				$valid['txt_disclaimer'] = sanitize_textarea_field($input['txt_disclaimer']);
			}
			if (isset($input['txt_co2_disclaimer'])) {
				$valid['txt_co2_disclaimer'] = sanitize_textarea_field($input['txt_co2_disclaimer']);
			}
			if (isset($input['txt_co2_disclaimer_fallback'])) {
				$valid['txt_co2_disclaimer_fallback'] = sanitize_textarea_field($input['txt_co2_disclaimer_fallback']);
			}
			// cta_order already validated above; avoid overwriting here
			if (isset($input['cta_order']) && !isset($valid['cta_order'])) {
				$valid['cta_order'] = sanitize_text_field($input['cta_order']);
			}
			if (isset($input['cta_app'])) {
				$valid['cta_app'] = sanitize_text_field($input['cta_app']);
			}
			if (isset($input['cta_app_app'])) {
				$valid['cta_app_app'] = sanitize_textarea_field($input['cta_app_app']);
			}
			if (isset($input['cta_tel'])) {
				$valid['cta_tel'] = sanitize_text_field($input['cta_tel']);
			}
			if (isset($input['cta_fav'])) {
				$valid['cta_fav'] = sanitize_text_field($input['cta_fav']);
			}
			if (isset($input['cta_fav_fav'])) {
				$valid['cta_fav_fav'] = sanitize_text_field($input['cta_fav_fav']);
			}
			if (isset($input['txt_404_title'])) {
				$valid['txt_404_title'] = sanitize_text_field($input['txt_404_title']);
			}
			if (isset($input['txt_404_btn'])) {
				$valid['txt_404_btn'] = sanitize_text_field($input['txt_404_btn']);
			}
			if (isset($input['txt_404_txt'])) {
				$valid['txt_404_txt'] = sanitize_text_field($input['txt_404_txt']);
			}
			if (isset($input['txt_btn'])) {
				$valid['txt_btn'] = wp_kses_post($input['txt_btn']);
			}
			if (isset($input['contact_app'])) {
				$valid['contact_app'] = wp_kses_post($input['contact_app']);
			}
			if (isset($input['contact_tel'])) {
				$valid['contact_tel'] = wp_kses_post($input['contact_tel']);
			}
			if (isset($input['txt_btn_product'])) {
				$valid['txt_btn_product'] = wp_kses_post($input['txt_btn_product']);
			}
			if (isset($input['txt_srch_btn'])) {
				$valid['txt_srch_btn'] = wp_kses_post($input['txt_srch_btn']);
			}
			if (isset($input['txt_srch'])) {
				$valid['txt_srch'] = wp_kses_post($input['txt_srch']);
			}

			if (isset($input['txt_make'])) {
				$valid['txt_make'] = wp_kses_post($input['txt_make']);
			}

			if (isset($input['txt_priceonrequest'])) {
				$valid['txt_priceonrequest'] = wp_kses_post($input['txt_priceonrequest']);
			}

			if (isset($input['txt_model'])) {
				$valid['txt_model'] = wp_kses_post($input['txt_model']);
			}

			if (isset($input['txt_select_make'])) {
				$valid['txt_select_make'] = wp_kses_post($input['txt_select_make']);
			}

			if (isset($input['txt_select_model'])) {
				$valid['txt_select_model'] = wp_kses_post($input['txt_select_model']);
			}

			if (isset($input['contactcar'])) {
				$valid['contactcar'] = sanitize_textarea_field($input['contactcar']);
			}
			if (isset($input['contactmes'])) {
				$valid['contactmes'] = sanitize_textarea_field($input['contactmes']);
			}
			if (isset($input['contacttimes'])) {
				$valid['contacttimes'] = wp_kses_post($input['contacttimes']);
			}
			if (isset($input['contactaddress'])) {
				$valid['contactaddress'] = wp_kses_post($input['contactaddress']);
			}
			if (isset($input['html_experts'])) {
				$valid['html_experts'] = wp_kses_post($input['html_experts']);
			}
			$valid['enable_pdf'] = (isset($input['enable_pdf']) && !empty($input['enable_pdf'])) ? 1 : 0;

			$valid['only_fl'] = (isset($input['only_fl']) && !empty($input['only_fl'])) ? 1 : 0;
			$valid['enable_fl'] = (isset($input['enable_fl']) && !empty($input['enable_fl'])) ? 1 : 0;

			if (isset($input['fl_percentage'])) {
				$valid['fl_percentage'] = sanitize_text_field($input['fl_percentage']);
			}
			if (isset($input['fl_duration'])) {
				$valid['fl_duration'] = sanitize_text_field($input['fl_duration']);
			}
			if (isset($input['fl_restschuld'])) {
				$valid['fl_restschuld'] = sanitize_text_field($input['fl_restschuld']);
			}

			if (isset($input['fav_opt_title'])) {
				$valid['fav_opt_title'] = sanitize_text_field($input['fav_opt_title']);
			} else {
				$valid['fav_opt_title'] = 'Meest gekozen opties';
			}
			if (isset($input['nonfav_opt_title'])) {
				$valid['nonfav_opt_title'] = sanitize_text_field($input['nonfav_opt_title']);
			} else {
				$valid['nonfav_opt_title'] = 'Overige opties';
			}



			$valid_caroptions = array(
				"AIR_SUSPENSION",
				"ALARM_SYSTEM",
				"ALLOY_WHEELS",
				"ALL_SEASON_TIRES",
				"AMBIENT_LIGHTING",
				"ANDROID_AUTO",
				"ARM_REST",
				"AUTOMATIC_RAIN_SENSOR",
				"AUXILIARY_HEATING",
				"BIODIESEL_SUITABLE",
				"BLIND_SPOT_MONITOR",
				"BLUETOOTH",
				"CARGO_BARRIER",
				"CARPLAY",
				"CD_MULTICHANGER",
				"CD_PLAYER",
				"CENTRAL_LOCKING",
				"COLLISION_AVOIDANCE",
				"DIGITAL_COCKPIT",
				"DIMMING_INTERIOR_MIRROR",
				"DISABLED_ACCESSIBLE",
				"DISTANCE_WARNING_SYSTEM",
				"E10_ENABLED",
				"ELECTRIC_ADJUSTABLE_SEATS",
				"ELECTRIC_BACKSEAT_ADJUSTMENT",
				"ELECTRIC_EXTERIOR_MIRRORS",
				"ELECTRIC_HEATED_REAR_SEATS",
				"ELECTRIC_HEATED_SEATS",
				"ELECTRIC_TAILGATE",
				"ELECTRIC_WINDOWS",
				"EMERGENCY_CALL_SYSTEM",
				"ESP",
				"FATIGUE_WARNING_SYSTEM",
				"FOLD_FLAT_PASSENGER_SEAT",
				"FOUR_WHEEL_DRIVE",
				"FRONT_FOG_LIGHTS",
				"FULL_SERVICE_HISTORY",
				"GLARE_FREE_HIGH_BEAM",
				"HANDS_FREE_PHONE_SYSTEM",
				"HEADLIGHT_WASHER_SYSTEM",
				"HEAD_UP_DISPLAY",
				"HEATED_STEERING_WHEEL",
				"HEATED_WINDSHIELD",
				"HIGH_BEAM_ASSIST",
				"HILL_START_ASSIST",
				"HYBRID_PLUGIN",
				"IMMOBILIZER",
				"ISOFIX",
				"KEYLESS_ENTRY",
				"LANE_DEPARTURE_WARNING",
				"LIGHT_SENSOR",
				"NAVIGATION_SYSTEM",
				"NONSMOKER_VEHICLE",
				"POWER_ASSISTED_STEERING",
				"SOUND_SYSTEM",
				"SUNROOF",
				"SPEED_LIMITER",
				"START_STOP_SYSTEM",
				"TIRE_PRESSURE_MONITORING",
				"TRAFFIC_SIGN_RECOGNITION",
				"TV",
				"VEGETABLEOILFUEL_SUITABLE",
				"WARANTY",
				"WINTER_TIRES",
				"SPORT_PACKAGE",
				"SPORT_SEATS",
				"PERFORMANCE_HANDLING_SYSTEM",
				"PANORAMIC_GLASS_ROOF",
				"DAB_RADIO",
				"TUNER_RADIO",
				"TRAILER_COUPLING"
			);

			foreach ($valid_caroptions as $option) {
				$valid['hide_' . sanitize_text_field($option)] = (isset($input['hide_' . $option]) && !empty($input['hide_' . $option])) ? 1 : 0;
				$valid['fav_' . sanitize_text_field($option)] = (isset($input['fav_' . $option]) && !empty($input['fav_' . $option])) ? 1 : 0;
				$valid['select_' . sanitize_text_field($option)] = (isset($input['select_' . $option]) && !empty($input['select_' . $option])) ? 1 : 0;
			}
		
		return $valid;
	}

	public function eurostocks_clean_ip_history_now()
	{
		global $wpdb;
		$table_name_eurostocks_ip = $wpdb->prefix . 'eurostocks_ip';
		$wpdb->query($wpdb->prepare("DELETE FROM %i WHERE registration_date < (NOW() - INTERVAL 1 DAY)", $table_name_eurostocks_ip));
	}

	public function eurostocks_update_db_check()
	{
		$current_db_version = get_option('eurostocks_db_version');
		if (!$current_db_version) {
			$current_db_version = 0.0;
		}
		

			$current_db_version = floatval($current_db_version);

			if ($current_db_version < 1.0) {

				global $wpdb;

				$charset_collate = $wpdb->get_charset_collate();
				$table_name_eurostocks_ip = $wpdb->prefix . 'eurostocks_ip';

				$sql_eurostocks_ip = $wpdb->prepare("CREATE TABLE %i (
					id mediumint(11) NOT NULL AUTO_INCREMENT,
					remote_addr text DEFAULT '',
					forwarded_for text DEFAULT '',
					blocked mediumint(3) DEFAULT 0,
					registration_date datetime DEFAULT CURRENT_TIMESTAMP,
					PRIMARY KEY  (id)
				);", $table_name_eurostocks_ip);

				require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
				dbDelta($sql_eurostocks_ip);
				$eurostocks_db_version = '1.0';
				update_option('eurostocks_db_version', $eurostocks_db_version);
			}

			if ($current_db_version < 1.1) {
				global $wpdb;

				$charset_collate = $wpdb->get_charset_collate();
				$table_name_eurostocks_ip = $wpdb->prefix . 'eurostocks_requests';

				$sql_eurostocks_ip = $wpdb->prepare("CREATE TABLE %i (
					id mediumint(11) NOT NULL AUTO_INCREMENT,
					user_action text DEFAULT '',
					page_action text DEFAULT '',
					car_make text DEFAULT '',
					car_model text DEFAULT '',
					car_id text DEFAULT '',
					blocked tinyint(1) DEFAULT 0,
					registration_date datetime DEFAULT CURRENT_TIMESTAMP,
					PRIMARY KEY  (id)
				);", $table_name_eurostocks_ip);

				require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
				dbDelta($sql_eurostocks_ip);

				$eurostocks_db_version = '1.1';
				update_option('eurostocks_db_version', $eurostocks_db_version);
			}

			if ($current_db_version < 1.3) {
				global $wpdb;


				$charset_collate = $wpdb->get_charset_collate();
				$table_name_eurostocks_ip = $wpdb->prefix . 'eurostocks_ip';

				$sql_eurostocks_ip = $wpdb->prepare("ALTER TABLE %i ADD COLUMN page_type VARCHAR(50) DEFAULT 'unknown';", $table_name_eurostocks_ip);
				require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
				$wpdb->query( $sql_eurostocks_ip );
			

				$eurostocks_db_version = '1.3';
				update_option('eurostocks_db_version', $eurostocks_db_version);
			}

			if ($current_db_version < 1.4) {
				global $wpdb;

				$table_name_eurostocks_requests = $wpdb->prefix . 'eurostocks_requests';
				$column_exists = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = %s AND COLUMN_NAME = 'blocked' AND TABLE_SCHEMA = DATABASE()",
						$table_name_eurostocks_requests
					)
				);
				if (!$column_exists) {
					$sql_eurostocks_requests = $wpdb->prepare("ALTER TABLE %i ADD COLUMN blocked tinyint(1) DEFAULT 0;", $table_name_eurostocks_requests);

					require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
					$wpdb->query($sql_eurostocks_requests);
				}

				$eurostocks_db_version = '1.4';
				update_option('eurostocks_db_version', $eurostocks_db_version);
			}

			if ($current_db_version < 1.5) {
				global $wpdb;

				$table_name_eurostocks_requests = $wpdb->prefix . 'eurostocks_requests';
				$column_exists = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = %s AND COLUMN_NAME = 'ip_address' AND TABLE_SCHEMA = DATABASE()",
						$table_name_eurostocks_requests
					)
				);

				if (!$column_exists) {
					$sql_eurostocks_requests = $wpdb->prepare("ALTER TABLE %i ADD COLUMN ip_address varchar(100) DEFAULT '';", $table_name_eurostocks_requests);

					require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
					$wpdb->query($sql_eurostocks_requests);
				}

				$eurostocks_db_version = '1.5';
				update_option('eurostocks_db_version', $eurostocks_db_version);
			}
		
	}

	public function export_analytics_csv()
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have permission to access this export.', 'eurostocks'));
		}

		check_admin_referer('eurostocks_export_analytics');

		$acceptable_periods = array('today', 'yesterday', 'week', 'month', 'year', 'all');
		$analytics_period = isset($_GET['analytics_period']) ? sanitize_text_field(wp_unslash($_GET['analytics_period'])) : 'all';
		if (!in_array($analytics_period, $acceptable_periods, true)) {
			$analytics_period = 'all';
		}

		global $wpdb;
		$table_name = $wpdb->prefix . 'eurostocks_requests';

		$where_clause = '';
		switch ($analytics_period) {
			case 'today':
				$where_clause = 'WHERE DATE(registration_date) = CURDATE()';
				break;
			case 'yesterday':
				$where_clause = 'WHERE DATE(registration_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)';
				break;
			case 'week':
				$where_clause = 'WHERE DATE(registration_date) >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK)';
				break;
			case 'month':
				$where_clause = 'WHERE DATE(registration_date) >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)';
				break;
			case 'year':
				$where_clause = 'WHERE DATE(registration_date) >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)';
				break;
			case 'all':
			default:
				$where_clause = '';
				break;
		}

		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, registration_date, page_action, user_action, car_make, car_model, car_id, ip_address, blocked FROM %i {$where_clause} ORDER BY registration_date DESC",
				$table_name
			),
			ARRAY_A
		);

		nocache_headers();
		header('Content-Type: text/csv; charset=utf-8');
		header('Content-Disposition: attachment; filename=eurostocks-analytics.csv');

		$output = fopen('php://output', 'w');
		fputcsv($output, array('id', 'registration_date', 'page_action', 'user_action', 'car_make', 'car_model', 'car_id', 'ip_address', 'blocked'));

		if (is_array($rows)) {
			foreach ($rows as $row) {
				fputcsv($output, $row);
			}
		}

		fclose($output);
		exit;
	}

	public function eurostocks_sanitize_text_field_array($array)
	{
		if (!is_array($array)) {
			return sanitize_text_field($array);
		}

		foreach ($array as $key => &$value) {
			if (is_array($value)) {
				$value = $this->eurostocks_sanitize_text_field_array($value);
			} else {
				$value = sanitize_text_field($value);
			}
		}
		return $array;
	}


	public function eurostocks_update_model_scheduler_handle()
	{
		$car_options = get_option($this->plugin_name . "_cars");
		$makes = [];
		if (isset($car_options['select_available_make']) && is_array($car_options['select_available_make'])) {
			$makes = $car_options['select_available_make'];
		}

		if (!empty($makes)) {
			foreach ($makes as $make) {
				wp_schedule_single_event(time() + 5, 'eurostocks_update_model_job', [$make]);
			}
		}
		return true;
	}

	public function eurostocks_update_model_job_handle($make_key)
	{

		$result = $this->eurostocks_request_models(sanitize_text_field($make_key));

		if (is_array($result)) {

			$modelsArray = array();

			foreach ($result as $k => $v) {
				if (isset($v['modelKey'])) {

					$modelsArray[] = sanitize_text_field($v['modelKey']) . '|' . sanitize_text_field($make_key);
				} else {
					$modelsArray[] = sanitize_text_field($v['modelGroupKey']) . '|' . sanitize_text_field($make_key) . '|GROUP';
					foreach ($v['Models'] as $child) {
						$modelsArray[] = sanitize_text_field($child['modelKey']) . '|' . sanitize_text_field($make_key);
					}
				}
			}
			$option_name = 'eurostocks_models_' . sanitize_text_field($make_key);

			update_option($option_name, $modelsArray);
			return true;
		} else {
			return false;
		}
	}

	public function eurostocks_add_cron_interval($schedules)
	{
		$schedules['monthly'] = array(
			'interval' => 2629744,
			'display'  => esc_html__('Every Month'),
		);
		return $schedules;
	}

	public function check_robots_txt()
	{
		$options = get_option($this->plugin_name);

		$option_name = 'eurostocks_error';
		if (get_option($option_name)) {
			delete_option($option_name);
		}

		$filter_page_id = $options['filters_page'];
		$url = get_permalink($filter_page_id);
		if (isset($url)) {
			$check = new Eurostocks_Robot_Txt_Parser($url);
			$check = $check->is_robots_allowed();
			$result = array('disallowed' => $check);
			echo json_encode($result);
		}

		wp_die();
	}

	function eurostocks_get_available_ctas() {
		return [
			'cta_cf'  		=> __('Mail us', 'eurostocks'),
			'cta_app'       => __('App', 'eurostocks'),
			'cta_tel'       => __('Call', 'eurostocks'),
			'cta_fav'       => __('Favorite', 'eurostocks'),
		];
	}



}
