<?php

namespace CarDealerPress\Includes\Functions;

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\helpers\helpers as helpers;
use CarDealerPress\Includes\Helpers\Option;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class Fn_Inventory {

	/**
	 * @var false|mixed|void
	 */
	public static $theme_options;
	/**
	 * @var false|mixed|void
	 */
	public static $admin_options;

	public $db_requests;
	public $safe;
	public function __construct() {
		// @codingStandardsIgnoreStart
		$this->safe = helpers::sanitize_get($_GET);
		// @codingStandardsIgnoreEnd

		$this->set_static_variables();
	}

	public function set_static_variables() {
		self::$theme_options = Option::get_cdp_theme_options();
		self::$admin_options = Option::get_cdp_admin_options();
		$this->db_requests   = new Requests();
	}


	public function cdp_get_banners( $page, $position, $banners, $params ) {
		$results      = array();
		$banner_index = null;
		$previous     = 0;
		$current_date = wp_date( 'Y-m-d', time() );
		foreach ( $banners as $key => $values ) {
			$current = 0;
			if ( ( empty( $values['page'] ) || $values['page'] === $page ) && $values['position'] === $position ) {
				$current ++;
				if ( $values['page'] === $page ) {
					$current ++;
				}
				if ( ( isset( $params['saleclass'] ) && strtolower( $params['saleclass'] ) === strtolower( $values['saleclass'] ) ) && 0 !== $current ) {
					$current ++;
				} elseif ( ! empty( $values['saleclass'] ) ) {
					$current = 0;
				}
				if ( ( isset( $params['vehicleclass'] ) && strtolower( $params['vehicleclass'] ) === strtolower( $values['vehicleclass'] ) ) && 0 !== $current ) {
					$current ++;
				} elseif ( ! empty( $values['vehicleclass'] ) ) {
					$current = 0;
				}
				if ( ( isset( $params['make'] ) && strtolower( $params['make'] ) === strtolower( $values['make'] ) ) && 0 !== $current ) {
					$current ++;
				} elseif ( ! empty( $values['make'] ) ) {
					$current = 0;
				}
				if ( ( isset( $params['model'] ) && strtolower( $params['model'] ) === strtolower( $values['model'] ) ) && 0 !== $current ) {
					$current ++;
				} elseif ( ! empty( $values['model'] ) ) {
					$current = 0;
				}
				if ( isset( $values['dealer'] ) ) {
					if ( ( isset( $params['dealer'] ) && 0 === strcmp( strtolower( $params['dealer'] ), strtolower( $values['dealer'] ) ) || 'all' === $values['dealer'] ) ) {
						$current ++;
					} elseif ( ! empty( $values['dealer'] ) ) {
						$current = 0;
					}
				}

				$current_date_time = strtotime( $current_date );
				$start_date_time   = strtotime( $values['startdate'] );
				$end_date_time     = strtotime( $values['enddate'] );

				if ( ( $current_date_time >= $start_date_time && $current_date_time <= $end_date_time )
					|| ( empty( $start_date_time ) && empty( $end_date_time ) )
				) {
					$current ++;
				} else {
					$current = 0;
				}

				if ( ( 0 === $previous || $current > $previous ) && 0 !== $current ) {
					$banner_index = $key;
					$previous     = $current;
				}
			}

			if ( is_numeric( $banner_index ) && 0 !== $previous ) {
				$results[] = "<div class='cdp-banner-$position cdp-banner-$page' >" . rawurldecode( stripslashes( $banners[ $banner_index ]['banner_data'] ) ) . '</div>';
			} else {
				$results[] = '';
			}
			$banner_index = null;
			$previous     = 0;
		}

		return $results;
	}

	public function cdp_limit_word_count( $text, $limit ) {
		if ( str_word_count( $text, 0 ) > $limit ) {
			$words = str_word_count( $text, 2 );
			$pos   = array_keys( $words );
			$text  = substr( $text, 0, $pos[ $limit ] ) . '...';
		}

		return $text;
	}

	public function cdp_get_db_dropdown_data( $key, $params ) {
		$results = array(
			'needle'    => '',
			'data'      => array(),
			'disable'   => 0,
			'dataCount' => array(),
		);
		$columns = ucfirst( $key ).', count(*) as Total';
		$param = $this->build_sql_conditions( $params );
		$group_by = $key;
		$order_by = $key;
		$db_data = $this->db_requests->cdp_inventory_special_request($columns, $param, $group_by, $order_by);

		if ( $db_data ) {
			foreach ( $db_data as $value ) {
				$data[]                              = $value[ ucfirst( $key ) ];
				$counts[ $value[ ucfirst( $key ) ] ] = $value['Total'];
			}
			$results['data']      = $data;
			$results['dataCount'] = $counts;
			if ( isset( $params[ $key ] ) && in_array( rawurldecode( $params[ $key ] ), $results['data'], true ) ) {
				$results['needle'] = $params[ $key ];
			} elseif ( 1 === count( $results['data'] ) ) {
				$params[ $key ] = $results['needle'] = $results['data'][0];
			} else {
				unset( $params[ $key ] );
			}
		}

		return $results;
	}

	function build_sql_conditions( $params ): string {
		$conditions = array();

		// Loop through the $params array
		foreach ( $params as $key => $value ) {
			// Only include non-empty values
			if ( ! empty( $value ) ) {
				// Escape the key and value for safety
				$escaped_key = esc_sql( $key );
				$escaped_value = esc_sql( $value );
				// Add the condition to the array
				$conditions[] = "$escaped_key = '$escaped_value'";
			}
		}

		// Join the conditions with " AND "
		return implode( ' AND ', $conditions );
	}


	public function cdp_construct_url( $params ) {
		$rules    = get_option( 'rewrite_rules' );
		$url_rule = isset( $rules['^(inventory)'] );
		if ( isset( $rules['^(inventory)'] ) ) {
			// Pretty URL.
			$pretty_url_parameters = array( 'saleclass', 'make', 'model' );
			$results               = '/inventory/';
			foreach ( $pretty_url_parameters as $value ) {
				$results .= isset( $params[ $value ] ) && $params[ $value ] ? rawurlencode( $params[ $value ] ) . '/' : '';
			}
			foreach ( $params as $key => $value ) {
				if ( $value ) {
					if ( ! in_array( $key, $pretty_url_parameters, true ) ) {
						$results = esc_url(add_query_arg( array( $key => rawurlencode( $value ) ), $results ));
					}
				}
			}
		} else {
			// Ugly URL.
			$results = esc_url(add_query_arg( array( 'taxonomy' => 'inventory' ) ));
			foreach ( $params as $key => $value ) {
				if ( $value ) {
					$results = esc_url(add_query_arg( array( $key => rawurlencode( $value ) ), $results ));
				}
			}
		}
		// Remove Unwanted Parameters.
		$results = esc_url(remove_query_arg( array( 'per_page', 'dealer_id', 'geo_search', 'manual_sort' ), $results ));

		return $results;
	}

	public function cdp_construct_parameter_update( $request = array(), &$params = array() ) {
		// Edge Cases.
		if ( isset( $request['saleclass'] ) || ! isset( $params['saleclass'] ) ) {
			if ( isset( $request['saleclass'] ) && 'certified' === $request['saleclass'] ) {
				$params['certified']  = 'Yes';
				$request['saleclass'] = 'Used';
			} else {
				unset( $params['certified'] );
			}
			unset( $params['make'] );
			unset( $params['model'] );
			unset( $params['trim'] );
		}
		if ( isset( $request['make'] ) || ! isset( $params['make'] ) ) {
			unset( $params['model'] );
			unset( $params['trim'] );
		}
		if ( isset( $request['model'] ) || ! isset( $params['model'] ) ) {
			unset( $params['trim'] );
		}
		if ( isset( $request['geo_state'] ) ) {
			unset( $params['geo_city'] );
			unset( $params['dealer'] );
		}
		if ( isset( $request['geo_city'] ) ) {
			unset( $params['dealer'] );
		}
	}

	public function cdp_hidden_vehicle_data( $vehicle, $type = 'id' ) {
		$content  = '<div ' . $type . '="vehicle-info-details" style="display: none;">';
		$content .= ( isset( $vehicle['vin'] ) ? '<span ' . $type . '="vehicle-vin">' . $vehicle['vin'] . '</span>' : '' );
		$content .= ( isset( $vehicle['stock'] ) ? '<span ' . $type . '="vehicle-stock">' . $vehicle['stock'] . '</span>' : '' );
		$content .= ( isset( $vehicle['year'] ) ? '<span ' . $type . '="vehicle-year">' . $vehicle['year'] . '</span>' : '' );
		$content .= ( isset( $vehicle['make'] ) ? '<span ' . $type . '="vehicle-make">' . $vehicle['make'] . '</span>' : '' );
		$content .= ( isset( $vehicle['model'] ) ? '<span ' . $type . '="vehicle-model">' . $vehicle['model'] . '</span>' : '' );
		$content .= ( isset( $vehicle['trim'] ) ? '<span ' . $type . '="vehicle-trim">' . $vehicle['trim'] . '</span>' : '' );
		$content .= ( isset( $vehicle['primary_price'] ) ? '<span ' . $type . '="vehicle-price">' . $vehicle['primary_price'] . '</span>' : '' );
		$content .= ( isset( $vehicle['contact_info']['dealer_id'] ) ? '<span ' . $type . '="vehicle-dealer-id">' . $vehicle['contact_info']['dealer_id'] . '</span>' : '' );
		$content .= ( isset( $vehicle['contact_info']['dealer'] ) ? '<span ' . $type . '="vehicle-dealer-name">' . $vehicle['contact_info']['dealer'] . '</span>' : '' );
		$content .= ( isset( $vehicle['contact_info']['phone'] ) ? '<span ' . $type . '="vehicle-dealer-phone">' . $vehicle['contact_info']['phone'] . '</span>' : '' );
		$content .= ( isset( $vehicle['contact_info']['location'] ) ? '<span ' . $type . '="vehicle-dealer-address">' . $vehicle['contact_info']['location'] . '</span>' : '' );
		$content .= '</div>';

		return $content;
	}

	public function display_breadcrumb( $parameters, $company, $override, $sc = '' ) {

		if ( ! empty( $sc ) ) {
			unset( $parameters['saleclass'] );
			$array_jump = array( 'saleclass' => $sc );
			$parameters = $array_jump + $parameters;
		} else {
			$array_jump = array( 'saleclass' => $parameters['saleclass'] );
			unset( $parameters['saleclass'] );
			$parameters = $array_jump + $parameters;
		}

		$company_name = ( ! empty( $override['contact_name'][ strtolower( $parameters['saleclass'] ) ] ) ) ? $override['contact_name'][ strtolower( $parameters['saleclass'] ) ] : $company['name'];
		$company_name = empty( $override['breadcrumb'] ) ? $company_name : $override['breadcrumb'];

		$breadcrumb = '<a href="' . site_url() . '/" title="' . $company_name . ': Home Page">' . ucwords( strtolower( urldecode( $company_name ) ) ) . '</a>';

		$put_in_trail = array( 'saleclass', 'make', 'model', 'trim' );
		if ( 'vin' === self::$admin_options['admin']['general']['vdp_url_identifier'] ) {
			$put_in_trail[] = 'vin';
		} else {
			$put_in_trail[] = 'id';
		}

		unset( $parameters['taxonomy'] );

		$rules       = get_option( 'rewrite_rules' );
		$crumb_trail = isset( $rules['^(inventory)'] ) ? '/inventory/' : '?taxonomy=inventory';

		foreach ( $parameters as $key => $value ) {
			if ( in_array( $key, $put_in_trail, true ) ) {
				if ( isset( $rules['^(inventory)'] ) ) {
					if ( 'trim' === $key && 'all' !== $value ) {
						$crumb_trail = esc_url(add_query_arg( array( $key => $value ), $crumb_trail ));
						$breadcrumb .= ' <span>&gt;</span> <a href=' . ( 'vin' !== $key || 'id' !== $key ? $crumb_trail : '' ) . '>' . ucfirst( urldecode( $value ) ) . '</a>';
					} elseif ( 'trim' !== $key && 'all' !== $value ) {
						$crumb_trail .= rawurlencode( urldecode( $value ) ) . '/';
						$breadcrumb  .= ' <span>&gt;</span> <a href=' . ( 'vin' !== $key || 'id' !== $key ? $crumb_trail : '' ) . '>' . ucfirst( urldecode( $value ) ) . '</a>';
					}
				} else {
					$crumb_trail = esc_url(add_query_arg( array( $key => $value ), $crumb_trail ));
					$breadcrumb .= ' <span>&gt;</span> <a href=' . ( 'vin' !== $key || 'id' !== $key ? $crumb_trail : '' ) . '>' . ucfirst( urldecode( $value ) ) . '</a>';
				}
			}
		}

		return $breadcrumb;
	}

	public function get_custom_contact_setting( $saleclass, $dealer_id, $setting ) {
		$company    = $this->db_requests->cdp_company_dealer_request( $dealer_id )[0];
		$field_data = self::$theme_options['theme']['overrides']['custom_contact'][ $setting ][ strtolower( $saleclass ) ];

		return empty( $field_data ) ? $company[ $setting ] : $field_data;
	}

	public function get_dealer_contact_info( $args ) {
		$override  = self::$theme_options['theme']['overrides']['custom_contact'] ?? '';
		$vehicle   = $args['vehicle'] ?? array();
		$company   = $this->db_requests->cdp_company_dealer_request( $vehicle['dealer_id'] )[0];
		$saleclass = $vehicle['saleclass'];

		$contact      = array(
			'dealer_id'   => $vehicle['dealer_id'],
			'greeting'    => 'For More Information', // TODO need to add an option.
			'dealer_name' => $company['name'],
			'phone'       => $company['phone'],
		);
		$phone_num    = $this->get_custom_contact_setting( $saleclass, $vehicle['dealer_id'], 'phone' );
		$company_name = $this->get_custom_contact_setting( $saleclass, $vehicle['dealer_id'], 'name' );

		$dealer_street = $company['street'];
		$dealer_city   = $company['city'];
		$dealer_state  = $company['state'];
		$dealer_zip    = $company['zip'];

		$results = '<div class="dealer-contact-wrapper">';
		if ( self::$theme_options['theme']['inventory_display']['list']['general']['display_dealer_name'] ) {
			$results .= '<span class="dealer-name form-value" data-name="dealer" itemprop="name" style="padding-right:5px;">' . $company_name . '</span><span> </span>';
		}
		if ( self::$theme_options['theme']['inventory_display']['list']['general']['display_dealer_phone'] ) {
			$results .= '<span class="dealer-number form-value" data-name="phone" itemprop="telephone"><a href="tel:' . $phone_num . '">' . $phone_num . '</a></span>';
		}
		if ( 'full' === self::$theme_options['theme']['inventory_display']['list']['general']['display_address_options'] ) {
			$results .= "<div class='vehicle-street' itemprop='address'>$dealer_street $dealer_city, $dealer_state. $dealer_zip</div>";
		}
		if ( 'city_state' === self::$theme_options['theme']['inventory_display']['list']['general']['display_address_options'] ) {
			$results .= "<div class='vehicle-city-state' itemprop='address'>$dealer_city, $dealer_state.</div>";
		}

		$results .= '<span class="dealer-id form-value" data-name="dealer_id" style="display:none;">' . $contact['dealer_id'] . '</span>' . $this->get_automall_email( $contact['dealer_id'], $saleclass );
		$results .= '</div>';

		return $results;
	}

	public function get_automall_email( $dealer_id, $vehicle_saleclass = 'new', $val_only = false ) {
		$content       = '';
		$dealer_emails = self::$theme_options['theme']['automall_emails']['dealers'] ?? array();
		$default_email = self::$theme_options['theme']['automall_emails']['defaults'][ strtolower( $vehicle_saleclass ) ];
		foreach ( $dealer_emails as $value ) {
			if ( $value['id'] === $dealer_id ) {
				$email_saleclass = 'new' === $value['saleclass'] ? 'new' : 'used';
				if ( 'all' === $value['saleclass'] || ( strtolower( $vehicle_saleclass ) === $email_saleclass ) ) {
					if ( $val_only ) {
						$content = $value['email'];
					} else {
						$content = '<span class="automall-email-value form-value" data-name="automall_email" style="display: none;">' . $value['email'] . '</span>';
					}
				}
			}
		}
		if ( empty( $content ) && $default_email ) {
			if ( $val_only ) {
				$content = $default_email;
			} else {
				$content = '<span class="automall-email-value form-value" data-name="automall_email" style="display: none;">' . $default_email . '</span>';
			}
		}

		return $content;
	}

	public function get_automall_email_adf( $dealer_id, $vehicle_saleclass = 'used' ) {
		$dealer_emails = self::$theme_options['theme']['automall_emails']['dealers'] ?? array();
		foreach ( $dealer_emails as $value ) {
			if ( $value['id'] === $dealer_id ) {
				$email_saleclass = 'new' === $value['saleclass'] ? 'new' : 'used';
				if ( 'all' === $value['saleclass'] || ( strtolower( $vehicle_saleclass ) === $email_saleclass ) ) {
					return $value['is_adf'] ?? 'no';
				}
			}
		}

		return 'no';
	}

	public function get_prices( $vehicle ) {
		$saleclass = strtolower( $vehicle['saleclass'] );

		$msrp             = intval( $vehicle['msrp'] ?? 0 );
		$retail_price     = intval( $vehicle['retailprice'] );
		$asking_price     = intval( $vehicle['askingprice'] );
		$sale_price       = intval( $vehicle['saleprice'] );
		$diff_asking_sale = $asking_price - $sale_price;
		$lowest_price     = $retail_price;
		if ( $asking_price > 0 && empty( $sale_price ) ) {
			$lowest_price = $asking_price;
		}
		if ( $diff_asking_sale >= 0 && $sale_price > 0 ) {
			$lowest_price = $sale_price;
		}
		$prices = array(
			'was_now'        => self::$theme_options['theme']['inventory_display']['prices']['display']['was_now'],
			'strike_through' => self::$theme_options['theme']['inventory_display']['prices']['display']['strike_through'],
			'show_used'      => self::$theme_options['theme']['inventory_display']['prices']['display']['show_used'],
			'show_new'       => self::$theme_options['theme']['inventory_display']['prices']['display']['show_new'],
			'on_sale'        => $diff_asking_sale >= 0 && $sale_price > 0,
			'asking_price'   => $asking_price,
			'sale_price'     => $sale_price,
			'sale_expire'    => $vehicle['sale_expire'] ?? '',
			'retail_price'   => $retail_price,
			'msrp'           => $msrp,
			'main_price'     => $lowest_price,
			'call_for_price' => self::$theme_options['theme']['inventory_display']['prices']['text'][ $saleclass ]['call_for_price'],
		);

		return $prices;
	}

	public function get_price_display( $args ) {

		$company      = $args['company'] ?? array();
		$vehicle      = $args['vehicle'];
		$saleclass    = strtolower( $vehicle['saleclass'] );
		$vin          = $vehicle['vin'];
		$theme        = $args['theme'] ?? 'custom';
		$custom_price_text = self::$theme_options['theme']['inventory_display']['prices']['text'][ $saleclass ] ?? array();

		$price = array(
			'was_now'        => self::$theme_options['theme']['inventory_display']['prices']['display']['was_now'],
			'strike_through' => self::$theme_options['theme']['inventory_display']['prices']['display']['strike_through'],
			'show_used'      => self::$theme_options['theme']['inventory_display']['prices']['display']['show_used'],
			'show_new'       => self::$theme_options['theme']['inventory_display']['prices']['display']['show_new'],
			'on_sale'        => $vehicle['saleprice'] < $vehicle['askingprice'],
			'asking_price'   => $vehicle['askingprice'],
			'sale_price'     => $vehicle['saleprice'],
			'sale_expire'    => $vehicle['sale_expire'],
			'retail_price'   => $vehicle['retailprice'],
			'msrp'           => $vehicle['msrp'],
			'call_for_price' => self::$theme_options['theme']['inventory_display']['prices']['text'][ $saleclass ]['call_for_price'],
		);
		$diff_asking_sale = intval( $price['asking_price'] ) - intval( $price['sale_price'] );

		$text_display_text = '';
		$text_msrp = ( ! empty( $custom_price_text['msrp'] ) ) ? $custom_price_text['msrp'] . ' ' : 'MSRP ';
		$text_standard  = ( ! empty( $custom_price_text['price'] ) ) ? $custom_price_text['price'] . ' ' : 'Price ';

		if ( 0 < $diff_asking_sale && 0 < intval( $price['sale_price'] )) {
			$default_asking_price = 'Compare At ';
		} else {
			$default_asking_price = 'Price ';

		}
		$text_compare = ( ! empty( $custom_price_text['compare_price'] ) ) ? $custom_price_text['compare_price'] . ' ' : $default_asking_price;

		$text_sale      = ( ! empty( $custom_price_text['sale_price'] ) ) ? $custom_price_text['sale_price'] . ' ' : 'Sale Price ';
		$text_discount  = ( ! empty( $custom_price_text['discount'] ) ) ? $custom_price_text['discount'] . ' ' : 'Discount ';
		$call_for_price = ( ! empty( $custom_price_text['call_for_price'] ) ) ? $custom_price_text['call_for_price'] . ' ' : 'Call For Price';
		$strike         = ( 'on' === $price['strike_through'] ) ? $theme . '-strike-through ' : '';

		$data                  = array();
		$data['on_sale']       = $price['on_sale'];
		$data['primary_price'] = 0;

		$data['msrp_text'] = '';
		$data['compare_price_text'] = '';
		$data['expire_text']  = ( ! empty( $price['sale_expire'] ) ) ? "<div class='$theme-sale-expires'>Sale Expires: $price[sale_expire]</div>" : '';
		$currency = 'USD';
		if ('CA' === $company['country_code']){
			$currency = 'CAD';
		}

		$asking_price_class = $theme . '-asking-price';
		$sale_price_class = $theme . '-sale-price';
		$no_price_class = $theme . '-no-price';
		if ( 'on' === $price['show_used'] && 'used' === $saleclass || 'on' === $price['show_new'] && 'new' === $saleclass ) {
			if ( $this->check_for_prices( $price ) ) {
				$price_class                = ! empty( $strike ) ? $strike . $asking_price_class : $asking_price_class;
				$data['msrp_text']          .= $this->create_price_text( array(
					'class'    => "$price_class $theme-msrp price-text-value-container",
					'text'     => $text_msrp,
					'currency' => $currency,
					'price'    => $price['msrp']
				) );
				$data['compare_price_text'] = $this->create_price_text( array(
					'class'    => "$price_class $theme-compare-price price-text-value-container",
					'text'     => $text_compare,
					'currency' => $currency,
					'price'    => $price['asking_price']
				) );
				$data['discount_text']      = ( 0 < $diff_asking_sale && 0 < intval( $price['sale_price'] ) ? $this->create_price_text( array(
					'class'    => "$theme-discount-price price-text-value-container",
					'text'     => $text_discount,
					'currency' => $currency,
					'price'    => $diff_asking_sale
				) ) : '' );
				$data['sale_price_text']    = $this->create_price_text( array(
					'class'    => "$sale_price_class $theme-sale-price price-text-value-container",
					'text'     => $text_sale,
					'currency' => $currency,
					'price'    => $price['sale_price']
				) );
				$primary_price = $this->get_primary_price( $price );
				$data['primary_text']    = $this->create_price_text( array(
					'class'    => "$theme-main-price price-text-value-container",
					'text'     => $text_sale,
					'currency' => $currency,
					'price'    => $primary_price,
				) );
				$data['primary_price'] = $primary_price;
			} else {
				$data['call_for_price_text'] = '<div class="' . $no_price_class . '"><span class="text default">' . $call_for_price . '</span></div>';
				$data['primary_text'] = '<div class="' . $no_price_class . '"><span class="text default">' . $call_for_price . '</span></div>';
				$data['no_price']            = true;
			}
		} else {
			$data['call_for_price_text'] = '<div class="' . $no_price_class . '"><span class="text default">' . $call_for_price . '</span></div>';
			$data['primary_text'] = '<div class="' . $no_price_class . '"><span class="text default">' . $call_for_price . '</span></div>';
			$data['no_price']     = true;
		}

		// Clean Price Values.
		$has_discount = $price['sale_price'] > 0 && 0 !== ( $price['asking_price'] - $price['sale_price']);
		$discount = $price['asking_price'] - $price['sale_price'];
		$data['hidden_prices'] = "<div class='hidden-vehicle-prices' style='display:none;'>";
		$data['hidden_prices'] .= "<div class='hidden-msrp form-value' data-name='msrp'>$price[msrp]</div>";
		$data['hidden_prices'] .= "<div class='hidden-retail form-value' data-name='retail'>$price[retail_price]</div>";
		$data['hidden_prices'] .= "<div class='hidden-asking form-value' data-name='asking'>$price[asking_price]</div>";
		$data['hidden_prices'] .= $has_discount ? "<div class='hidden-discount' data-name='discount'>$discount</div>" : "";
		$data['hidden_prices'] .= "<div class='hidden-sale form-value' data-name='sale'>$price[sale_price]</div>";
		$data['hidden_prices'] .= "<div class='hidden-main form-value vehicle-save' data-name='price'>$data[primary_price]</div>";
		$data['hidden_prices'] .= "</div>";

		return $data;
	}

	public function check_for_prices( $price ) {
		if ( 0 < intval($price['msrp']) || 0 < intval($price['asking_price']) || 0 < intval($price['sale_price']) ) {
			return true;
		} else {
			return false;
		}
	}

	public function get_primary_price( $price ) {
		switch ( true ) {
			case 0 < intval($price['msrp']) && 0 === intval($price['asking_price']) && 0 == intval($price['sale_price']):
				$primary_price = $price['msrp'];
				break;
			case 0 < intval( $price['asking_price'] ) && ( 0 === intval( $price['sale_price'] || intval($price['asking_price']) === intval($price['sale_price']) ) ):
				$primary_price = $price['asking_price'];
				break;
			case 0 < intval($price['sale_price']) && ( intval($price['sale_price']) <= intval($price['asking_price']) ):
				$primary_price = $price['sale_price'];
				break;
			default:
				$primary_price = 0;
		}

		return $primary_price;
	}

	public function create_price_text($args){
		$price_class = $args['class'] ?? '';
		$text = $args['text'] ?? '';
		$currency= $args['currency'] ?? '';
		$price= $args['price'] ?? '';
		$formatted_price = $this->price_format( $price );
		if ( 0 < intval( $price ) ) {
			$content = "<div class='$price_class'>";
			$content .= "<span class='text'>$text</span>";
			$content .= "<span class='value'> <span itemprop='priceCurrency' content='$currency'>$</span>";
			$content .= "<span itemprop='price' content='$price'>$formatted_price</span></span>";
			$content .= "</div>";
		} else {
			$content = '';
		}

		return $content;
	}

	public function price_format($price){
		$decimal = Option::check_for_option('cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'prices',
				'display',
				'show_decimals',
			),0);
		if ('on' === $decimal){
			$decimal = 2;
		}
		return number_format( $price, $decimal, '.', ',' );
	}

	public function no_photo_replace( &$image ) {
		// extender_no_image_replace.

		if ( ( empty( $image ) || strstr( $image, '_no_photo' ) ) ) {
			$image = CDP_IMG . 'templates/inventory/detail_no_photo.png';
		}

		if ( ( empty( $image ) || strstr( $image, '_no_photo' ) ) && ! empty( self::$theme_options['theme']['overrides']['default_no_image'] ) ) {
			$image = self::$theme_options['theme']['overrides']['default_no_image'];
		}

		return $image;
	}

	public function get_photo_detail_display( $vehicle, $default_active, $flex = '' ) {
		$photos    = $vehicle['photos_raw']; // TODO future fix photos in db, pull in all original photos.
		$video     = $vehicle['video'];
		$flex_item = $flex ? 'style="flex: 1 1 auto; margin: 0; text-align: center;" ' : '';

		if (empty($vehicle['photos_raw'])){
			$photos[] = ! empty( $vehicle['sold_on'] ) ? (object) array( "medium" =>  CDP_IMG . 'templates/inventory/sold_overlay.png' ) : array();
			$photos[] = isset( $vehicle['image_medium'] ) ? (object) array( "medium" => $vehicle['image_medium'] ) : array();
		}

		$class         = ( 'video' === strtolower( $default_active ) ) ? array( 'active', '' ) : array( '', 'active' );
		$content_video = '';

		if ( $video ) {
			$buttons       = '<div ' . $flex_item . ' class="tabs-button tabs-button-img-photo ' . $class[1] . '" data-name="img-photo">Photos</div><div ' . $flex_item . ' class="tabs-button tabs-button-img-video ' . $class[0] . '" data-name="img-video">Video</div>';
			$content_video = '<div class="tabs-content tabs-content-img-video ' . $class[0] . '">';
			$mime          = wp_check_filetype( $video, wp_get_mime_types() );
			if ( empty( $mime['ext'] ) || strpos( $mime['type'], 'video' ) === false ) {
				if ( strpos( $video, 'dmotorworks' ) !== false || strpos( $video, 'idostream' ) !== false || strpos( $video, 'liveVideo' ) !== false || strpos( $video, 'vehicledata' ) !== false || strpos( $video, 'dealervideos' ) !== false || strpos( $video, 'flickfusion' ) !== false ) {
					$content_video .= '<div id="video-overlay-wrapper-dm" onclick=\'window.open("' . $video . '","popup","width=640,height=500,scrollbars=no,resizable=yes,toolbar=no,directories=no,location=no,menubar=yes,status=no,left=50,top=125"); return false\'>';
					// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
					$content_video .= '<img id="video-overlay-play-button" src="' . CDP_IMG . 'templates/inventory/video_play_button.png" />';
					// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
					$content_video .= '<img id="video-overlay-image" src="' . $photos[0]->medium . '" />';
					$content_video .= '</div>';
				} else {
					$content_video .= '<div id="inventory-video-wrapper">';
					// currently only works for youtube videos.
					preg_match( '/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/', $video, $matches );
					if ( isset( $matches[0] ) ) {
						$content_video .= '<iframe id="inventory-video-iframe" src="https://www.youtube.com/embed/' . $matches[0] . '?feature=player_detailpage" allowfullscreen></iframe>';
					}
					$content_video .= '</div>';

				}
			} else {
				$content_video .= '<div id="video-overlay-wrapper">';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content_video .= '<img id="video-overlay-play-button" src="' . CDP_IMG . 'templates/inventory/video_play_button.png" />';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content_video .= '<img id="video-overlay-image" src="' . $photos[0]->medium . '" />';
				$content_video .= '</div>';
				$content_video .= '<div id="wp-video-shortcode-wrapper">';
				$content_video .= wp_video_shortcode(
					array(
						'src'    => $video,
						'height' => 360,
						'width'  => 640,
					)
				);
				$content_video .= '</div>';
			}
			$content_video .= '</div>';
		} else {
			$buttons  = '<div ' . $flex_item . ' class="tabs-button tabs-button-img-photo active" data-name="img-photo">Photos</div>';
			$class[1] = 'active';
		}

		$content_photos = '<div class="tabs-content tabs-content-img-photo ' . $class[1] . '"><div id="vehicle-images">';
		$i              = 0;
		if (empty($vehicle['photos_raw'])){
			// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
			$sold_overlay = ! empty( $vehicle['sold_on'] ) ? '<img class="marked-sold-overlay" src="' . CDP_IMG . 'templates/inventory/sold_overlay.png" />' : '';
			// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
			$content_photos .= ( isset( $vehicle['image_medium'] ) ? $sold_overlay.'<img class="vehicle-image" src="' . $vehicle['image_medium'] . ' " alt="slide-image"/>' : '' );
		} else {
			foreach ( $photos as $image ) {
				$photo = $this->no_photo_replace( $image->large );
				$alt            = $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'];
				$content_photos .= '<a class="lightbox" data-lightbox="vehicle-lightbox" rel="slides" href="' . str_replace( '&', '&amp;', $photo ) . '">';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content_photos .= '<img src="' . str_replace( '&', '&amp;', $photo ) . '"  alt="image-' . $i . ' ' . $alt . '"/></a>';
				$i ++;
			}
		}
		$content_photos .= '</div><div id="vehicle-thumbnails"></div></div>';

		$display = '<div id="photo-tabs-wrapper">';

		$display .= '<div id="photo-tabs-buttons" ' . $flex . '>';
		$display .= $buttons;
		$display .= '</div>';

		$display .= '<div id="photo-tabs-content">';
		$display .= $content_photos;
		$display .= $content_video;
		$display .= '</div>';

		$display .= '</div>';

		return $display;
	}

	public function get_fuel_economy_display( $fuel, $country, $img_id = 0, $value_only = false ) {
		$city    = ! empty( $fuel ) && ! empty( $fuel['city'] ) ? $fuel['city'] : 0;
		$highway = ! empty( $fuel ) && ! empty( $fuel['highway'] ) ? $fuel['highway'] : 0;

		switch ( $img_id ) {
			case 0:
				$img_name = 'mpg_39x52.png';
				break;
			case 1:
				$img_name = 'mpg_s_39x52.png';
				break;
			case 2:
				$img_name = 'mpg_green_44x65.png';
				break;
		}

		// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
		$img_link  = '<img src="' . CDP_IMG . 'templates/inventory/' . $img_name . '" name="fuel-economy" />';
		$fuel_text = $value_only ? array() : '';

		if ( $value_only ) {
			$fuel_text = array(
				'city' => $city,
				'hwy'  => $highway,
			);
		}

		if ( ! empty( $city ) && ! empty( $highway ) && empty( $fuel_text ) ) {
			$fuel_text = '<div id="fuel-economy-wrapper"><div id="fuel-city"><span id="city-text">City</span><span id="city-value">' . $city . '</span></div><div id="fuel-image">' . $img_link . '</div><div id="fuel-highway"><span id="highway-text">Hwy</span><span id="highway-value">' . $highway . '</span></div><p id="fuel-disclaimer">Actual mileage will vary with options, driving conditions, driving habits and vehicle&#39;s condition.</p></div>';
		}

		return $fuel_text;

	}

	public function get_gform_button_display( $forms, $saleclass = 'All', $override = false ) {
		$ids = array();
		switch ( strtolower( $saleclass ) ) {
			case 'new':
				$sc = 1;
				break;
			case 'used':
				$sc = 2;
				break;
			default:
				$sc = 0;
		}
		$results = '<div id="form-button-wrapper">';
		foreach ( $forms as $key => $form ) {
			if ( 0 === intval( $form['saleclass'] ) || $form['saleclass'] === $sc ) {
				$ids[]    = $form['id'];
				$results .= '<div id="form-button-' . $form['id'] . '" class="form-button form-' . $form['id'] . '" data-name="form-id-' . $form['id'] . '">' . $form['title'] . '</div>';
			}
		}
		if ( ! empty( $ids ) ) {
			$results .= '<div id="form-data">';
			foreach ( $ids as $id ) {
				$results .= '<div id="form-id-' . $id . '" class="form-wrap">' . do_shortcode( '[gravityform id=' . $id . ' title=true description=false]' ) . '</div>';
			}
			$results .= '</div>';
		}

		$results .= '</div>';

		return $results;
	}

	public function get_form_display( $forms, $saleclass = 'All' ) {

		switch ( strtolower( $saleclass ) ) {
			case 'new':
				$sc = 1;
				break;
			case 'used':
				$sc = 2;
				break;
			default:
				$sc = 0;
		}

		foreach ( $forms as $key => $form ) {
			if ( empty( $form['button'] ) && ( 0 === intval( $form['saleclass'] ) || $form['saleclass'] === $sc ) ) {
				$content = "<div class='form-wrapper'>";
				$content .= "<div id='form-id-$form[id]' class='form-display-wrap form-$form[id]' data-name='form-id-$form[id]'>";
				$content .= gravity_form( $form['id'], true );
				$content .= '</div>';
				$content .= '</div>';
				helpers::output_wp_kses( $content);

			}
		}

	}

	public function get_loan_calculator( $loan_data, $price, $button = true, $params = array() ) {
		$display = '';

		// Get Loan Values.
		if ( isset( $params['saleclass'] ) ) {
			$loan = $loan_data[ strtolower( $params['saleclass'] ) ]['default'];
			$this->get_custom_loan( $loan_data['custom'], $loan, $params );
		}

		$calculate = $loan['display_calc'] ?? '';
		if ( ! empty( $calculate ) ) {
			if ( is_numeric( $price ) && 0 !== $price ) {
				$down    = ( $loan['down_percent'] ? round( $price * ( $loan['down'] / 100 ) ) : $loan['down'] );
				$display = '<div id="loan-calculator-wrapper">';

				$display .= ( $button ) ? '<div id="loan-calculator-button">Payment Calculator</div>' : '';

				$display .= '<div id="loan-calculator-data">';
				$display .= '<div id="loan-calculator">';
				$display .= '<div class="loan-value"><label>Vehicle Price</label><input type="text" id="loan-calculator-price" value="$' . ( is_numeric( $price ) ? $this->price_format( $price ) : '0' ) . '" /></div>';
				$display .= '<div class="loan-value"><label>Interest Rate</label><input type="text" id="loan-calculator-interest-rate" value="' . $loan['interest'] . '%" /></div>';
				$display .= '<div class="loan-value"><label>Trade-in Value</label><input type="text" id="loan-calculator-trade-in-value" value="$' . $this->price_format( $loan['trade'] ) . '" /></div>';
				$display .= '<div class="loan-value"><label>Term (months)</label><input type="text" id="loan-calculator-term" value="' . $loan['term'] . '" /></div>';
				$display .= '<div class="loan-value"><label>Down Payment</label><input type="text" id="loan-calculator-down-payment" value="$' . $this->price_format( $down ) . '" /></div>';
				$display .= '<div class="loan-value"><label>Sales Tax</label><input type="text" id="loan-calculator-sales-tax" value="' . $loan['tax'] . '%" /></div>';

				$display .= '<hr>';

				$display .= ( $loan['display_bi_monthly'] ) ? '<div class="loan-payment"><label>Bi Monthly Cost</label><div id="loan-calculator-bi-monthly-cost"></div></div>' : '';
				$display .= ( $loan['display_monthly'] ) ? '<div class="loan-payment"><label>Monthly Cost</label><div id="loan-calculator-monthly-cost"></div></div>' : '';

				$display .= ( $loan['display_total_cost'] ) ? '<div class="loan-total"><label>Total Cost<br><small>(including taxes)</small></label><div id="loan-calculator-total-cost"></div></div>' : '';

				$display .= '<div id="loan-calculator-submit"><button>Re-Calculate</button></div>';

				$display .= '</div></div>';

				$display .= '</div>';
			} else {
				$display = '<div id="loan-calculator-error">No price is currently available to calculate. Please contact dealer for price information.</div>';
			}
		}

		return $display;
	}

	public function get_loan_value( $loan_data, $price, $params = array() ) {
		$display = '';
		// Get Loan Values.
		if ( isset( $params['saleclass'] ) ) {
			$loan = $loan_data[ strtolower( $params['saleclass'] ) ]['default'];
			$this->get_custom_loan( $loan_data['custom'], $loan, $params );
		}
		$calculate = $loan['display_payment'] ?? '';
		if ( ! empty( $calculate ) && is_numeric( $price ) && $price !== 0 ) {
			// Extract numeric values from loan parameters
			$number_pattern = '/[^0-9\.]/';
			$interest       = (float) preg_replace( $number_pattern, '', $loan['interest'] );
			$term           = (float) preg_replace( $number_pattern, '', $loan['term'] );
			$trade          = (float) preg_replace( $number_pattern, '', $loan['trade'] );
			$down           = (float) preg_replace( $number_pattern, '', $loan['down'] );
			$tax            = (float) preg_replace( $number_pattern, '', $loan['tax'] );

			// Calculate down payment (as percentage if specified)
			if ( $loan['down_percent'] ) {
				$down = round( ( $price * ( $down / 100 ) ) );
			}

			// Calculate total price after trade-in, down payment, and tax
			$total_price = ( $price - $trade - $down );
			$total_price += $total_price * ( $tax / 100 );

			// Calculate monthly payment
			if ( $interest > 0 ) {
				$monthly_rate    = $interest / 1200; // Convert annual % to monthly decimal
				$monthly_payment = $monthly_rate * $total_price / ( 1 - pow( 1 + $monthly_rate, - $term ) );
			} else {
				$monthly_payment = $total_price / $term;
			}
			$display_text = str_replace( '[payment]', '<strong class="loan-payment-value">' . $this->price_format( round( $monthly_payment ) ) . '</strong>', $loan['display_text'] );
			$display_text = str_replace( '[term]', $loan['term'], $display_text );
			$display_text = str_replace( '[trade]', $loan['trade'], $display_text );
			$display_text = str_replace( '[down_value]', $down, $display_text );
			$display_text = str_replace( '[down]', $loan['down'], $display_text );
			$display_text = str_replace( '[interest]', $loan['interest'], $display_text );

			$disclaimer_text = str_replace( '[payment]', '<strong>' . $this->price_format( round( $monthly_payment ) ) . '</strong>', $loan['disclaimer'] );
			$disclaimer_text = str_replace( '[term]', $loan['term'], $disclaimer_text );
			$disclaimer_text = str_replace( '[trade]', $loan['trade'], $disclaimer_text );
			$disclaimer_text = str_replace( '[down_value]', $down, $disclaimer_text );
			$disclaimer_text = str_replace( '[down]', $loan['down'], $disclaimer_text );
			$disclaimer_text = str_replace( '[interest]', $loan['interest'], $disclaimer_text );

			$display .= '<div class="loan-payment-wrapper">';
			$display .= $display_text;
			$display .= ( ! empty( $loan['disclaimer'] ) ? '<span class="loan-disclaimer-icon tooltip-icon"><span class="tooltip" style="display: none;">' . $disclaimer_text . '</span></span>' : '' );
			$display .= '</div>';
		}

		return $display;
	}

	public function get_custom_loan( $custom, &$default, $params ) {
		if ( ! empty( $custom ) ) {
			$param_saleclass = 'new' === strtolower( $params['saleclass'] ) ? 1 : ( 'used' === strtolower( $params['saleclass'] ) ? 2 : 0 );
			foreach ( $custom as $key => $loan ) {
				$check_saleclass = 'all' === $loan['saleclass'] || $loan['saleclass'] === $param_saleclass;
				$check_make      = empty( $loan['make'] ) || strtolower( $loan['make'] ) === strtolower( $params['make'] );
				$check_model     = empty( $loan['model'] ) || strtolower( $loan['model'] ) === strtolower( $params['model'] );
				$check_trim      = empty( $loan['trim'] ) || strtolower( $loan['trim'] ) === strtolower( $params['trim'] );
				switch ( $loan['year_qualifier'] ) {
					case 'equal':
						$year_qualifier = '==';
						break;
					case 'less than':
						$year_qualifier = '<';
						break;
					case 'greater than':
						$year_qualifier = '>';
						break;
				}
				$check_year = empty( $loan['year'] ) || ( $params['year'] . $year_qualifier . $loan['year'] );
				if ( $check_make && $check_saleclass && $check_model && $check_trim && $check_year ) {
					foreach ( $loan as $id => $value ) {
						if ( ! empty( $value ) && isset( $default[ $id ] ) ) {
							$default[ $id ] = $value;
						}
					}
				}
			}
		}
	}

	public function get_payment( $loan_data, $price, $params = array() ) {
		$payment = '';
		if ( isset( $params['saleclass'] ) ) {
			$loan = $loan_data[ strtolower( $params['saleclass'] ) ]['default'];
			$this->get_custom_loan( $loan_data['custom'], $loan, $params );
		}
		$calculate = $loan['display_payment'] ?? '';
		if ( ! empty( $calculate ) ) {
			if ( is_numeric( $price ) && 0 !== $price ) {
				$number_pattern = '/[^0-9\.]/';
				$interest       = preg_replace( $number_pattern, '', $loan['interest'] );
				$term           = preg_replace( $number_pattern, '', $loan['term'] );
				$trade          = preg_replace( $number_pattern, '', $loan['trade'] );
				$down           = preg_replace( $number_pattern, '', $loan['down'] );
				$tax            = preg_replace( $number_pattern, '', $loan['tax'] );
				if ( $loan['down_percent'] ) {
					$down = round( $price * ( $down / 100 ) );
				}
				$total_price = ( ( $price - $trade ) - $down );
				$total_price += $total_price * ( $tax / 100 );

				if ( $interest > 0 ) {
					$interest        /= 1200;
					$payment = $interest * $total_price / ( 1 - pow( 1 + $interest, - $term ) );
				} else {
					$payment = $total_price / $term;
				}
			}
		}
		return round( intval($payment) );
	}

	public function build_tab_display( $buttons, $tab_data, $active, $flex = '' ) {

		$flex_item = $flex ? 'style="flex: 1 1 auto; margin: 0; text-align: center;" ' : '';

		$active_tab = '';

		if ( ! empty( $tab_data[ $buttons[ $active ][0] ][0] ) ) {
			$active_tab = $buttons[ $active ][0];
		} else {
			foreach ( $buttons as $key => $button ) {
				if ( empty( $active_tab ) ) {
					$active_tab = ( $tab_data[ $button[0] ][0] ) ? $button[0] : '';
				}
			}
		}

		switch ( strtolower( $tab_data['values']['saleclass'] ) ) {
			case 'new':
				$sc = 1;
				break;
			case 'used':
				$sc = 2;
				break;
			default:
				$sc = 0;
		}

		echo '<div id="vehicle-details-wrapper" >';

		helpers::output_wp_kses( '<div id="vehicle-details-tabs-buttons" ' . $flex . '>','post');
		foreach ( $buttons as $key => $button ) {
			if ( $tab_data[ $button[0] ][0] ) {
				$class = ( $active_tab === $button[0] ) ? 'active' : '';
				switch ( $button[0] ) { // Button Output.
					case 'form':
						$i     = 0;
						$forms = $tab_data[ $button[0] ][1];
						foreach ( $forms as $key => $form ) {
							if ( ( 0 === intval( $form['saleclass'] ) || $form['saleclass'] === $sc ) ) {
								$form_ids[ $i ] = $form['id'];
								helpers::output_wp_kses( '<div ' . $flex_item . ' class="tabs-button tabs-button-details-form-' . $form['id'] . ' ' . $class . ' " data-name="details-form-' . $i . '">' . $form['title'] . '</div>','post');
								$i ++;
							}
						}
						break;
					default:
						helpers::output_wp_kses( '<div ' . $flex_item . ' class="tabs-button tabs-button-details-' . $button[0] . ' ' . $class . ' " data-name="details-' . $button[0] . '">' . $button[1] . '</div>','post');
				}
			}
		}
		echo '</div>';

		echo '<div id="vehicle-details-tabs-content">';
		foreach ( $buttons as $key => $button ) {
			if ( $tab_data[ $button[0] ][0] && 'form' !== $button[0] ) {
				$class = ( $active_tab === $button[0] ) ? 'active' : '';

				helpers::output_wp_kses( '<div class="tabs-content tabs-content-details-' . $button[0] . ' ' . $class . ' "><div id="vehicle-detail-' . $button[0] . '">','post');

				switch ( $button[0] ) { // Content Output.
					case 'options':
						echo '<ul>';
						foreach ( $tab_data[ $button[0] ][1] as $option ) {
							helpers::output_wp_kses( '<li>' . $option . '</li>' );
						}
						echo '</ul>';
						break;
					case 'equipment':
						helpers::output_wp_kses( $this->display_equipment( $tab_data[ $button[0] ][1] ) );
						break;
					case 'loan':
						helpers::output_wp_kses( $this->get_loan_calculator( $tab_data[ $button[0] ][1], $tab_data['values']['price'], false, $tab_data[ $button[0] ][2] ) );
						break;

					default:
						helpers::output_wp_kses( $tab_data[ $button[0] ][1] );
				}
				echo '</div></div>';

			}
		}
		// Form Loop.
		if ( ! empty( $form_ids ) ) {
			foreach ( $form_ids as $key => $id ) {
				$content = '<div class="tabs-content tabs-content-details-form-' . $key . '"><div id="vehicle-detail-form-' . $key . '" class="vehicle-detail-form" >';
				$content .= '<div id="form-id-' . $id . '" class="form-wrapper">';
				$content .= gravity_form( $id, true, false, false, '', true );
				helpers::output_wp_kses( $content );
				echo '</div></div></div>';
			}
		}
		echo '</div>';

		echo '</div>';

	}

	public function get_vehicle_detail_display( $options, $description, $show_equipment = false, $equipment = array(), $active = 'options' ) {

		switch ( strtolower( $active ) ) {
			case 'options':
				$class = count( $options ) > 0 ? array( 'active', '', '' ) : '';
				break;
			case 'description':
				$class = strlen( $description ) > 0 ? array( '', 'active', '' ) : '';
				break;
			case 2:
				$class = $show_equipment && ! $this->is_Empty_check( $equipment ) ? array( '', '', 'active' ) : '';
				break;
		}

		if ( empty( $class ) ) {
			if ( count( $options ) > 0 ) {
				$class = array( 'active', '', '' );
			} elseif ( strlen( $description ) > 0 ) {
				$class = array( '', 'active', '' );
			} elseif ( $show_equipment && ! $this->is_Empty_check( $equipment ) ) {
				$class = array( '', '', 'active' );
			}
		}

		$buttons = '';
		$content = '';

		if ( count( $options ) > 0 ) {
			$buttons .= '<div class="tabs-button tabs-button-details-options ' . $class[0] . '" data-name="details-options">Vehicle Options</div>';
			$content .= '<div class="tabs-content tabs-content-details-options ' . $class[0] . '"><div id="vehicle-detail-options"><ul>';
			foreach ( $options as $option ) {
				$content .= '<li>' . $option . '</li>';
			}
			$content .= '</ul></div></div>';
		}

		if ( strlen( $description ) > 0 ) {
			$buttons .= '<div class="tabs-button tabs-button-details-desc ' . $class[1] . '" data-name="details-desc">Description</div>';
			$content .= '<div class="tabs-content tabs-content-details-desc ' . $class[1] . '"><div id="vehicle-detail-desc">';
			$content .= $description;
			$content .= '</div></div>';
		}

		if ( $show_equipment && ! $this->is_Empty_check( $equipment ) ) {
			$buttons .= '<div class="tabs-button tabs-button-details-equipment ' . $class[2] . '" data-name="details-equipment">Standard Equipment</div>';
			$content .= '<div class="tabs-content tabs-content-details-equipment ' . $class[2] . '"><div id="vehicle-detail-equipment">';
			$content .= $this->display_equipment( $equipment );
			$content .= '</div></div>';
		}

		$display = '<div id="vehicle-details-wrapper" >';

		$display .= '<div id="vehicle-details-tabs-buttons">';
		$display .= $buttons;
		$display .= '</div>';

		$display .= '<div id="vehicle-details-tabs-content">';
		$display .= $content;
		$display .= '</div>';

		$display .= '</div>';

		return $display;

	}

	public function get_default_tag_names() {
		$icons = array(
			'on-sale',
			'certified',
			'special',
			'cherry-deal',
			'custom-wheels',
			'gas-saver',
			'good-buy',
			'hybrid',
			'local-trade-in',
			'low-miles',
			'moon-roof',
			'navagation',
			'one-owner',
			'priced-to-go',
			'rare',
			'sale-pending',
			'under-blue-book',
			'wont-last',
			'video',
		);

		return $icons;
	}

	public function build_tag_icons( $vehicle_tags, $vin = '' ) {
		$default      = $this->get_default_tag_names();
		$custom       = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'tags',
				'custom',
			)
		);
		$icons        = '';
		$temp         = array();
		$vehicle_tags = empty( $vehicle_tags ) ? array() : explode( ',', $vehicle_tags );

		if ( ! empty( $custom ) ) {
			usort( $custom, array( $this, 'sort_custom_tags' ) );

			// Get Custom Icons.
			foreach ( $custom as $value ) {
				if ( in_array( $value['name'], $vehicle_tags, true ) ) {
					$icons .= ! empty( $value['link'] ) ? '<a href="' . str_replace( '{vin}', $vin, $value['link'] ) . '">' : '';
					$icons .= '<img title="' . $value['name'] . '" class="icon-custom icon-emb-' . $value['name'] . '" src="' . $value['url'] . '" />';
					$icons .= ! empty( $value['link'] ) ? '</a>' : '';
					$temp[] = $value['name'];
				}
			}
		}
		$img_src = CDP_IMG . 'templates/inventory/';
		// Get Defaults.
		foreach ( $default as $value ) {
			if ( ! in_array( $value, $temp, true ) ) {
				if ( in_array( $value, $vehicle_tags, true ) ) {
					$icons .= '<img title="' . $value . '" class="icon-default icon-emb-' . $value . '" src="' . $img_src . 'tags/' . $value . '.png" />';
				}
			}
		}

		return $icons;

	}

	public function decode_geo_query( $dealer_geo, &$params, &$geo_params ) {
		if ( ! empty( $dealer_geo ) && ( isset( $params['geo_state'] ) || isset( $params['geo_city'] ) || isset( $params['geo_zip'] ) ) ) {
			if ( isset( $params['geo_state'] ) && 'all' !== strtolower( $params['geo_state'] ) ) {
				$geo_params['state'] = $params['geo_state'];
			}

			if ( isset( $params['geo_city'] ) && 'all' !== strtolower( $params['geo_city'] ) ) {
				$geo_params['city'] = $params['geo_city'];
			}

			if ( isset( $params['geo_zip'] ) && 'all' !== strtolower( $params['geo_zip'] ) ) {
				$geo_params['zip'] = $params['geo_zip'];
			}

			if ( isset( $geo_params['zip'] ) ) {
				$geo_params['key']   = 'zip';
				$geo_params['city']  = $this->recursive_array_parent_key_search( $geo_params['zip'], $dealer_geo );
				$geo_params['state'] = $this->recursive_array_parent_key_search( $geo_params['city'], $dealer_geo );
			} elseif ( isset( $geo_params['city'] ) ) {
				$geo_params['key']   = 'city';
				$geo_params['state'] = $this->recursive_array_parent_key_search( $geo_params['city'], $dealer_geo );
			} elseif ( isset( $geo_params['state'] ) ) {
				$geo_params['key'] = 'state';
			} else {
				$geo_params['key'] = 'default';
			}
			$dealer_ids = $this->get_geo_dealer_ids( $dealer_geo, $geo_params );
			if ( ! empty( $dealer_ids ) ) {
				$params['geo_search'] = 1;
				$params['dealer_id']  = implode( ',', $dealer_ids );
			}
		}
	}

	public function get_geo_dealer_ids( $geo, $params ) {
		$dealers = array();
		if ( isset( $params['zip'] ) && isset( $params['city'] ) && isset( $params['state'] ) ) {
			foreach ( $geo[ $params['state'] ][ $params['city'] ][ $params['zip'] ] as $dealer ) {
				$dealers[] = $dealer;
			}
		} elseif ( isset( $params['city'] ) && isset( $params['state'] ) ) {
			foreach ( $geo[ $params['state'] ][ $params['city'] ] as $zips ) {
				foreach ( $zips as $dealer ) {
					$dealers[] = $dealer;
				}
			}
		} elseif ( isset( $params['state'] ) && count( $geo ) > 1 ) {
			foreach ( $geo[ $params['state'] ] as $cities ) {
				foreach ( $cities as $zips ) {
					foreach ( $zips as $dealer ) {
						$dealers[] = $dealer;
					}
				}
			}
		}

		return $dealers;
	}

	public function recursive_array_parent_key_search( $needle, $haystack, $parent_key = '' ) {
		foreach ( $haystack as $key => $value ) {
			if ( strval( $needle ) === strval( $key ) ) {
				return $parent_key;
			} elseif ( is_array( $value ) ) {
				$pass  = $key;
				$found = $this->recursive_array_parent_key_search( $needle, $value, $pass );
				if ( false !== $found ) {
					return $found;
				}
			}
		}

		return false;
	}

	public function build_geo_dropdown( $geo, $params, $show_zip = false, $remove_text = '' ) {
		$result = $search_tag = $back_tag = '';
		if ( ! empty( $geo ) ) {
			if ( ! isset( $params['error'] ) ) {
				$result   = '<select id="inventory-geo-select" onchange="document.location = this.value;">';
				$case_key = $params['key'] ?? 'default';
				$case_key = empty( $show_zip ) && in_array( $case_key, array( 'city', 'zip' ), true ) ? 'state' : $case_key;
				// $case_key = isset($geo[ (isset($params[$case_key]) ? $params[$case_key]: '') ]) ? $case_key : 'default';
				switch ( $case_key ) {
					case 'zip':
					case 'city':
						$search_tag = '<div id="geo_text">' . $params['city'] . ', ' . $params['state'] . ' ' . ( $params['zip'] ?? '' ) . '</div>';
						$back_link  = esc_url(remove_query_arg( array( 'geo_zip', 'geo_city', 'geo_state' ) ));
						$back_tag   = '<a id="geo-back-link" href="' . $back_link . '">' . ( ! empty( $remove_text ) ? $remove_text : 'Return' ) . '</a>';
						$result    .= '<option value="' . esc_url(add_query_arg( array( 'geo_zip' => 'all' ) )) . '">All Zip Codes</option>';
						foreach ( $geo[ $params['state'] ][ $params['city'] ] as $zip => $dealer ) {
							$selected = ( isset( $params['zip'] ) && $params['zip'] === $zip ) ? 'selected' : '';
							$result  .= '<option value="' . esc_url(add_query_arg( array( 'geo_zip' => $zip ) ) ) . '" ' . $selected . '>' . $zip . '</option>';
						}
						break;
					case 'state':
						$search_tag = '<div id="geo_text">' . ( isset( $params['city'] ) ? $params['city'] . ', ' : '' ) . $params['state'] . '</div>';
						$back_link  = esc_url(remove_query_arg( array( 'geo_state', 'geo_city', 'geo_zip' ) ));
						$back_tag   = '<a id="geo-back-link" href="' . $back_link . '">' . ( ! empty( $remove_text ) ? $remove_text : 'Return' ) . '</a>';
						$result    .= '<option value="' . esc_url(remove_query_arg( array( 'geo_city' ) ) ). '">All Cities</option>';
						foreach ( $geo[ $params['state'] ] as $city => $zips ) {
							$selected = ( isset( $params['city'] ) && $params['city'] === $city ) ? 'selected' : '';
							$result  .= '<option value="' . esc_url(add_query_arg( array( 'geo_city' => rawurlencode( $city ) ) ) ) . '" ' . $selected . '>' . $city . '</option>';
						}
						break;
					default:
						if ( count( $geo ) > 1 ) {
							$result .= '<option value="' . esc_url(add_query_arg( array( 'geo_state' => 'all' ) ) ) . '">All States</option>';
							foreach ( $geo as $state => $cities ) {
								$result .= '<option value="' . esc_url(add_query_arg( array( 'geo_state' => rawurlencode( $state ) ) ) ) . '">' . $state . '</option>';
							}
						} else {
							$search_tag = isset( $params['state'] ) ? '<div id="geo_text">' . $params['state'] . '</div>' : '';
							$result    .= '<option value="' . esc_url(add_query_arg( array( 'geo_city' => 'all' ) ) ) . '">All Cities</option>';
							foreach ( $geo as $state => $cities ) {
								foreach ( $cities as $city => $zips ) {
									$result .= '<option value="' . esc_url(add_query_arg( array( 'geo_city' => rawurlencode( $city ) ) ) ) . '">' . $city . '</option>';
								}
							}
						}
						break;
				}
				$result .= '</select>';
			} else {
				$result = '<div id="geo-error">Error</div>';
			}
			$results = array(
				'dropdown'  => $result,
				'back_link' => $back_tag,
				'search'    => $search_tag,
			);

			return $results;
		}
	}

	public function sort_custom_tags( $a, $b ) {
		return ( $a['order'] > $b['order'] ) ? + 1 : - 1;
	}

	public function display_autocheck_image( $vin, $sc = 'new', $page = 'list' ) {
		$autocheck = '';
		if ( 'used' === strtolower( $sc ) ) {
			$autocheck      = '<div class="autocheck-' . $page . '" >';
			$onclick_string = "'" . site_url() . '/inventory/autocheck/' . $vin . "/','popup', 'width=960,height=800,scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'";
			$autocheck     .= '<a rel="nofollow" onclick="window.open(' . $onclick_string . '); return false"  >';
			// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
			$autocheck     .= '<img alt="autocheck logo" src="' . CDP_IMG . 'templates/inventory/autocheck_' . $page . '.png" /></a>';
			$autocheck     .= '</div>';
		}

		return $autocheck;
	}

	public function cdp_display_carfax( $vin, $url = '', $carfax_image_url = '', $page = 'detail' ) {
		if ( preg_match( '/1own/', $carfax_image_url ) ) {
			$one_owner = 'carfax-one-owner';
		} else {
			$one_owner = '';
		}

		if ( 'detail' === $page ) {
			$page_class = 'detail-page-carfax';
		} else {
			$page_class = 'list-page-carfax';
		}

		$result  = '<div class="inventory-vehicle-carfax ' . $one_owner . ' ' . $page_class . '">';
		$result .= '<a rel="nofollow" href="' . $url . '" class="inventory-' . $page_class . ' ' . $one_owner . '" target="_blank" name="Carfax">';
		// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
		$result .= '<img src="' . $carfax_image_url . '" alt="'. $one_owner .'" />';
		$result .= '</a>';
		$result .= '</div>';

		return $result;
	}

	// autocheck
	// no current clients have autocheck so leaving till can confirm it breaks or works.
	public function get_proxy_site_page( $url ) {
		$options = array(
			CURLOPT_RETURNTRANSFER => true,     // return web page.
			CURLOPT_HEADER         => true,     // return headers.
			CURLOPT_FOLLOWLOCATION => true,     // follow redirects.
			CURLOPT_ENCODING       => '',       // handle all encodings.
			CURLOPT_AUTOREFERER    => true,     // set referer on redirect.
			CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect.
			CURLOPT_TIMEOUT        => 120,      // timeout on response.
			CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects.
		);

//		$ch = curl_init( $url );
//		curl_setopt_array( $ch, $options );
//		$remote_site = curl_exec( $ch );
//		$header      = curl_getinfo( $ch );
//		curl_close( $ch );
//		$header['content'] = $remote_site;
		$response = wp_remote_get( $url );
		$header = $response['header'];

		return $header;
	}

	public function sort_equipment( $a, $b ) {
		return ( $a->group > $b->group ) ? + 1 : - 1;
	}

	// Sort Options by length.
	public function sort_length( $a, $b ) {
		return strlen( $a ) - strlen( $b );
	}

	public function display_equipment( $equipment, $saleclass = 'used' ) {
		$eq = '';

		if ( ! $this->is_Empty_check( $equipment ) ) {

			$equipment_groups = array();
			$equipment_data   = array();

			usort( $equipment, array( $this, 'sort_equipment' ) );

			foreach ( $equipment as $item ) {
				$equipment_data[ $item->group ][] = $item;
				if ( ! in_array( $item->group, $equipment_groups, true ) ) {
					$equipment_groups[] = $item->group;
				}
			}

			$eq .= '<div class="equipment-disclaimer"><i><sup>*</sup>Standard Equipment is the default equipment supplied for the Make and Model of this vehicle, but may not represent the final vehicle with additional / altered equipment options.</i></div>';

			foreach ( $equipment_groups as $group ) {
				if ( 'new' === strtolower( $saleclass ) || ( 'Warranty' !== $group && 'used' === strtolower( $saleclass ) ) ) {
					$eq     .= '<div class="equipment_group">';
					$replace = array( ' ', ',', '/', '-' );
					$name    = strtolower( str_replace( $replace, '_', $group ) );
					$eq     .= '<h4 class="collapse-toggle" data-name="' . $name . '">' . $group . '</h4>';
					$eq     .= '<ul class="equipment_list collapse-divider ' . $name . '">';
					foreach ( $equipment_data[ $group ] as $data ) {
						$eq .= '<li>' . $data->name;
						$eq .= ! empty( $data->data ) ? ': ' . $data->data : null;
						$eq .= '</li>';
					}
					$eq .= '</ul>';
					$eq .= '</div>';
				}
			}
		}

		return $eq;
	}

	public function get_similar_vehicles( $vms, $detail_vin, $sale_class, $vehicle_class, $price, $make, $make_filter, $location, $flex = '' ) {

		if ( ! empty( $vehicle_class ) ) {
			$price_from = $price - 3000;
			$price_to   = $price + 1000;
			if ( $price_from < 0 ) {
				$price_from = 0;
			}

			if ( $price > 0 ) {
				$sim_array = array(
					'search_sim'   => 1,
					'photo_view'   => 1,
					'saleclass'    => $sale_class,
					'vehicleclass' => $vehicle_class,
					'per_page'     => 4,
					'price_from'   => $price_from,
					'price_to'     => $price_to,
				);
			} else {
				$sim_array = array(
					'search_sim'   => 1,
					'photo_view'   => 1,
					'saleclass'    => $sale_class,
					'vehicleclass' => $vehicle_class,
					'per_page'     => 4,
					'make'         => $make,
				);
			}

			if ( 0 === strcasecmp( $sale_class, 'new' ) && ! empty( $make_filter ) ) {
				$sim_array = array_merge( $sim_array, array( 'make_filters' => $make_filter ) );
			}

			$vms->tracer    = 'Obtaining Similar Vehicles - 1';
			$inventory_sims = $vms->get_inventory( array( 'parameters' => $sim_array ) );

			$sim_value = '';

			if ( ! empty( $inventory_sims ) && count( $inventory_sims ) > 1 ) {
				$sim_value = $this->similar_vehicle_view( $inventory_sims, $location, $detail_vin, $flex );
			} elseif ( isset( $sim_array['price_from'] ) ) {
				unset( $sim_array['price_from'] );
				unset( $sim_array['price_to'] );
				$sim_array      = $sim_array + array( 'make' => $make );
				$vms->tracer    = 'Obtaining Similar Vehicles - 2';
				$inventory_sims = $vms->get_inventory( array( 'parameters' => $sim_array ) );
				if ( ! empty( $inventory_sims ) && count( $inventory_sims ) > 1 ) {
					$sim_value = $this->similar_vehicle_view( $inventory_sims, $location, $detail_vin, $flex );
				}
			}

			return $sim_value;
		}
	}

	public function similar_vehicle_view( $inventory_sims, $location, $detail_vin, $flex = '' ) {
		if ( ! empty( $inventory_sims ) ) {
			$flex_item = $flex ? 'style="flex: 0 1 auto; max-width: 200px; margin: 2% 1%; background-color: #1e1e1e; width: 100%;" ' : '';

			$sim_value   = '<div id="similar-vehicles-wrapper">';
			$sim_value  .= '<div id="similar-title">Similar Vehicles</div>';
			$sim_value  .= '<div id="similar-items" ' . $flex . '>';
			$sim_counter = 0;
			foreach ( $inventory_sims as $vehicle ) :
				$link_params               = array(
					'year'  => $vehicle['year'],
					'make'  => $vehicle['make'],
					'model' => $vehicle['model'],
					'state' => $location['state'],
					'city'  => $location['city'],
					'vin'   => $vehicle['vin'],
					'vms_id'    => $vehicle['vms_id'],
				);
				$link                      = $this->generate_inventory_link( array('params' => $link_params, 'type' => 1 ) );
				$sim_generic_vehicle_title = $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'];
				if ( ( $vehicle['saleprice'] < $vehicle['askingprice'] ) && $vehicle['saleprice'] > 0 ) {
					$sim_main_price = '<div class="similar-price">Price $' . $this->price_format( $vehicle['saleprice'] ) . '</div>';
				} else {
					if ( $vehicle['askingprice'] > 0 ) {
						$sim_main_price = '<div class="similar-price">Price $' . $this->price_format( $vehicle['askingprice'] ) . '</div>';
					} else {
						$saleclass      = $vehicle['saleclass'];
						$sim_main_price = '<div class="similar-price">' . self::$theme_options['theme']['inventory_display']['prices']['text'][ $saleclass ]['call_for_price'] . '</div>';
					}
				}

				if ( $detail_vin !== $vehicle['vin'] && $sim_counter < 3 ) {
					$sim_counter = $sim_counter + 1;
					// Similar Start.
					$sim_value .= '<div class="similar-item" ' . $flex_item . '>';
					// Similar Headline.
					$sim_value .= '<div class="similar-headline">';
					$sim_value .= '<span class="similar-saleclass">' . $vehicle['saleclass'] . '</span>';
					$sim_value .= '<a href="' . $link . '" title="' . $sim_generic_vehicle_title . '" >';
					$sim_value .= '<span class="similar-make">' . $vehicle['make'] . '</span>';
					$sim_value .= '<span class="similar-make">' . $vehicle['model'] . '</span>';
					$sim_value .= '</a></div>';
					// Similar Content Wrapper -start.
					$sim_value .= '<div class="similar-content-wrap">';
					// Similar Photo.
					$sim_value .= '<div class="similar-column-left">';
					$sim_value .= '<div class="similar-photo">';
					$sim_value .= '<a href="' . $link . '" title="' . $sim_generic_vehicle_title . '">';
					$image      = $this->no_photo_replace( $vehicle['thumbnail'] );
					// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
					$sim_value .= '<img src="' . $image . '" alt="' . $sim_generic_vehicle_title . '" title="' . $sim_generic_vehicle_title . '" />';
					$sim_value .= '</a></div></div>';
					// Similar Info.
					$sim_value .= '<div class="similar-column-right">';
					$sim_value .= '<div class="similar-info">';
					$sim_value .= '<div class="similar-details">';
					$sim_value .= '<span class="similar-stock-number">Stock #: ' . $vehicle['stock'] . '</span>';
					$sim_value .= '<span class="similar-year">Year: ' . $vehicle['year'] . '</span>';
					$sim_value .= '<span class="similar-trim">Trim: ' . $vehicle['trim'] . '</span>';
					$sim_value .= '</div>';
					$sim_value .= '<div class="similar-price">';
					$sim_value .= $sim_main_price;
					$sim_value .= '</div>';
					$sim_value .= '</div></div>';
					// Similar Content Wrapper -end.
					$sim_value .= '</div>';
					// Similar Button.
					$sim_value .= '<div class="similar-button">';
					$sim_value .= '<a href="' . $link . '" title="More Information: ' . $sim_generic_vehicle_title . '">More Information</a>';
					$sim_value .= '</div>';
					// Similar End.
					$sim_value .= '</div>';
				}
			endforeach;
			$sim_value .= '</div></div>';

			return $sim_value;
		}
	}
	public function generate_inventory_link( $args ){
		$params = $args['params'];
		$include = $args['include'] ?? array();
		$remove = $args['remove'] ?? array();
		$type = $args['type'] ?? 0;

		$rules          = get_option( 'rewrite_rules' );
		$rule       = isset( $rules['^(inventory)'] );
		$exclude = array(
			'page',
			'dealer_id',
			'taxonomy',
			'per_page',
			'make',
			'model',
			'saleclass',
			'geo_search',
			'geo_state',
			'geo_city',
			'geo_zip',
			'dealer',
		);
		if ( ! empty( $include ) ) {
			foreach ( $include as $key => $value ) {
				$params[ $key ] = $value;
			}
		}
		if ( ! empty( $remove ) ) {
			foreach ( $remove as $value ) {
				unset( $params[ $value ] );
			}
		}
		$vdp_url_option = Option::check_for_option(
			'cdp_admin_options',
			array(
				'admin',
				'general',
				'vdp_url_identifier',
			),
			'vin'
		);
		if ( $rule ) {
			if ( $type ) {
//				$separator = Option::check_for_option(
//					'cdp_admin_options',
//					array(
//						'admin',
//						'general',
//						'vdp_url_separator',
//					),
//				);
				$separator = '/';
				$link = '/inventory/' . $params['year'] . $separator .
				        rawurlencode(rawurldecode($params['make'])) . $separator .
				        rawurlencode(rawurldecode( $params['model'])) . $separator .
				        rawurlencode(rawurldecode($params['state'])) . $separator .
				        rawurlencode(rawurldecode(wp_strip_all_tags($params['city']))) . $separator;
				if ( ! empty( $params['vin'] ) && 'vin' === $vdp_url_option ) {
					$link .= $params['vin'] . '/';
				} else {
					$link .= $params['vms_id'] . '/';
				}
			} else {
				$link  = '/inventory/' . $params['saleclass'] . '/';
				$link .= isset( $params['make'] ) && 'all' !== strtolower( $params['make'] ) ? rawurlencode( rawurldecode( $params['make'] ) ) . '/' : '';
				$link .= isset( $params['model'] ) && 'all' !== strtolower( $params['model'] ) ? rawurlencode( rawurldecode( $params['model'] ) ) . '/' : '';
				foreach ( $params as $key => $param ) {
					if ( ! in_array( $key, $exclude, true ) && 'all' !== strtolower( $param ) && ! empty( $param ) ) {
						$link = esc_url(add_query_arg( array( $key => $param ), $link ) );
					}
				}
			}
		} else {
			if ( ! empty( $params['vin'] ) && 'vin' === $vdp_url_option ) {
				unset($params['vms_id']);
			} else {
				unset($params['vin']);
			}
			$link = $this->generate_taxonomy_url( array( 'params' => array( 'taxonomy' => 'inventory' ), 'additional' => $params  ) );
		}
		if ( ! isset( $params['vin'] ) ) {
			$this->apply_geo_query_links( $link );
		}

		return $link;
	}

	function generate_taxonomy_url($args) {
		$params = $args['params'];
		$additional = $args['additional'] ?? array();
		$remove = $args['remove'] ?? array();
		$url = '';
		$params = array_unique(array_merge($params, $additional));
		if ( !empty($remove) ) {
			foreach ($remove as $key) {
				unset( $params[ $key ] );
			}
		}
		foreach ( $params as $key => $value ) {
			if ( 'taxonomy' === $key ) {
				$url = '?taxonomy=' . $value;
			} else {
				$url .= '&' . $key . '=' . $value;
			}
		}
		return $url;
	}

	public function apply_geo_query_links( &$link ) {
		if ( isset( $this->safe['geo_state'] ) ) {
			$link = esc_url(add_query_arg( array( 'geo_state' => rawurlencode( $this->safe['geo_state'] ) ), $link ));
		}
		if ( isset( $this->safe['geo_city'] ) ) {
			$link = esc_url(add_query_arg( array( 'geo_city' => rawurlencode( $this->safe['geo_city'] ) ), $link ));
		}
		if ( isset( $this->safe['geo_zip'] ) ) {
			$link = esc_url(add_query_arg( array( 'geo_zip' => rawurlencode( $this->safe['geo_zip'] ) ), $link ));
		}
	}

	public function build_slider_script( $params ) {
		$pre            = ( 'price' === $params['type'] ) ? '$' : '';
		$set_value_from = $params['search']['from'] ?? $params['default']['low'];
		$set_value_to   = $params['search']['to'] ?? $params['default']['high'];
		$max = $params['default']['high'];
		$min = $params['default']['low'];
		$step = $params['step'];
		$type = $params['type'];
		$name = "#$type-range-slider";
		$script  = "<script type='text/javascript' >";
		$script .= "jQuery(document).ready(function(){";
		$script .= "jQuery('$name').slider({max: $max ,min: $min, range: true,step: $step ,values: [ $set_value_from , $set_value_to ], slide: ";
		$script .= "function( event, ui ) { ";
		$script .= "jQuery( '#$type-range-values' ).val( '$pre' + ui.values[ 0 ] +  '- $pre' + ui.values[ 1 ] );";
		$script .= "jQuery( '#$type-range-flag' ).val('true' );";
		$script .= "} });";
		$script .= "let min = jQuery( '$name' ).slider( 'values', 0 );";
		$script .= "let max = jQuery( '$name' ).slider( 'values', 1 );";
		$script .= "jQuery( '#$type-range-values' ).val( '$pre' + min + '- $pre' + max );";
		$script .= '});</script>';

		return $script;
	}

	public function apply_gravity_form_hooks( $data ) {
		$hooks = $this->get_gravity_hooks( $data );
		foreach ( $hooks as $key => $result ) {
			add_filter(
				'gform_field_value_' . $key,
				function ( $value ) use ( $result ) {
					$value = $result;

					return $value;
				}
			);
		}
	}

	public function get_gravity_hooks( $data ) {

		$hooks = array(
			'dt_stock_number' => ( $data['stock_number'] ?? $data['stock'] ),
			'dt_vin'          => $data['vin'],
			'dt_year'         => $data['year'],
			'dt_make'         => ( $data['make']['name'] ?? $data['make'] ),
			'dt_model'        => ( $data['model']['name'] ?? $data['model'] ),
			'dt_trim'         => ( $data['trim']['name'] ?? $data['trim'] ),
			'dt_saleclass'    => $data['saleclass'],
			'dt_exterior'     => ( $data['exterior_color'] ?? $data['exterior'] ),
			'dt_interior'     => ( $data['interior_color'] ?? $data['interior'] ),
			'dt_mileage'      => $data['odometer'],
			'dt_price'        => $data['primary_price'],
			'dt_dealer'       => ( $data['contact_info']['dealer'] ?? $data['dealer'] ),
			'dt_dealer_id'    => ( $data['contact_info']['dealer_id'] ?? $data['dealer_id'] ),
			'dt_location'     => ( $data['contact_info']['location'] ?? $data['location'] ),
			'dt_phone'        => ( $data['contact_info']['phone'] ?? $data['phone'] ),
			'dt_transmission' => $data['transmission'],
		);

		$hooks['dt_automall_email'] = $this->get_automall_email( ( isset( $data['contact_info']['dealer_id'] ) ? $data['contact_info']['dealer_id'] : $data['dealer_id'] ), $data['saleclass'], true );
		$hooks['dt_is_adf']         = $this->get_automall_email_adf( ( isset( $data['contact_info']['dealer_id'] ) ? $data['contact_info']['dealer_id'] : $data['dealer_id'] ), $data['saleclass'] );

		return $hooks;
	}

	public function cdp_apply_setting_scripts( $scripts, $page, $saleclass ) {
		$page_type = 'list' === $page ? 'list' : 'detail';
		$sc_type   = 'new' === strtolower( $saleclass ) ? 'new' : 'used';
		$replace   = array( ' ', ',', '/', '-' );
		foreach ( $scripts as $script ) {
			if ( 'all' === $script['saleclass'] || $script['saleclass'] === $sc_type ) {
				if ( 'all' === $script['page'] || $script['page'] === $page_type ) {
					$in_footer   = ! ( 'header' === $script['location'] );
					$script_name = strtolower( str_replace( $replace, '_', $script['name'] ) );
					wp_enqueue_script( $script_name, $script['url'], 'jQuery', CDP_VERSION, $in_footer );
				}
			}
		}
	}

	public function cdp_apply_setting_styles( $styles, $page, $saleclass ) {
		$page_type = 'list' === $page ? 'list' : 'detail';
		$sc_type   = 'new' === strtolower( $saleclass ) ? 'new' : 'used';
		$replace   = array( ' ', ',', '/', '-' );
		foreach ( $styles as $style ) {
			if ( 'all' === $style['saleclass'] || $style['saleclass'] == $sc_type ) {
				if ( 'all' === $style['page'] || $style['page'] === $page_type ) {
					$style_name = strtolower( str_replace( $replace, '_', $style['name'] ) );
					wp_enqueue_style( $style_name, $style['url'] , array(), CDP_VERSION);
					if ( ! empty( $style['override'] ) ) {
						wp_deregister_style( 'cdp_inventory' );
					}
				}
			}
		}
	}

	public function cdp_create_saleclass_dd_sc( $flag = 'all', $default = 'all' ) {
		$content  = '<div class="sc-search-item saleclass">';
		$content .= '<label class="sc-search-label">Sale Class</label>';
		$content .= '<select id="sc-search-saleclass" class="inventory-select" onchange="cdp_vehicle_caller(this.value, \'saleclass\');">';

		switch ( strtolower( $flag ) ) {
			case 'all':
				$content .= '<option value="" ' . ( 'all' === strtolower( $default ) ? 'selected' : '' ) . ' >All Vehicles</option>';
				$content .= '<option value="new" ' . ( 'new' === strtolower( $default ) ? 'selected' : '' ) . '>New Vehicles</option>';
				$content .= '<option value="used" ' . ( 'used' === strtolower( $default ) ? 'selected' : '' ) . '>Pre-Owned Vehicles</option>';
				// $content .= '<option value="certified">Certified Pre-Owned</option>';
				break;
			case 'new':
				$content .= '<option value="new" selected>New Vehicles</option>';
				break;
			case 'used':
				$content .= '<option value="used" selected>Pre-Owned Vehicles</option>';
				// $content .= '<option value="certified">Certified Pre-Owned</option>';
				break;
			case 'certified':
				$content .= '<option value="used" selected>Pre-Owned Vehicles</option>';
				// $content .= '<option value="certified" selected>Certified Pre-Owned</option>';
				break;
		}

		$content .= '</select>';
		$content .= '</div>';

		return $content;
	}

	public function cdp_generate_make_options( $vms, $saleclass, $makes = array(), $val_only = false, $alt_id = 0 ) {

		if ( empty( $makes ) || 'used' === strtolower( $saleclass ) ) {
			$vms->tracer = 'Getting Makes';
			$makes       = $vms->get_makes(
				array(
					'parameters' => array(
						'saleclass' => $saleclass,
						'dealer_id' => $alt_id,
					),
				)
			);
		}
		$options = '';
		if ( $val_only ) {
			return $makes; // Returns data as Array.
		} else {
			if ( 1 === count( $makes ) ) {
				$content['val'] = strtolower( rawurlencode( $makes[0] ) );
			} else {
				$content['val'] = '';
				$options        = '<option value="">All Makes</option>';
			}
			foreach ( $makes as $make ) {
				$options .= '<option value="' . strtolower( rawurlencode( $make ) ) . '">' . $make . '</option>';
			}
			$content['display'] = $options;

			return $content;
		}

	}

	public function cdp_generate_model_options( $vms, $saleclass, $make = '', $val_only = false, $alt_id = 0 ) {

		if ( empty( $make ) ) {
			$content['val']      = '';
			$content['display']  = '<option value="">Models</option>';
			$content['disabled'] = 'TRUE';

			return $content;
		}

		$vms->tracer = 'Getting Models';
		$models      = $vms->get_models(
			array(
				'parameters' => array(
					'saleclass' => $saleclass,
					'make'      => $make,
					'alt_id'    => $alt_id,
				),
			)
		);

		if ( $val_only ) {
			return $models;
		} else {
			if ( 1 === count( $models ) ) {
				$content['val'] = strtolower( rawurlencode( $models[0] ) );
				$options        = '';
			} else {
				$content['val'] = '';
				$options        = '<option value="">All Models</option>';
			}
			foreach ( $models as $model ) {
				$options .= '<option value="' . strtolower( rawurlencode( $model ) ) . '">' . $model . '</option>';
			}
			$content['display'] = $options;

			return $content;
		}

	}

	public function cdp_generate_trim_options( $vms, $saleclass, $make = '', $model = '', $val_only = false, $alt_id = 0 ) {

		if ( empty( $make ) || empty( $model ) ) {
			$content['val']      = '';
			$content['display']  = '<option value="">Trims</option>';
			$content['disabled'] = 'TRUE';

			return $content;
		}

		$vms->tracer = 'Getting Trims';
		$trims       = $vms->get_trims(
			array(
				'parameters' => array(
					'saleclass' => $saleclass,
					'make'      => $make,
					'model'     => $model,
					'alt_id'    => $alt_id,
				),
			)
		);

		if ( $val_only ) {
			return $trims;
		} else {
			if ( 1 === count( $trims ) ) {
				$content['val'] = strtolower( rawurlencode( $trims[0] ) );
				$options        = '';
			} else {
				$content['val'] = '';
				$options        = '<option value="">All Trims</option>';
			}
			foreach ( $trims as $trim ) {
				$options .= '<option value="' . strtolower( rawurlencode( $trim ) ) . '">' . $trim . '</option>';
			}
			$content['display'] = $options;

			return $content;
		}

	}

	public function is_Empty_check( $obj ) {
		if ( empty( $obj ) ) {
			return true;
		} elseif ( is_numeric( $obj ) ) {
			return false;
		} elseif ( is_string( $obj ) ) {
			return ! strlen( trim( $obj ) );
		} elseif ( is_object( $obj ) ) {
			return $this->is_Empty_check( (array) $obj );
		}
		// It's an array!
		foreach ( $obj as $element ) {
			if ( ! $this->is_Empty_check( $element ) ) {
				return false;
			}
		}

		// all good.
		return true;
	}

	public function get_disclaimer() {
		return urldecode( stripslashes( self::$theme_options['theme']['overrides']['disclaimer'] ) );
	}

	public function get_info_column( $style, $vehicle, $phone, $dealer_name, $loan, $ac, $gform_id, $gform_data, $contact_info ) {
		$column  = '<div id="inventory-column-info" class="inventory-column ' . $style . '">'; // column wrapper.
		$column .= '<div id="inventory-request-form">'; // get info form wrapper.
		if ( function_exists( 'gravity_form' ) && ! empty( $gform_id ) ) {
			// get_form_display( $theme_settings['gravity_form']['data'], $saleclass );
			$column .= '<div class="form-wrapper">';
			$column .= '<div id="info-form-id-' . $gform_id . '" class="form-display-wrap form-' . $gform_id . '" name="form-id-' . $gform_id . '">';
			$column .= do_shortcode( '[gravityform id=' . $gform_id . ' title=true description=false]' );
			$column .= '</div>';
			$column .= '</div>';
		}
		$column .= '</div>'; // get info form wrapper.
		$column .= '<div id="inventory-contact-information">'; // dealer contact info.
		$column .= '<div id="contact-information-header" class="inventory-header">Contact Information</div>';
		$column .= '<div id="contact-greeting">' . $contact_info['greeting'] . '</div>';
		$column .= '<div id="contact-dealer-name">' . $dealer_name . '</div>';
		$column .= '<div id="contact-dealer-address">' . $vehicle['location'] . '</div>';
		if ( ! empty( $phone ) ) {
			$column .= '<div id="contact-dealer-phone">Phone Number: <a tel="' . $phone . '">' . $phone . '</a></div>';
		}
		$column .= '</div>'; // dealer contact info.
		$column .= '<div id="inventory-helpful-links">'; // extra links.
		if ( ! empty( $loan ) ) {
			$column .= '<div id="inventory-calculator">'; // calculator.
			$column .= $loan;
			$column .= '</div>';
		}
		if ( ! empty( $gform_data ) ) {
			$column .= $gform_data;
		}
		if ( ! empty( $ac ) ) {
			$column .= $ac;
		}
		if ( ! empty( $vehicle['carfax'] ) && 'used' === strtolower( $vehicle['saleclass'] ) ) {
			$column .= '<div class="carfax-wrapper">' . $this->cdp_display_carfax( $vehicle['vin'], $vehicle['carfax'], $vehicle['carfax_image_url'] ) . '</div>';
		}

		$column .= '</div>'; // extra links.
		$column .= '</div>'; // column wrapper.

		return $column;
	}

	public function get_detail_column( $style, $vehicle, $price, $fuel, $tags, $detail_tabs, $equipment, $loan ) {
		$column  = '<div id="inventory-column-details" class="inventory-column ' . $style . '">'; // column wrapper.
		$column .= '<div id="inventory-vehicle-information">'; // vehicle info.
		$column .= '<div id="vehicle-info-header" class="inventory-header">Vehicle Information</div>';
		$column .= '<div id="vehicle-info-wrapper">' . ( ! empty( $vehicle['exterior'] ) ? '<div id="info-ext-color"><span>Exterior: </span>' . $vehicle['exterior'] . '</div>' : '' ) . ( ! empty( $vehicle['interior'] ) ? '<div id="info-int-color"><span>Interior: </span>' . $vehicle['interior'] . '</div>' : '' ) . ( ! empty( $vehicle['engine'] ) ? '<div id="info-engine"><span>Engine: </span>' . $vehicle['engine'] . '</div>' : '' ) . ( ! empty( $vehicle['fuel_type'] ) ? '<div id="info-fuel-type"><span>Fuel Type: </span>' . $vehicle['fuel_type'] . '</div>' : '' ) . ( ! empty( $vehicle['transmission'] ) ? '<div id="info-transmission"><span>Transmission: </span>' . $vehicle['transmission'] . '</div>' : '' ) . ( ! empty( $vehicle['odometer'] ) ? '<div id="info-odometer"><span>Odometer: </span>' . $vehicle['odometer'] . '</div>' : '' ) . ( ! empty( $vehicle['stock'] ) ? '<div id="info-stock-number"><span>Stock #: </span><span class="inventory-stock-number">' . $vehicle['stock'] . '</span></div>' : '' ) . ( ! empty( $vehicle['vin'] ) ? '<div id="info-vin"><span>VIN: </span><span class="inventory-vin">' . $vehicle['vin'] . '</span></div>' : '' ) . '</div>';
		$column .= '<div id="inventory-price-wrapper" class="inventory-price">' . $price['compare_price_text'] . $price['primary_text'] . $price['expire_text'] . $price['hidden_prices'] . $loan . '</div>';
		$column .= '</div>'; // vehicle info.
		if ( ! empty( $fuel ) ) {
			$column .= $fuel;
		}
		if ( ! empty( $tags ) ) {
			$column .= $tags;
		}
		if ( ! empty( $detail_tabs ) ) {
			$column .= $detail_tabs;
		}
		if ( ! empty( $equipment ) ) {
			$column .= $equipment;
		}
		$column .= '</div>'; // column wrapper.

		return $column;
	}

	public function get_photo_column( $style, $photo ) {
		$column  = '<div id="inventory-column-photo" class="inventory-column ' . $style . '">';
		$column .= $photo;
		$column .= '</div>'; // column wrapper.

		return $column;
	}
}
