<?php

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

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

	/**
	 * 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 the 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 public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{
		wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/eurostocks-public.css', array(), $this->version, 'all');
		wp_enqueue_style($this->plugin_name . '-owl', plugin_dir_url(__FILE__) . 'js/node_modules/owl.carousel/dist/assets/owl.carousel.min.css', array(), $this->version, 'all');
		wp_enqueue_style($this->plugin_name . 'owl-theme', plugin_dir_url(__FILE__) . 'js/node_modules/owl.carousel/dist/assets/owl.theme.default.min.css', array(), $this->version, 'all');
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts()
	{
		$ajax_nonce = wp_create_nonce("eurostocks_nonce");

		$options = get_option($this->plugin_name);
		if (isset($options['expand_filters'])) {
			$expand_filters = $options['expand_filters'];
		} else {
			$expand_filters = 0;
		}
		$anti_spam_script_texts = array(
			'success' => wp_strip_all_tags(Eurostocks_Anti_Spam_Settings::get_text('ajax_success_message')),
			'error'   => wp_strip_all_tags(Eurostocks_Anti_Spam_Settings::get_text('ajax_generic_error_message')),
		);
		wp_enqueue_script($this->plugin_name . '-public', plugin_dir_url(__FILE__) . 'js/eurostocks-public.js', array('jquery'), $this->version, false);
		wp_localize_script(
			$this->plugin_name . '-public',
			'eurostocks',
			array(
				'admin_url'           => admin_url('admin-ajax.php'),
				'eurostocks_security' => $ajax_nonce,
				'eurostocks_filters'  => $expand_filters,
				'anti_spam_texts'     => $anti_spam_script_texts,
			)
		);
		wp_enqueue_script($this->plugin_name . '-owl', plugin_dir_url(__FILE__) . 'js/node_modules/owl.carousel/dist/owl.carousel.min.js', array('jquery'), $this->version, false);
		wp_enqueue_script($this->plugin_name . '-fslightbox', plugin_dir_url(__FILE__) . 'js/node_modules/fslightbox/index.js', array(), $this->version, true);
		wp_enqueue_script($this->plugin_name . '-popperjs', plugin_dir_url(__FILE__) . 'js/node_modules/@popperjs/core/dist/umd/popper.min.js', array(), $this->version, true);
		wp_enqueue_script($this->plugin_name . '-tippy', plugin_dir_url(__FILE__) . 'js/node_modules/tippy.js/dist/tippy-bundle.umd.min.js', array($this->plugin_name . '-popperjs'), $this->version, true);

		if (isset($options['use_as_iframe']) && $options['use_as_iframe'] == 1) {
			wp_enqueue_script($this->plugin_name . '-iframe', plugin_dir_url(__FILE__) . 'js/iframeResizer.contentWindow.min.js', array(), $this->version, false);
		}
	}

	public function eurostocks_send_form()
	{
		// check nonce 

		if (!check_ajax_referer('eurostocks_nonce', 'security')) {
			wp_send_json_error();
			wp_die();
		} else {
			// check nonce again
			if (isset($_POST['security'])) {
				if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'eurostocks_nonce')) {
					wp_send_json_error();
					wp_die();
				}
			} else {
				wp_send_json_error();
				wp_die();
			}
			if (!isset($_POST['data-action'])) {
				echo "error, missing data action";
				wp_die();
			}
			if (isset($_POST['url']) && $_POST['url'] != "") {
				wp_die();
			}
			$options = get_option($this->plugin_name);

			if (isset($options['contactmes']) && $options['contactmes'] != "") {
				$contactmes = $options['contactmes'];
			} else {
				$contactmes = "";
			}
			if (isset($options['contactcar']) && $options['contactcar'] != "") {
				$contactcar = $options['contactcar'];
			} else {
				$contactcar = "";
			}


			if (isset($_POST['form_id']) && $_POST['form_id'] == "a") {
				$redirect_to = $options['redirect'];
				$to = $options['email'];


				$headers = array();
				// add reply to
				if (isset($_POST['email']) && $_POST['email'] != "") {
					$headers[] = 'Reply-To: ' . sanitize_text_field($_POST['email']);
				}
				$message = "Beste, \r\n";
				$message .= "Er is een import auto vraag binnen gekomen via de website. \r\n \r\n";

				$message .= esc_html__("Name:", "eurostocks") . " " . esc_html(sanitize_text_field($_POST['name'])) . "  \r\n";
				$message .= esc_html__("E-mail:", "eurostocks") . " " . esc_html(sanitize_text_field($_POST['email'])) . "  \r\n";
				$message .= esc_html__("Tel:", "eurostocks") . " " . esc_html(sanitize_text_field($_POST['tel'])) . "  \r\n";
				$message .= esc_html__("Message:", "eurostocks") . " " . esc_html(sanitize_text_field($_POST['message'])) . "  \r\n \r\n";
				$message .= esc_html__("Url:", "eurostocks") . " " . esc_url(sanitize_text_field($_POST['car'])) . "  \r\n \r\n";
				$message .= esc_html($contactmes) . "  \r\n";

				// interne mail
				wp_mail($to, "Import auto zoeken - " . esc_html(sanitize_text_field($_POST['name'])), $message, $headers, '');

				$analytics = new Eurostocks_Analytics('contactform', 'filter', '', '', '');
				$analytics->register_visit();

				$data = array(
					'message' => __("Het contactformulier is succesvol verzonden", 'eurostocks'),
					'redirect_url' => esc_url($redirect_to)
				);

				$option_name = 'eurostocks_sendmailc';
				if (get_option($option_name) !== false) {
					$current = intval(get_option($option_name));
					$current++;
					update_option($option_name, $current);
				} else {

					$autoload = 'no';
					add_option($option_name, 1, "", $autoload);
				}
			} else {
				$to = $options['email'];
				$headers = array();
				if (isset($_POST['email']) && $_POST['email'] != "") {
					$headers[] = 'Reply-To: ' . sanitize_text_field($_POST['email']);
				}


				$redirect_to = $options['redirect'];
				$message  = __("Dear, ") . " \r\n";
				$message .= __("An import car request has been received via the website.", 'eurostocks') . " \r\n \r\n";
				$message .= __("Car: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['car'])) . "  \r\n \r\n";
				$message .= __("Details: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['euroCarDetails'])) . "  \r\n \r\n";
				$message .= __("Name: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['name'])) . "  \r\n";
				$message .= __("E-mail: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['email'])) . "  \r\n";
				$message .= __("Tel: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['tel'])) . "  \r\n";
				$message .= __("Message: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['message'])) . "  \r\n \r\n";

				if (isset($_POST["auto_ruilen"]) && !empty($_POST["auto_ruilen"])) {
					$message .= __("Trade car: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['auto_ruilen'])) . "  \r\n \r\n";
				}
				if (isset($_POST['kenteken']) && $_POST['kenteken'] != "") {
					$message .= esc_html__("License: ", "eurostocks") . esc_html(sanitize_text_field($_POST['kenteken'])) . "  \r\n \r\n";
				}
				if (isset($_POST['kilometerstand']) && $_POST['kilometerstand'] != "") {
					$message .= esc_html__("Mileage: ", "eurostocks") . esc_html(sanitize_text_field($_POST['kilometerstand'])) . "  \r\n \r\n";
				}
				if (isset($_POST["leaseofferte"]) && !empty($_POST["leaseofferte"])) {
					$message .= esc_html__("Lease quote: ", "eurostocks") . esc_html(sanitize_text_field($_POST['lease_offerte'])) . "  \r\n \r\n";
				}

				$message .= $contactmes . "  \r\n";

				wp_mail($to, "Import " . esc_html(sanitize_text_field($_POST['carTitle'])), $message, $headers, '');

				$analytics = new Eurostocks_Analytics('contactform', 'detail', '', '', '');
				$analytics->register_visit();

				$to_client = sanitize_text_field($_POST['email']);
				$headers = array();
				$headers[] = 'Reply-To: ' . $to;
				$message_client = $contactcar;
				$message_client .= " \r\n\r\n";
				$message_client .= __("Details: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['euroCarDetails'])) . "  \r\n \r\n";
				$message_client .= __("Name: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['name'])) . "  \r\n";
				$message_client .= __("E-mail: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['email'])) . "  \r\n";
				$message_client .= __("Tel: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['tel'])) . "  \r\n";
				$message_client .= __("Message: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['message'])) . "  \r\n \r\n";
				$message_client .= "Url: " . esc_url(sanitize_text_field($_POST['car'])) . "  \r\n \r\n";

				if (isset($_POST["auto_ruilen"]) && !empty($_POST["auto_ruilen"])) {
					$message_client .= __("Trade car: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['auto_ruilen'])) . "  \r\n \r\n";
				}
				if (isset($_POST['kenteken']) && $_POST['kenteken'] != "") {
					$message_client .= "License plate: " . esc_html(sanitize_text_field($_POST['kenteken'])) . "  \r\n \r\n";
				}
				if (isset($_POST['kilometerstand']) && $_POST['kilometerstand'] != "") {
					$message_client .= esc_html__("Mileage: ", "eurostocks") . esc_html(sanitize_text_field($_POST['kilometerstand'])) . "  \r\n \r\n";
				}
				if (isset($_POST["leaseofferte"]) && !empty($_POST["leaseofferte"])) {
					$message_client .= __("Lease quote: ", 'eurostocks') . esc_html(sanitize_text_field($_POST['leaseofferte'])) . "  \r\n \r\n";
				}

				$message_client .= $contactmes . "  \r\n";

				wp_mail(
					$to_client,
					sprintf(
						esc_html__('Your request for %s has been successfully received', 'eurostocks'),
						esc_html(sanitize_text_field($_POST['carTitle']))
					),
					$message_client,
					$headers,
					''
				);
			} // end if

			$data = array(
				'message' => __("The contact form has been sent successfully", 'eurostocks'),
				'redirect_url' => $redirect_to
			);

			$option_name = 'eurostocks_sendmailc';

			if (get_option($option_name) !== false) {
				$current = intval(get_option($option_name));
				$current++;
				update_option($option_name, $current);
			} else {
				$deprecated = null;
				$autoload = 'no';
				add_option($option_name, 1);
			}
			wp_send_json_success($data);

			wp_die();
		}
	}


	public function eurostocks_details_shortcode($atts = array())
	{

		global $wp_query;

		if (isset($wp_query->query_vars['euro_var'])) {
			$car_id = sanitize_text_field($wp_query->query_vars['euro_var']);
			$lang = get_locale();
			if ($lang == 'nl_NL') {
				$language_iso_code = 'nl';
			} elseif ($lang == 'fr_FR') {
				$language_iso_code = 'fr';
			} elseif ($lang == 'de_DE') {
				$language_iso_code = 'de';
			} else {
				$language_iso_code = 'en';
			}

			// ip check request
			$ip_status = $this->eurostocks_checkIpAddress('vehicle_detail');
			if (isset($ip_status['status']) && 'allowed' === $ip_status['status']) {

				$data = $this->eurostocks_request_vehicle_details($car_id, $language_iso_code);
				if (isset($data['vehicle']['make']) && isset($data['vehicle']['model'])) {
					$make = sanitize_text_field($data['vehicle']['make']);
					$model = sanitize_text_field($data['vehicle']['model']);
				} else {
					$make = '';
					$model = '';
				}

				$analytics = new Eurostocks_Analytics('pageview', 'detail', $make, $model, $car_id);
				$analytics->register_visit();
				ob_start();
				
				include_once('partials/eurostocks-public-vehicle-details-display.php');
				return ob_get_clean();
			} elseif (isset($ip_status['status']) && 'verify_email' === $ip_status['status']) {
				$analytics = new Eurostocks_Analytics('pageview', 'detail', '', '', $car_id, 1);
				$analytics->register_visit();
				return $this->render_verification_form($ip_status);
			} else {
				$analytics = new Eurostocks_Analytics('pageview', 'detail', '', '', $car_id, 1);
				$analytics->register_visit();
				return $this->render_limit_message($ip_status);
			}
		}

		return '';
	}

	public function custom_rewrite_rule()
	{
	
		$lang_data      = eurostocks_get_language_details();
		$default_lang   = $lang_data['default_lang'];
		$current_lang   = $lang_data['current_lang'];
		$diflang        = $lang_data['diflang'];

		if(!$diflang || function_exists('weglot_get_current_language')){
			$options = get_option($this->plugin_name);

			if (isset($options['details_page'])) {
				add_rewrite_rule('^' . 'auto' . '/([\-\w+]*)' . '/' . '([\-\w+]*)', 'index.php?page_id=' . $options['details_page'] . '&euro_var=$matches[1]&euro_type=$matches[2]', 'top');
				add_rewrite_rule('^' . 'auto' . '/([^/]*)/?', 'index.php?page_id=' . $options['details_page'] . '&euro_var=$matches[1]', 'top');
			}
		}
		else{
			$options = get_option($this->plugin_name);
			if(isset($options[esc_html($current_lang)]) && isset($options[esc_html($current_lang)]['details_page'])){
				$details_page = $options[esc_html($current_lang)]['details_page'];
				add_rewrite_rule('^' . esc_html($current_lang) . '/' . 'auto' . '/([\-\w+]*)' . '/' . '([\-\w+]*)', 'index.php?page_id=' . $details_page . '&euro_var=$matches[1]&euro_type=$matches[2]', 'top');
				add_rewrite_rule('^' . esc_html($current_lang) . '/' . 'auto' . '/([^/]*)/?', 'index.php?page_id=' . $details_page . '&euro_var=$matches[1]', 'top');
			}		
		}
		
	}

	public function custom_rewrite_tag()
	{
		add_rewrite_tag('%euro_var%', '([^&]+)');
		add_rewrite_tag('%euro_type%', '([^&]+)');
		flush_rewrite_rules();
	}

	public function eurostocks_search_shortcode($atts = array())
	{
		$analytics = new Eurostocks_Analytics('pageview', 'search', '', '', '');
		$analytics->register_visit();

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

		if (!is_array($atts)) {
			$atts = array();
		}
		

		ob_start();
		include_once('partials/eurostocks-public-search.php');
		return ob_get_clean();
	}

	public function eurostocks_shortcode($atts = array())
	{
		if (!is_array($atts)) {
			$atts = array();
		}

		$options = get_option($this->plugin_name);
		$current_page_id = get_the_ID();
		if (isset($options['filters_page'])) {
			$filter_page = intval($options['filters_page']);
			
			if ($current_page_id != $filter_page) {
				$option_name = 'eurostocks_error';
				if (get_option($option_name) == false) {
					add_option($option_name, 1, "", false);
				} 
			}
		} 
		
		$car_options = get_option('eurostocks_cars');

		$make = '';
		$model = '';

		$modelNotNeeded = false;
		$makeNotNeeded = false;
		if ((isset($atts['allow_make_only']) && $atts['allow_make_only'] == "true") || (isset($car_options['make_only']) && ($car_options['make_only'] == 1 || $car_options['make_only'] == 2))) {
			$modelNotNeeded = true;

			if($car_options['make_only'] == 2){
				$makeNotNeeded = true;
			}
		}
		


		if (isset($_GET['pagenumber']) && $_GET['pagenumber'] != '') {
			$atts['pagenumber'] = sanitize_text_field($_GET['pagenumber']);
		} else {
			$atts['pagenumber'] = 1;
		}
		if (isset($_GET['model'])) {
			$modelexpl = explode('|', stripcslashes(sanitize_text_field($_GET['model'])));
			if (isset($modelexpl[1])) {
				unset($atts['model']);
				$atts['model_group'] = $modelexpl[0];
				$model = $modelexpl[0];
			} else {
				$atts['model'] = $modelexpl[0];
				$model = $modelexpl[0];
				unset($atts['model_group']);
			}
		} else {
			if(isset($atts['model'])){
				$modelexpl = explode('|', stripcslashes(sanitize_text_field($atts['model'])));
				if (isset($modelexpl[1])) {
					unset($atts['model']);
					$atts['model_group'] = $modelexpl[0];
					$model = $modelexpl[0];
				} else {
					$atts['model'] = $modelexpl[0];
					$model = $modelexpl[0];
					unset($atts['model_group']);
				}
			}
			else{
				$model = '';
				if ($modelNotNeeded) {
					unset($atts['model']);
					unset($atts['model_group']);
				}
			}
			
		}

		$atts['feature'] = array();
		if (isset($options['feature_warranty']) && $options['feature_warranty'] == 1) {
			$atts['feature'][] = 'WARRANTY';
		}

		if (isset($options['maintenance_history']) && $options['maintenance_history'] == 1) {
			$atts['feature'][] = 'FULL_SERVICE_HISTORY';
		}

		if (isset($options['no_damage_history']) && $options['no_damage_history'] == 1) {
			$atts['is_accident_damaged'] = false;
		}

		if (isset($options['max_prev_owners']) && $options['max_prev_owners'] == 1) {
			$atts['number_of_previous_owners_max'] = 1;
		}

		if (isset($options['dealers'])) {
			$atts['customer_id'] = esc_html($options['dealers']);
		}

		if (isset($_GET['yearFrom']) && $_GET['yearFrom'] != '') {
			$atts['year_from'] = sanitize_text_field($_GET['yearFrom']);
		} elseif (isset($atts['year_from']) && $atts['year_from'] !== '') {
			$atts['year_from'] = sanitize_text_field($atts['year_from']);
		} elseif (isset($options['min_bouwjaar']) && $options['min_bouwjaar'] != '') {
			$atts['year_from'] = (int) $options['min_bouwjaar'];
		}

		if (isset($_GET['yearTo']) && $_GET['yearTo'] != '') {
			$atts['year_to'] = sanitize_text_field($_GET['yearTo']);
		}

		if (isset($_GET['mileageFrom']) && $_GET['mileageFrom'] != '') {
			$atts['mileage_from'] = sanitize_text_field($_GET['mileageFrom']);
		}

		if (isset($_GET['mileageTo']) && $_GET['mileageTo'] != '') {
			$atts['mileage_to'] = sanitize_text_field($_GET['mileageTo']);
		} else {
			if (isset($options['max_kmstand']) && $options['max_kmstand'] != '') {
				$atts['mileage_to'] = (int) $options['max_kmstand'];
			}
		}

		if (isset($_GET['powerFrom']) && $_GET['powerFrom'] != '') {
			$atts['power_from'] = sanitize_text_field($_GET['powerFrom']);
		}

		if (isset($_GET['powerTo']) && $_GET['powerTo'] != '') {
			$atts['power_to'] = sanitize_text_field($_GET['powerTo']);
		}

		if (isset($_GET['priceFrom']) && $_GET['priceFrom'] != '') {
			$atts['price_from'] = sanitize_text_field($_GET['priceFrom']);
		}

		if (isset($_GET['priceTo']) && $_GET['priceTo'] != '') {
			$atts['price_to'] = sanitize_text_field($_GET['priceTo']);
		}

		if (isset($_GET['fuelType']) && $_GET['fuelType'] != '') {
			$atts['fuel_type'] = sanitize_text_field($_GET['fuelType']);
		}

		if (isset($_GET['transmission']) && $_GET['transmission'] != '') {
			$atts['transmission'] = sanitize_text_field($_GET['transmission']);
		}

		if (isset($_GET['speedControl']) && $_GET['speedControl'] != '') {
			$atts['speed_control'] = sanitize_text_field($_GET['speedControl']);
		}

		if (isset($_GET['interiorType']) && $_GET['interiorType'] != '') {
			$atts['interior_type'] = sanitize_text_field($_GET['interiorType']);
		}

	

		if (isset($_GET['climatisation']) && $_GET['climatisation'] != '') {
			$atts['climatisation'] = sanitize_text_field($_GET['climatisation']);
		}

		if (isset($_GET['carCategory']) && $_GET['carCategory'] != '') {
			$atts['category'] = sanitize_text_field($_GET['carCategory']);
		}

		if (isset($_GET['headlightType']) && $_GET['headlightType'] != '') {
			$atts['headlight_type'] = sanitize_text_field($_GET['headlightType']);
		}

		if (isset($_GET['doorCount']) && $_GET['doorCount'] != '') {
			$atts['door_count'] = sanitize_text_field($_GET['doorCount']);
		}

		if (isset($_GET['driveType']) && $_GET['driveType'] != '') {
			$atts['drive_type'] = sanitize_text_field($_GET['driveType']);
		}

		if (isset($_GET['vat']) && $_GET['vat'] != '') {
			$atts['vat'] = sanitize_text_field($_GET['vat']);
		}

		if (isset($_GET['exteriorColor']) && $_GET['exteriorColor'] != '') {
			$atts['exterior_color'] = sanitize_text_field($_GET['exteriorColor']);
		}

		if (isset($_GET['seatsCount']) && $_GET['seatsCount'] != '') {
			$atts['seats_count'] = sanitize_text_field($_GET['seatsCount']);
		}

		if (isset($_GET['sortOn']) && $_GET['sortOn'] != '') {
			$atts['sort_on'] = sanitize_text_field($_GET['sortOn']);
		} else {
			if (isset($options['default_sort']) && $options['default_sort'] != '') {
				$atts['sort_on'] = $options['default_sort'];
			} else {
				$atts['sort_on'] = 'creationDesc';
			}
		}

		if (isset($_GET['options']) && $_GET['options'] != '' && is_array($_GET['options']) && !empty($_GET['options'])) {
			foreach ($_GET['options'] as $option) {
				$atts['feature'][] = sanitize_text_field($option);
			}
		}

		if (isset($_GET['parkingAssistant']) && $_GET['parkingAssistant'] != '') {

			foreach ($_GET['parkingAssistant'] as $option) {
				$atts['parking_assistant'][] = sanitize_text_field($option);
			}
		}

		$lang = get_locale();
		if ($lang == 'nl_NL') {
			$atts['language_iso_code'] = 'nl';
		} elseif ($lang == 'fr_FR') {
			$atts['language_iso_code'] = 'fr';
		} elseif ($lang == 'de_DE') {
			$atts['language_iso_code'] = 'de';
		} else {
			$atts['language_iso_code'] = 'en';
		}

		$ip_status = $this->eurostocks_checkIpAddress('vehicle_list');

		if (! isset($ip_status['status'])) {
			$ip_status['status'] = 'allowed';
		}

		if ('allowed' === $ip_status['status']) {
			if ($modelNotNeeded == true) {
				if (isset($_GET['make']) && $_GET['make'] != '') {
					$make = sanitize_text_field($_GET['make']);
					if($make == ''){
						$make = '';
						$model = '';
					}else{
						if(!isset($_GET['model'])){
							$model = '';
							$atts['model'] = '';
						}
					}
					$atts['make'] = $make;
					$data = $this->eurostocks_request_vehicles($atts);
				} elseif (isset($atts['make']) && $atts['make'] != '') {
					$data = $this->eurostocks_request_vehicles($atts);
					$make = $atts['make'];
				} else {
					if($makeNotNeeded == true){
						$data = $this->eurostocks_request_vehicles($atts);
						$make = '';
						$model = '';
					}
					else{
						$data = array();
						$make = '';
						$model = '';
					}
				
				}
			} elseif (isset($_GET['make']) && isset($_GET['model'])) {
				$make = sanitize_text_field($_GET['make']);
				$atts['make'] = $make;
				$model = sanitize_text_field($_GET['model']);
				
				$modelexpl = explode('|', stripcslashes(sanitize_text_field($_GET['model'])));
				if (isset($modelexpl[1])) {
					unset($atts['model']);
					$atts['model_group'] = $modelexpl[0];
					$model = $modelexpl[0];
				} else {
					$atts['model'] = $modelexpl[0];
					$model = $modelexpl[0];
					unset($atts['model_group']);
				}

				$data = $this->eurostocks_request_vehicles($atts);
			} elseif (isset($atts['make']) && $atts['make'] != '' && isset($atts['model']) && $atts['model'] != '') {

				$modelexpl = explode('|', stripcslashes(sanitize_text_field($atts['model'])));
				if (isset($modelexpl[1])) {
					unset($atts['model']);
					$atts['model_group'] = $modelexpl[0];
					$model = $modelexpl[0];
				} else {
					$atts['model'] = $modelexpl[0];
					$model = $modelexpl[0];
					unset($atts['model_group']);
				}


				$data = $this->eurostocks_request_vehicles($atts);
				$make = $atts['make'];
			} else {
				if($makeNotNeeded == true){
					$data = $this->eurostocks_request_vehicles($atts);
					$make = '';
					$model = '';
				}
				else{
					$data = array();
					$make = '';
					$model = '';
				}
			}
			$analytics = new Eurostocks_Analytics('pageview', 'filter', $make, $model, '');
			$analytics->register_visit();
		} elseif ('verify_email' === $ip_status['status']) {
			$analytics = new Eurostocks_Analytics('pageview', 'filter', $make, $model, '', 1);
			$analytics->register_visit();
			return $this->render_verification_form($ip_status);
		} else {
			$analytics = new Eurostocks_Analytics('pageview', 'filter', $make, $model, '', 1);
			$analytics->register_visit();
			return $this->render_limit_message($ip_status);
		}
 
		ob_start();
		if ($data == 429) {
			echo "Limiet bereikt";
		}
		include_once('partials/eurostocks-public-display.php');
		return ob_get_clean();
	}

	public function endsWith($haystack, $needle)
	{
		return substr_compare($haystack, $needle, -strlen($needle)) === 0;
	}


	public function eurostocks_request_vehicles($args)
	{
		$login = get_option($this->plugin_name);
		$client = new Eurostocks_Request($login['username'], $login['password'], $login['api_key']);
		$vehicles = $client->getVehicleList($args);

		return $vehicles;

		wp_die();
	}

	public function eurostocks_request_vehicle_details($vehicle_id, $lang)
	{
		$login = get_option($this->plugin_name);

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

		return $vehicle;

		wp_die();
	}

	public function eurostocks_details_pdf($atts = array())
	{
		global $wp_query;

		if (isset($wp_query->query_vars['euro_var']) && isset($wp_query->query_vars['euro_type']) && $wp_query->query_vars['euro_type'] == "pdf") {
			$lang = get_locale();
			if ($lang == 'nl_NL') {
				$language_iso_code = 'nl';
			} else {
				$language_iso_code = 'en';
			}
			$car_id = sanitize_text_field($wp_query->query_vars['euro_var']);
			$ip_status = $this->eurostocks_checkIpAddress('vehicle_pdf');
			if (isset($ip_status['status']) && 'allowed' === $ip_status['status']) {

				$dompdf = new \Dompdf\Dompdf();
				$options = $dompdf->getOptions();
				$options->set(array('isRemoteEnabled' => true));
				$dompdf->setOptions($options);
				$dompdf->setPaper('A4', 'portret');

				$data = $this->eurostocks_request_vehicle_details($car_id, $language_iso_code);
				if (isset($data['vehicle']['make']) && isset($data['vehicle']['model'])) {
					$make = sanitize_text_field($data['vehicle']['make']);
					$model = sanitize_text_field($data['vehicle']['model']);
				} else {
					$make = '';
					$model = '';
				}

				$analytics = new Eurostocks_Analytics('pageview', 'detail_pdf', $make, $model, $car_id);
				$analytics->register_visit();

				ob_start();
				if ($data == 429) {
					echo "Limiet bereikt";
				}
				include_once('partials/eurostocks-public-vehicle-details-pdf.php');
				$html = ob_get_clean();
				$dompdf->loadHtml($html);
				$dompdf->render();
				$dompdf->stream("auto-" . $wp_query->query_vars['euro_type'] . ".pdf", array('Attachment' => 0));
				exit();
			} elseif (isset($ip_status['status']) && 'verify_email' === $ip_status['status']) {
				$pdf_verify_message = Eurostocks_Anti_Spam_Settings::get_text('pdf_limit_verify_message');
				$analytics = new Eurostocks_Analytics('pageview', 'detail_pdf', '', '', $car_id, 1);
				$analytics->register_visit();
				wp_die(
					esc_html($pdf_verify_message),
					esc_html__('Verification required', 'eurostocks'),
					array('response' => 429)
				);
			} else {
				$pdf_block_message = Eurostocks_Anti_Spam_Settings::get_text('pdf_limit_block_message');
				$analytics = new Eurostocks_Analytics('pageview', 'detail_pdf', '', '', $car_id, 1);
				$analytics->register_visit();
				wp_die(
					esc_html($pdf_block_message),
					esc_html__('Limit reached', 'eurostocks'),
					array('response' => 429)
				);
			}
		}
	}


	public function eurostocks_checkIpAddress($page_type = 'general')
	{
		$ipoptions = get_option('eurostocks-anti-spam');
		if (isset($ipoptions['disable_ipfilter']) && $ipoptions['disable_ipfilter'] == 1) {
			return array('status' => 'allowed');
		} else {
			$checkip = new Eurostocks_Botchecker();
			return $checkip->checkIp($page_type);
		}
	}

	protected function render_verification_form($context = array())
	{
		$limit     = isset($context['limit']) ? (int) $context['limit'] : 0;
		$count     = isset($context['count']) ? (int) $context['count'] : 0;
		$page_type = isset($context['page_type']) ? sanitize_key($context['page_type']) : 'general';
		$limit_reason = isset($context['reason_key']) && $context['reason_key'] !== '' ? sanitize_key($context['reason_key']) : Eurostocks_Anti_Spam_Settings::get_reason_key_for_page_type($page_type);
		$verification_status = isset($_GET['eurostocks_verification']) ? sanitize_text_field(wp_unslash($_GET['eurostocks_verification'])) : '';
		$anti_spam_texts = Eurostocks_Anti_Spam_Settings::get_texts();
		$attempt_limit = Eurostocks_Email_Verification::MAX_ATTEMPTS_PER_DAY;
		$attempts_remaining = Eurostocks_Email_Verification::attempts_remaining($this->get_client_ip(), $attempt_limit);

		ob_start();
		include plugin_dir_path(__FILE__) . 'partials/eurostocks-public-email-verification.php';
		return ob_get_clean();
	}

	protected function render_limit_message($status)
	{
		$fallback_message = Eurostocks_Anti_Spam_Settings::get_text('limit_generic_message');
		$message = isset($status['message']) && $status['message'] !== '' ? $status['message'] : $fallback_message;
		return esc_html($message);
	}

	public function submit_verification_email()
	{
		$anti_spam_texts = Eurostocks_Anti_Spam_Settings::get_texts();

		if (!check_ajax_referer('eurostocks_nonce', 'security', false)) {
			wp_send_json_error(array('message' => $anti_spam_texts['form_security_error_message']));
		}

		$email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
		$page_type = isset($_POST['page_type']) ? sanitize_key(wp_unslash($_POST['page_type'])) : 'general';
		$page_type = $page_type !== '' ? $page_type : 'general';
		$return_url = isset($_POST['return_url']) ? wp_unslash($_POST['return_url']) : '';
		$return_url = $this->resolve_return_url($return_url);

		if ('' === $email || !is_email($email)) {
			wp_send_json_error(array('message' => $anti_spam_texts['ajax_invalid_email_message']));
		}

		if (Eurostocks_Email_Verification::is_disposable_email($email)) {
			wp_send_json_error(array('message' => $anti_spam_texts['ajax_disposable_email_message']));
		}

		$ip = $this->get_client_ip();
		if ('' === $ip) {
			wp_send_json_error(array('message' => $anti_spam_texts['ajax_missing_ip_message']));
		}

		$attempt_limit = Eurostocks_Email_Verification::MAX_ATTEMPTS_PER_DAY;
		if ($attempt_limit > 0 && !Eurostocks_Email_Verification::can_attempt($ip, $attempt_limit)) {
			wp_send_json_error(array(
				'message'             => $anti_spam_texts['ajax_attempt_limit_message'],
				'attempts_remaining'  => 0,
			));
		}

		$limit_reason = '';
		$ip_metadata = Eurostocks_Anti_Spam_Settings::get_ip_metadata_for($ip);
		if (!empty($ip_metadata) && !empty($ip_metadata['reason_key'])) {
			$limit_reason = sanitize_key($ip_metadata['reason_key']);
		}
		if ('' === $limit_reason) {
			$limit_reason = Eurostocks_Anti_Spam_Settings::get_reason_key_for_page_type($page_type);
		}

		$token = $this->generate_verification_token();

		Eurostocks_Email_Verification::delete_tokens_for_ip($ip);
		Eurostocks_Email_Verification::store_token($token, $ip, $email, $page_type, $return_url, $limit_reason);
		Eurostocks_Email_Verification::mark_pending($ip, $email, $token, $page_type, $return_url, $limit_reason);
		Eurostocks_Anti_Spam_Settings::record_ip_event($ip, array(
			'status'     => 'verify_email',
			'reason_key' => $limit_reason,
			'page_type'  => $page_type,
		));

		$verification_link = add_query_arg(
			array('eurostocks_verify' => rawurlencode($token)),
			home_url('/')
		);

		$subject_template = $anti_spam_texts['email_subject'] !== '' ? $anti_spam_texts['email_subject'] : __('Verify your email address', 'eurostocks');
		$site_name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$subject = str_replace('{site_name}', $site_name, $subject_template);
		$subject = wp_strip_all_tags($subject, true);

		$email_body_template = $anti_spam_texts['email_body'];
		$message = str_replace(
			array('{verification_link}', '{site_name}'),
			array(esc_url_raw($verification_link), wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES)),
			$email_body_template
		);

		$sent = wp_mail($email, $subject, $message, array('Content-Type: text/plain; charset=UTF-8'));

		if (!$sent) {
			delete_transient(Eurostocks_Email_Verification::TOKEN_TRANSIENT_PREFIX . $token);
			delete_transient(Eurostocks_Email_Verification::STATUS_TRANSIENT_PREFIX . Eurostocks_Email_Verification::hash_ip($ip));
			$current_attempts_remaining = Eurostocks_Email_Verification::attempts_remaining($ip, $attempt_limit);
			wp_send_json_error(array(
				'message'             => $anti_spam_texts['ajax_send_error_message'],
				'attempts_remaining'  => $current_attempts_remaining,
			));
		}

		$attempt_data = Eurostocks_Email_Verification::increment_attempts($ip, $attempt_limit);
		$attempts_remaining = $attempt_limit > 0 ? max(0, $attempt_limit - (int) $attempt_data['count']) : 0;

		wp_send_json_success(array(
			'message'             => $anti_spam_texts['ajax_success_message'],
			'attempts_remaining'  => $attempts_remaining,
		));
	}

	public function maybe_handle_email_verification()
	{
		if (!isset($_GET['eurostocks_verify'])) {
			return;
		}

		$token = sanitize_text_field(wp_unslash($_GET['eurostocks_verify']));
		if ('' === $token) {
			wp_safe_redirect($this->prepare_verification_redirect('', 'failed'));
			exit;
		}

		$payload = Eurostocks_Email_Verification::get_token_payload($token, true);
		$return_url = '';
		if (is_array($payload) && isset($payload['return_url'])) {
			$return_url = $payload['return_url'];
		}

		if (false === $payload || !isset($payload['ip']) || !isset($payload['email'])) {
			wp_safe_redirect($this->prepare_verification_redirect($return_url, 'failed'));
			exit;
		}

		Eurostocks_Email_Verification::mark_verified($payload['ip'], $payload['email']);

		wp_safe_redirect($this->prepare_verification_redirect($return_url, 'success'));
		exit;
	}

	protected function resolve_return_url($raw_url)
	{
		$raw_url = is_string($raw_url) ? $raw_url : '';
		$resolved = esc_url_raw($raw_url);

		if ('' === $resolved) {
			$referer = wp_get_referer();
			if ($referer) {
				$resolved = esc_url_raw($referer);
			}
		}

		if ('' === $resolved) {
			$resolved = home_url('/');
		}

		return $resolved;
	}

	protected function prepare_verification_redirect($url, $status)
	{
		$safe_status = 'success' === $status ? 'success' : 'failed';
		$validated = wp_validate_redirect($url, home_url('/'));
		$clean = remove_query_arg('eurostocks_verification', $validated);
		return add_query_arg('eurostocks_verification', $safe_status, $clean);
	}

	protected function get_client_ip()
	{
		$options = Eurostocks_Anti_Spam_Settings::get_options();
		$use_cloudflare_ip = isset($options['use_cloudflare_ip']) && (int) $options['use_cloudflare_ip'] === 1;

		if ($use_cloudflare_ip && isset($_SERVER['HTTP_CF_CONNECTING_IP']) && $_SERVER['HTTP_CF_CONNECTING_IP'] !== '') {
			$ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CF_CONNECTING_IP']));
			if (!filter_var($ip, FILTER_VALIDATE_IP)) {
				// Invalid IP in header, fall back to REMOTE_ADDR if available
				if (isset($_SERVER['REMOTE_ADDR'])) {
					$ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
				} else {
					return '';
				}
			}
		} elseif (isset($_SERVER['REMOTE_ADDR'])) {
			$ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
		} else {
			return '';
		}

		if (strpos($ip, ':ffff:') !== false) {
			$ip = substr($ip, strrpos($ip, ':') + 1);
		}

		return $ip;
	}

	protected function generate_verification_token()
	{
		try {
			return bin2hex(random_bytes(16));
		} catch (\Exception $e) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCATCH
			error_log('Eurostocks_Public::generate_verification_token() - random_bytes() failed: ' . $e->getMessage());
		}

		return md5(uniqid('', true) . wp_generate_password(32, false));
	}

	public function eurostocks_replace_merk_model($string, $merk, $model)
	{
		$string = str_replace("{merk}", $merk, $string);
		$string = str_replace("{model}", $model, $string);
		return $string;
	}

	public function eurostocks_replace_merk_model_aantal($string, $merk, $model, $aantal)
	{
		$string = str_replace("{merk}", $merk, $string);
		$string = str_replace("{model}", $model, $string);
		$string = str_replace("{aantal}", $aantal, $string);
		return $string;
	}

	public function eurostocks_financial_lease($interest, $duration, $restschuld, $price)
	{
		$eurostocks_fl_rest_percentage = $restschuld / 100;
		$loanAmountRest = $price * $eurostocks_fl_rest_percentage;
		$paymentTotalAmount = $price - $loanAmountRest;
		$rate = $interest / 1200;
		$monthlyPayment = ($rate + $rate / (pow($rate + 1, $duration) - 1)) * $paymentTotalAmount;
		$monthlyPayment = number_format($monthlyPayment, 0, ',', '.');
		return $monthlyPayment;
	}

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

	private function eurostocks_should_log_ajax_errors()
	{
		return defined('WP_DEBUG_LOG') && WP_DEBUG_LOG;
	}

	private function eurostocks_log_models_ajax_error($message, $context = array())
	{
		if (!$this->eurostocks_should_log_ajax_errors()) {
			return;
		}

		$normalized_context = array();
		if (is_array($context)) {
			foreach ($context as $key => $value) {
				if (is_array($value)) {
					$normalized_context[sanitize_key($key)] = $this->eurostocks_sanitize_text_field_array($value);
				} else {
					$normalized_context[sanitize_key($key)] = sanitize_text_field((string) $value);
				}
			}
		}

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

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

	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 eurostocks_get_models_for_make()
	{
		$security = isset($_POST['security']) ? sanitize_text_field(wp_unslash($_POST['security'])) : '';
		if ('' !== $security && !wp_verify_nonce($security, 'eurostocks_nonce')) {
			// This endpoint is public and read-only. Cached pages can carry stale nonces,
			// so log invalid tokens for debugging but do not block the request.
			$this->eurostocks_log_models_ajax_error('Ignoring invalid nonce while requesting models.', array(
				'has_security' => 'yes',
			));
		}

		if (!isset($_POST['data-action'])) {
			$this->eurostocks_log_models_ajax_error('data-action missing while requesting models.');
			wp_send_json_error(
				array(
					'code'    => 'missing_action',
					'message' => __( 'Missing request action.', 'eurostocks' ),
				),
				400
			);
		}

		// check if make isset
		if (!isset($_POST['make'])) {
			$this->eurostocks_log_models_ajax_error('Make missing while requesting models.');
			wp_send_json_error(
				array(
					'code'    => 'missing_make',
					'message' => sanitize_text_field( __( 'Missing make.', 'eurostocks' ) ),
				),
				400
			);
		}

		$make_key = sanitize_text_field(wp_unslash($_POST['make']));

		if ('' === $make_key) {
			$this->eurostocks_log_models_ajax_error('Make missing while requesting models.');
			wp_send_json_error(
				array(
					'code'    => 'missing_make',
					'message' => __( 'Missing make.', 'eurostocks' ),
				),
				400
			);
		}

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

		if ( is_wp_error( $result ) ) {
			$code    = $result->get_error_code();
			$message = $result->get_error_message();
			$this->eurostocks_log_models_ajax_error('Model request returned WP_Error.', array(
				'make' => $make_key,
				'code' => $code,
				'message' => $message,
			));
			wp_send_json_error( array( 'code' => $code, 'message' => sanitize_text_field( $message ) ) );
		} elseif (is_array($result)) {
			wp_send_json_success( $this->eurostocks_sanitize_text_field_array( $result ) );
		} elseif (is_string($result) && '' !== $result) {
			$this->eurostocks_log_models_ajax_error('Model request returned an error string.', array(
				'make' => $make_key,
				'message' => $result,
			));
			wp_send_json_error( array( 'code' => 'error', 'message' => sanitize_text_field( $result ) ) );
		} else {
			$this->eurostocks_log_models_ajax_error('Model request returned an empty or unexpected result.', array(
				'make' => $make_key,
				'result_type' => gettype($result),
			));
			wp_send_json_error( array( 'code' => 'error', 'message' => sanitize_text_field( __( 'No models found', 'eurostocks' ) ) ) );
		}
	}

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


}
