<?php

namespace CarDealerPress\Includes\Functions;

use CarDealerPress\templates\partials\inventory\List_Search_Filters;
use CarDealerPress\templates\partials\inventory\Image_Display;
use CarDealerPress\templates\partials\inventory\Prices;
use CarDealerPress\templates\partials\inventory\Vehicle_Attributes;
use CarDealerPress\Includes\Database\{Requests};
use CarDealerPress\includes\helpers\helpers as helpers;
use CarDealerPress\Includes\Helpers\Option;

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

class Extender_Functions {
	public $fn_inventory;
	public static $links;

	public static $vms_caller;
	private $db_request;

	public static $company;
	public static $passed_parameters;
	public static $request_data;
	public static $saved_vehicles;
	public static $compared_vehicles;
	public static $srp_view;
	public static $search_view;
	/**
	 * @var false|mixed|void
	 */
	public static $theme_options;
	/**
	 * @var false|mixed|void
	 */
	public static $admin_options;


	public function __construct() {
		$this->init();
	}

	private function init() {
		self::$theme_options = Option::get_cdp_theme_options();
		self::$admin_options = Option::get_cdp_admin_options();
		$this->db_request    = new Requests();
		$this->fn_inventory  = new Fn_Inventory();

		self::$srp_view    = self::$theme_options['theme']['inventory_display']['list']['search_filters']['general']['srp_view'] ?? 'list';
		self::$search_view = self::$theme_options['theme']['inventory_display']['list']['search_filters']['general']['search_view'] ?? 'top';

		if ( self::$admin_options['admin']['help']['host'] && helpers::company_id() ) {
			self::$vms_caller = new VehicleManagementSystem( self::$admin_options['admin']['help']['host'], helpers::company_id() );
		}
		if ( self::$vms_caller ) {
			$company_id = helpers::company_id();
			$companies  = $this->db_request->cdp_company_request();
			if ( $companies ) {
				foreach ( $companies as $company ) {
					if ( $company['company_id'] === $company_id && $company['dealer_id'] === $company_id ) {
						self::$company = $company;
					}
				}
			}
		}

		$this->extender_saved_vehicles();
		$this->extender_compared_vehicles();
	}

	public function links() {
		$rules    = get_option( 'rewrite_rules' );
		$url_rule = isset( $rules['^(inventory)'] );

		self::$links['do_not_carry']     = esc_url(remove_query_arg( 'page' ));
		self::$links['tmp_do_not_carry'] = esc_url(remove_query_arg( 'certified', self::$links['do_not_carry'] ));

		self::$links['new_link']  = ( isset( $rules['^(inventory)'] ) ) ? '/inventory/New/' : esc_url(add_query_arg( array( 'saleclass' => 'New' ), self::$links['tmp_do_not_carry'] ));
		self::$links['used_link'] = ( isset( $rules['^(inventory)'] ) ) ? '/inventory/Used/' : esc_url(add_query_arg( array( 'saleclass' => 'Used' ) ));
		self::$links['cert_link'] = ( isset( $rules['^(inventory)'] ) ) ? esc_url(add_query_arg( 'certified', 'yes', '/inventory/Used/' ))
			: esc_url(add_query_arg(
				array(
					'saleclass' => 'Used',
					'certified' => 'yes',
				))
			);
	}

	public function load_parameters( $parameters = array() ) {
		// @codingStandardsIgnoreStart
		self::$passed_parameters = $parameters;
		// @codingStandardsIgnoreEnd
	}

	public function load_request_data( $request ) {
		self::$request_data = $request['data'] ?? array();
	}

	public function custom_filters_search() {
		$search_view   = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'list',
				'search_filters',
				'general',
				'search_view',
			)
		);
		$vehicle_count = $this->db_request->cdp_db_init( 'searchtotal', self::$passed_parameters );
		$show_geo      = self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'];
		$previous_text = self::$passed_parameters['search'] ?? '';
//		$content       = '<div id="search-container">';
//		$content       .= '<div id="search-item-container">';
		// Count
		$content = '<div id="search-count" class="search-item ignore-slide">Vehicles (<span class="search-vehicle-count">' . esc_html( $vehicle_count ) . '</span>)</div>';
		// Text.
		$content .= '<div id="search-text" class="search-item search-action-not-now">';
			$content .= '<input class="text-input input-action input-search" name="search" type="text" value="' . esc_html( $previous_text ) . '" placeholder="Search" list="text-data-list" />';
			$content .= $this->build_text_data_list();
			$content .= '<button class="text-search-button"><span>Search</span></button>';
		$content .= '</div>';
		// List of Current Filters.
		$content .= '<div id="search-tag-container" style="display:none;"><span>Filters</span>';
			$content .= $this->extender_remove_tag_list();
		$content .= '</div>';
		$content .= '<div id="listing-clear-search" style="display:none;"><span>Reset Search</span></div>';
		// GEO.
		$location = '';
		if ( $show_geo || 'geo_dealer_names_only' === self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['geo_options'] ) {
			$location = '<div id="side-search-location" class="side-search-item search-action-not-now open">';
			$location .= '<div class="side-search-item-label search-label show-label">Location <span class="search-item-icon"></span></div>';
			$location .= '<div class="side-search-item-dropdown">';
			$location .= $this->extender_create_geo_list();
			$location .= '</div>';
			$location .= '</div>';
		}
		$content .= "<div id='filters-search' class='search-$search_view'>";
		$content .= $location;
		//$vehicle_filters = ['saleclass','vehicleclass','body','make','model','trim'];
		$filter_settings = $this->filter_settings();
		foreach ( $filter_settings as $filter ) {
			if ( $filter['display'] !== 'on' ) {
				continue;
			}
			$name   = $filter['name'];
			$params = [
				'name'          => $name,
				'display_label' => $filter['display_label'],
			];

			switch ( true ) {
				case preg_match( '/year|price|odometer/', $name ):
					$content .= $filter['display_type'] === 'dropdown'
						? List_Search_Filters::range_dropdown( $params )
						: List_Search_Filters::range_sliders( $params );
					break;
				case $name === 'features':
					$params['parameters'] = self::$passed_parameters;
					$content              .= List_Search_Filters::dropdown_checkbox( $params );
					break;
				case $name === 'mpg':
					$params = [
						$filter['display_label'],
						'city',
						'highway',
					];
					$content .= List_Search_Filters::range_mpg_dropdown( $params );
//					$content .= $filter['display_type'] === 'dropdown'
//						? List_Search_Filters::range_dropdown( $params )
//						: List_Search_Filters::range_sliders( $params );
					break;
				default:
					$content .= List_Search_Filters::dropdown_list( $params );
					break;
			}
		}
		$content .= '</div>';
//		$content .= '</div>';
//		$content .= '</div>';
		return $content;
	}

	public function filter_settings(){
		$filters    = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'list',
				'search_filters',
				'general',
				'filters',
			)
		);
		foreach ( $filters as $filter ) {
			$settings[] = array('name' => esc_html($filter['name']), 'display' => $filter['display'], 'display_type' => $filter['display_type']);
		}
		return $filters;
	}


	public function contact_wrapper( $vehicle, $company, $page = 'list' ) {

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

		$content = '<div itemprop="address" itemscope itemtype="https://schema.org/PostalAddress" style="display:none;">';
		$content .= '<span itemprop="streetAddress" content="' . $dealer_street . '"></span>';
		$content .= '<span itemprop="addressLocality" content="' . $dealer_city . '"></span>';
		$content .= '<span itemprop="addressRegion" content="' . $dealer_state . '"></span>';
		$content .= '<span itemprop="postalCode" content="' . $dealer_zip . '"></span>';
		$content .= '<span itemprop="addressCountry" content="' . $company['country_code'] . '"></span>';
		$content .= '</div>';
		if ( self::$theme_options['theme']['inventory_display'][ $page ]['general']['display_dealer_name'] ) {
			$dealer_name = Option::check_for_option(
				'cdp_theme_options',
				array(
					'theme',
					'overrides',
					'custom_contact',
					'name',
					strtolower( $vehicle['saleclass'] ),
				),
				$company['name']
			);
			$content     .= '<div class="dealer-name form-value address" data-name="dealer" itemprop="name">' . $dealer_name . '</div>';
		}
		if ( 'full' === self::$theme_options['theme']['inventory_display'][ $page ]['general']['display_address_options'] ) {
			$content .= "<div class='vehicle-street address'>$dealer_street $dealer_city, $dealer_state. $dealer_zip</div>";
		}
		if ( 'city_state' === self::$theme_options['theme']['inventory_display'][ $page ]['general']['display_address_options'] ) {
			$content .= "<div class='vehicle-city-state address' >$dealer_city, $dealer_state.</div>";
		}
		if ( self::$theme_options['theme']['inventory_display'][ $page ]['general']['display_dealer_phone'] ) {
			$phone_number = self::$theme_options['theme']['overrides']['custom_contact']['phone'][ strtolower( $vehicle['saleclass'] ) ] ?? $company['phone'];
			$content      .= '<div class="dealer-number form-value" data-name="phone" itemprop="telephone"><a href="tel:' . $phone_number . '">' . $phone_number . '</a></div>';
		}
		$content .= "<div class='dealer-id form-value' data-name='dealer_id' style='display:none;'>$company[dealer_id]</div>";
		$content .= $this->fn_inventory->get_automall_email( $company['dealer_id'], $vehicle['saleclass'] );
		$content .= '<div class="is-adf form-value" data-name="is_adf" style="display:none;" >' . $this->fn_inventory->get_automall_email_adf( $company['dealer_id'], $vehicle['saleclass'] ) . '</div>';

		return $content;
	}

	public function extender_inventory_list_view() {
		$location_id  = 0;
		$companies_db = $this->db_request->cdp_db_init( 'company' );
		$company      = array();
		$vehicles     = $this->db_request->cdp_db_init( 'inventory', self::$passed_parameters );
		if ( empty( $vehicles ) ) {
			$content = $this->extender_vehicle_list_page_no_results();
		} else {
			$content = '<div class="inventory-vehicle-page page-' . ( self::$passed_parameters['page'] ?? '1' ) . ' active">';
			foreach ( $vehicles as $vehicle ) {
				$link_params = array(
					'year'   => $vehicle['year'],
					'make'   => $vehicle['make'],
					'model'  => $vehicle['model'],
					'state'  => $vehicle['geo_state'],
					'city'   => $vehicle['geo_city'],
					'vin'    => $vehicle['vin'],
					'vms_id' => $vehicle['vms_id'],
				);
				if ( empty( $vehicle['sold_on'] ) ) {
					$link = $this->fn_inventory->generate_inventory_link( array('params' => $link_params, 'type' => 1 ) );
				} else {
					$link = '';
				}
				if ( $location_id !== $vehicle['dealer_id'] || empty( $company ) ) {
					$location_id = $vehicle['dealer_id'];
					foreach ( $companies_db as $key => $info ) {
						if ( $location_id === $info['dealer_id'] ) {
							$company = $info;
						}
					}
				}
				$content .= '<div id="' . $vehicle['vin'] . '" class="inventory-vehicle-container vehicle-container vehicle-saleclass-' . strtolower( $vehicle['saleclass'] ) . ' company-' . $vehicle['company_id'] . ' location-' . $vehicle['dealer_id'] . '" itemscope itemtype="https://schema.org/Car">';
				$content .= '<div class="inventory-vehicle-inner-container">';
				// Top.
				$content .= '<div class="inventory-vehicle-inner-top-container">';
				$content .= ( empty( $vehicle['headline'] ) ? '' : '<div class="inventory-vehicle-headline">' . $vehicle['headline'] . '</div>' );
				$content .= '</div>';
				$content .= '<div class="inventory-vehicle-header" itemprop="name">';
				$content .= '<a href="' . $link . '">';
				$content .= '<span class="header-year vehicle-save form-value" data-name="year" itemprop="modelDate">' . $vehicle['year'] . '</span>';
				$content .= '<span class="header-make form-value vehicle-save" data-name="make" itemprop="manufacturer">' . $vehicle['make'] . '</span>';
				$content .= '<span class="header-model form-value vehicle-save" data-name="model" itemprop="model">' . $vehicle['model'] . '</span>';
				$content .= '<span class="header-trim form-value vehicle-save" data-name="trim">' . $vehicle['trim'] . '</span>';
				$content .= '</a>';
				$content .= '</div>';

				// Left.
				$content .= '<div class="inventory-vehicle-inner-left-container">';
				$content .= '<div class="inventory-vehicle-image">';
				$image   = $this->fn_inventory->no_photo_replace( $vehicle['thumbnail'] );
				$content .= ( isset( $vehicle['video'] ) && $vehicle['video'] ? '<div class="list-video-play-icon" onclick=\'window.open("' . $vehicle['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\'></div>' : '' );
				$content .= '<a class="vehicle-save" name="link" href="' . $link . '" class="image-link">';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content .= ! empty( $vehicle['sold_on'] ) ? '<img class="marked-sold-overlay" src="' . CDP_IMG . 'templates/inventory/sold_overlay.png" />' : '';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content .= '<img title="' . $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'] . ' Located at ' . $vehicle['dealer'] . '" alt="Thumbnail - ' . $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'] . '" class="vehicle-image vehicle-save" data-name="image" src="' . str_replace( '_small', '_medium', $image ) . '" itemprop="image" /></a>';
				$content .= '</div>';
				$content .= '<div class="inventory-vehicle-contact" itemprop="brand" itemscope itemtype="https://schema.org/AutoDealer">';
				$content .= '<div class="dealer-contact-wrapper">';
				$content .= $this->contact_wrapper( $vehicle, $company );
				$content .= '</div>';
				$content .= '</div>';
				$content .= '</div>';
				// Middle start.
				$content .= '<div class="inventory-vehicle-inner-middle-container">';
				$content .= '<div class="vehicle-information-attributes">';
				$content .= Vehicle_Attributes::call(
					array(
						'row_color' => true,
						'vehicle'   => $vehicle,
						'layout'    => 'list',
						'page'      => 'list',
					)
				);
				$content .= '</div>';

				if ( ! empty( self::$theme_options['theme']['inventory_display']['general']['saved_vehicles']['display'] ) ) {
					if ( ! empty( self::$saved_vehicles ) ) {
						$save_class = ( array_key_exists( $vehicle['vin'], self::$saved_vehicles ) ? 'checked' : '' );
					} else {
						$save_class = '';
					}

					if ( ! empty( self::$compared_vehicles ) ) {
						$compare_class = ( array_key_exists( $vehicle['vin'], self::$compared_vehicles ) ? 'checked' : '' );
					} else {
						$compare_class = '';
					}
					$content .= '<div class="saved-compare-container">';
					$content .= '<div class="info-item saved-vehicles-container">';
					$content .= '<div class="inventory-vehicle-save ' . $save_class . '">';
					$content .= '<span class="save-text">' . ( empty( $save_class ) ? 'Save Vehicle' : 'Vehicle Saved' ) . '</span>';
					$content .= '<span class="save-checkbox">' . ( empty( $save_class ) ? '' : 'X' ) . '</span>';
					$content .= '</div>';
					$content .= '</div>';

					$content .= '<div class="info-item compare-vehicles-container">';
					$content .= '<div class="inventory-vehicle-compare ' . $compare_class . '">';
					$content .= '<span class="compare-text">' . ( empty( $compare_class ) ? 'Compare Vehicle' : 'Remove Compare' ) . '</span>';
					$content .= '<span class="compare-checkbox">' . ( empty( $compare_class ) ? '' : 'X' ) . '</span>';
					$content .= '</div>';
					$content .= '</div>';
					$content .= '</div>';
				}
				$content .= '</div>';

				// Right.
				$content     .= '<div class="inventory-vehicle-inner-right-container">';
				$price       = $this->fn_inventory->get_price_display(
					array(
						'company' => $company,
						'vehicle' => $vehicle,
						'theme'   => 'inventory',
					)
				);
				$content .= ( ( new Prices($vehicle) )->price_box());

				$loan_parameters = array(
					'make'      => $vehicle['make'],
					'model'     => $vehicle['model'],
					'trim'      => $vehicle['trim'],
					'year'      => $vehicle['year'],
					'saleclass' => $vehicle['saleclass'],
				);
				$content         .= '<div class="price-item price-loan-payment">' . $this->fn_inventory->get_loan_value( self::$theme_options['theme']['inventory_display']['payment_calculator'], $price['primary_price'], $loan_parameters ) . '</div>';
				// revamp with for position.
				$buttons = Option::check_for_option(
					'cdp_theme_options',
					array(
						'theme',
						'inventory_display',
						'list',
						'general',
						'buttons',
					)
				);
				$box     = $this->extender_clean_box_data( $vehicle, 'list_box' );
				if ( ! empty( $buttons['box']['content'] ) ) {
					$content .= '<div class="list-button-box">' . $box['content'] . '</div>';
				}
				$content .= '<div class="vdp-form-buttons">';
				$content .= '<div class="price-item price-information"><a href="' . $link . '">' . ( empty( $buttons['vdp_link']['name'] ) ? 'More Information' : $buttons['vdp_link']['name'] ) . '</a></div>';
				if ( ! empty( $buttons['form']['gform_id'] ) ) {
					$content .= '<div class="price-item price-form" data-key="' . $vehicle['vin'] . '">' . ( empty( $buttons['form']['name'] ) ? 'Get ePrice' : $buttons['form']['name'] ) . '</div>';
				}
				$content .= '</div>'; // end vdp-form buttons
				// revamp with for position temp note.
				// Mobile Contact.
				$content .= '<div class="dealer-contact-mobile-wrapper">';
				$content .= $this->contact_wrapper( $vehicle, $company );
				$content .= '</div>';
				$content .= '</div>'; // end right
				// Bottom.
				$content .= '<div class="inventory-vehicle-inner-bottom-container">';
				$content .= '<div class="bottom-form-holder"></div>';
				if ( self::$theme_options['theme']['inventory_display']['tags']['display_tags'] ) {
					if ( ! empty( $vehicle['tags'] ) ) {
						$content .= '<div class="bottom-item extra-item bottom-tags">';
						$content .= $this->fn_inventory->build_tag_icons( $vehicle['tags'], $vehicle['vin'] );
						$content .= '</div>';
					} else {
						$content .= '<div class="bottom-item extra-item item-one">' . ( $boxes['box_one'] ?? '' ) . '</div>';
					}
				} else {
					$content .= '<div class="bottom-item extra-item item-one">' . ( $boxes['box_one'] ?? '' ) . '</div>';
				}
				$boxes   = $this->extender_clean_box_data( $vehicle, 'list' );
				$content .= '<div class="bottom-item extra-item item-two">';
				if ( $vehicle['autocheck'] || $vehicle['carfax'] ) {
					$content .= ( $vehicle['autocheck'] ? $this->fn_inventory->display_autocheck_image( $vehicle['vin'], $vehicle['saleclass'], 'list' ) : '' );
					if ( ! empty( $vehicle['carfax'] ) || 'used' === strtolower( $vehicle['saleclass'] ) ) {
						$content .= $this->fn_inventory->cdp_display_carfax( $vehicle['vin'], $vehicle['carfax'], $vehicle['carfax_image_url'], 'list' );
					}
				} else {
					$content .= ( $boxes['box_two'] ?? '' );
				}
				$content .= '</div>';
				$content .= '<div class="bottom-item extra-item item-three">' . ( $boxes['box_three'] ?? '' ) . '</div>';
				$content .= '<div class="bottom-item extra-item item-four">' . ( $boxes['box_four'] ?? '' ) . '</div>';
				$content .= '</div>';
				$content .= '</div>';
				$content .= '</div>';
			}
			$content .= '</div>';

		}

		return $content;
	}

	public function extender_vehicle_list_page_no_results() {
		$content                   = '<div class="inventory-vehicle-page active error">';
		$content                   .= '<div class="list-no-results-container">';
		$content                   .= '<div class="list-no-results-image"></div>';
		$gform_no_results_found_id = self::$theme_options['theme']['inventory_display']['list']['general']['no_results_form'];
		if ( empty( self::$theme_options['theme']['inventory_display']['list']['general']['no_results_form_text'] ) ) {
			$content .= '<div class="list-no-results-text">Sorry, no results found. Please modify your selection in the filters, remove existing filters ';
			$content .= $gform_no_results_found_id ? ', or fill out the short form below and we will notify you when your vehicle becomes available.' : '.';
			$content .= '</div>';
		} else {
			$content .= '<div>' . urldecode( stripslashes( self::$theme_options['theme']['inventory_display']['list']['general']['no_results_form_text'] ) ) . '</div>';
		}
		$content .= '<div class="inventory-not-found"><h3><a onClick="history.go(-1)" title="Return to Previous Search" class="jquery-ui-button">Return to Previous Search</a></h3></div>';
		if ( function_exists( 'gravity_form' ) ) {
			$content .= ( empty( $gform_no_results_found_id ) ? '' : '<div class="list-no-results-form">' . gravity_form( $gform_no_results_found_id, $display_title = false, $display_description = false, $display_inactive = false, $field_values = false, $ajax = true, $tabindex = 0, $echo = false ) . '</div>' );
		}
		$content .= '</div>';
		$content .= '</div>';

		return $content;
	}

	public function detail_page_sold_vehicle( $vehicle ) {
		if ( $vehicle['sold_on'] ) {
			$content            = '<div id="inventory-detail-not-found-container">';
			$url_rule = isset( $rules['^(inventory)'] );
			if ( $url_rule ) {
				$link = site_url() . '/inventory/' . $vehicle['saleclass'];
			} else {
				$link = site_url() . '?taxonomy=inventory&saleclass=' . $vehicle['saleclass'];
			}
			$content .= '<div class="inventory-not-found"><button title="Go to main inventory" class="detail-return-to-inventory-link" href=' . $link . '>Go to main inventory Search</button></div>';
			$title              = $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'];
			$gform_sold_form_id = Option::check_for_option(
				'cdp_theme_options',
				array(
					'theme',
					'inventory_display',
					'detail',
					'general',
					'vehicle_sold_form_id',
				)
			);
			$gform_sold_text    = Option::check_for_option(
				'cdp_theme_options',
				array(
					'theme',
					'inventory_display',
					'detail',
					'general',
					'vehicle_sold_form_text',
				), 'The ' . $title . ' is no longer available.'
			);
			$content            .= '<div class="detail-no-results-text">' . urldecode( stripslashes( $gform_sold_text ) ) . '</div>';
			if ( function_exists( 'gravity_form' ) ) {
				$content .= ( empty( $gform_sold_form_id ) ? '' : '<div class="detail-no-results-form">' . gravity_form( $gform_sold_form_id, $display_title = false, $display_description = false, $display_inactive = false, $field_values = false, $ajax = true, $tabindex = 0, $echo = false ) . '</div>' );
			}
			$content .= '</div>';

			return $content;
		}
	}

	public function extender_inventory_list_view_grid() {
		$location_id = 0;
		$companies   = $this->db_request->cdp_db_init( 'company' );
		$company     = array();
		$vehicles    = $this->db_request->cdp_db_init( 'inventory', self::$passed_parameters );

		if ( empty( $vehicles ) ) {
			$content = $this->extender_vehicle_list_page_no_results();
		} else {
			$content = '<div class="inventory-vehicle-page page-' . ( self::$passed_parameters['page'] ?? '1' ) . ' active">';
			$content .= '<div class="inventory-vehicle-wrapper-grid">';

			foreach ( $vehicles as $vehicle ) {
				$link_params = array(
					'year'   => $vehicle['year'],
					'make'   => $vehicle['make'],
					'model'  => $vehicle['model'],
					'state'  => $vehicle['geo_state'],
					'city'   => $vehicle['geo_city'],
					'vin'    => $vehicle['vin'],
					'vms_id' => $vehicle['vms_id'],
				);
				if ( empty( $vehicle['sold_on'] ) ) {
					$link = $this->fn_inventory->generate_inventory_link( array('params' => $link_params, 'type' => 1 ) );
				} else {
					$link = '';
				}
				if ( $location_id !== $vehicle['dealer_id'] || empty( $company ) ) {
					$location_id = $vehicle['dealer_id'];
					foreach ( $companies as $key => $info ) {
						if ( $location_id === $info['dealer_id'] ) {
							$company = $info;
						}
					}
				}
				$content .= '<div id="' . $vehicle['vin'] . '" class="grid vehicle-container vehicle-saleclass-' . strtolower( $vehicle['saleclass'] ) . ' company-' . $vehicle['company_id'] . ' location-' . $vehicle['dealer_id'] . '" itemscope itemtype="https://schema.org/Car">';
				$content .= '<div class="inventory-vehicle-container">';
				// 2nd Tier - Photo.
				$content .= '<div class="nested inventory-vehicle-tier-photo">';
				$content .= '<div class="inventory-vehicle-image">';
				$image   = $this->fn_inventory->no_photo_replace( $vehicle['thumbnail'] );
				$content .= ( isset( $vehicle['video'] ) && $vehicle['video'] ? '<div class="list-video-play-icon" onclick=\'window.open("' . $vehicle['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\'></div>' : '' );
				$content .= '<a class="vehicle-save" name="link" href="' . $link . '" class="image-link">';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content .= ! empty( $vehicle['sold_on'] ) ? '<img class="marked-sold-overlay" src="' . CDP_IMG . 'templates/inventory/sold_overlay.png" />' : '';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content .= '<img title="' . $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'] . ' Located at ' . $vehicle['dealer'] . '" alt="Thumbnail - ' . $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'] . '" class="vehicle-image vehicle-save" data-name="image" src="' . str_replace( '_small', '_medium', $image ) . '" itemprop="image" /></a>';
				$content .= '</div>';
				$content .= '</div>';
				// Tier - header/headline.
				$content .= '<div class="nested inventory-vehicle-titles">';
				$content .= ( empty( $vehicle['headline'] ) ? '' : '<div class="inventory-vehicle-headline">' . $vehicle['headline'] . '</div>' );
				$content .= '<div class="inventory-vehicle-header" itemprop="name">';
				$content .= '<a href="' . $link . '">';
				$content .= '<div class="header-year-make-model-trim">';
				$content .= '<span class="header-year form-value vehicle-save" data-name="year" itemprop="modelDate">' . $vehicle['year'] . '</span>';
				$content .= '<span class="header-make form-value vehicle-save" data-name="make" itemprop="manufacturer">' . $vehicle['make'] . '</span>';
				$content .= '<span class="header-model form-value vehicle-save" data-name="model" itemprop="model">' . $vehicle['model'] . '</span>';
				$content .= '<span class="header-trim form-value vehicle-save" data-name="trim">' . $vehicle['trim'] . '</span>';
				$content .= '</div>';
				$content .= '</a>';
				$content .= '</div>';
				$content .= '</div>';
				// Dealer Contact.
				$content .= '<div class="nested inventory-vehicle-tier-dealer-name" itemprop="brand" itemscope itemtype="https://schema.org/AutoDealer">';
				$content .= '<div class="dealer-contact-wrapper">';
				$content .= $this->contact_wrapper( $vehicle, $company );
				$content .= '</div>';
				$content .= '</div>';

				// Price Display.
				$content     .= '<div class="nested inventory-vehicle-tier-pricing">';
				$price       = $this->fn_inventory->get_price_display(
					array(
						'company' => $company,
						'vehicle' => $vehicle,
						'theme'   => 'inventory',
					)
				);
				$content .= ( ( new Prices($vehicle) )->price_box());

				$loan_parameters = array(
					'make'      => $vehicle['make'],
					'model'     => $vehicle['model'],
					'trim'      => $vehicle['trim'],
					'year'      => $vehicle['year'],
					'saleclass' => $vehicle['saleclass'],
				);
				$content         .= '<div class="price-item price-loan-payment">' . $this->fn_inventory->get_loan_value( self::$theme_options['theme']['inventory_display']['payment_calculator'], $price['primary_price'], $loan_parameters ) . '</div>';

				$buttons = Option::check_for_option(
					'cdp_theme_options',
					array(
						'theme',
						'inventory_display',
						'list',
						'general',
						'buttons',
					)
				);
				$box     = $this->extender_clean_box_data( $vehicle, 'list_box' );
				if ( ! empty( $buttons['box']['content'] ) ) {
					$content .= '<div class="list-button-box">' . $box['content'] . '</div>';
				}
				$content .= '<div class="vdp-form-buttons">';
				$content .= '<div class="price-item price-information"><a href="' . $link . '">' . ( empty( $buttons['vdp_link']['name'] ) ? 'More Information' : $buttons['vdp_link']['name'] ) . '</a></div>';
				if ( ! empty( $buttons['form']['gform_id'] ) ) {
					$content .= '<div class="price-item price-form" data-key="' . $vehicle['vin'] . '">' . ( empty( $buttons['form']['name'] ) ? 'Get ePrice' : $buttons['form']['name'] ) . '</div>';
				}
				$content .= '</div>'; // end vdp-form-buttons

				$content .= '</div>'; // end price display

				$content .= '<div class="nested vehicle-information-attributes">';
				$content .= Vehicle_Attributes::call(
					array(
						'vehicle' => $vehicle,
						'layout'  => 'list',
						'page'    => 'list',
					)
				);
				$content .= '</div>';

				if ( ! empty( self::$theme_options['theme']['inventory_display']['general']['saved_vehicles']['display'] ) ) {
					if ( ! empty( self::$saved_vehicles ) ) {
						$save_class = ( array_key_exists( $vehicle['vin'], self::$saved_vehicles ) ? 'checked' : '' );
					} else {
						$save_class = '';
					}
					if ( ! empty( self::$compared_vehicles ) ) {
						$compare_class = ( array_key_exists( $vehicle['vin'], self::$compared_vehicles ) ? 'checked' : '' );
					} else {
						$compare_class = '';
					}
					$content .= '<div class="nested inventory-vehicle-tier-save-compare-vehicles">';
					$content .= '<div class="info-item saved-vehicles-container">';
					$content .= '<div class="inventory-vehicle-save ' . $save_class . '">';
					$content .= '<span class="save-text">' . ( empty( $save_class ) ? 'Save Vehicle' : 'Vehicle Saved' ) . '</span>';
					$content .= '<span class="save-checkbox">' . ( empty( $save_class ) ? '' : 'X' ) . '</span>';
					$content .= '</div>';
					$content .= '</div>';

					$content .= '<div class="info-item compare-vehicles-container">';
					$content .= '<div class="inventory-vehicle-compare ' . $compare_class . '">';
					$content .= '<span class="compare-text">' . ( empty( $compare_class ) ? 'Compare Vehicle' : 'Remove Compare' ) . '</span>';
					$content .= '<span class="compare-checkbox">' . ( empty( $compare_class ) ? '' : 'X' ) . '</span>';
					$content .= '</div>';
					$content .= '</div>';
					$content .= '</div>';
				}

				$content .= '<div class="inventory-vehicle-left-bottom">';
				$content .= '</div>';

				// Mobile Contact.
				$content .= '<div class="nested dealer-contact-mobile-wrapper">';
				$content .= $this->contact_wrapper( $vehicle, $company );
				$content .= '</div>';

				// Bottom Extra Boxes.
				$content .= '<div class="nested inventory-vehicle-tier-extra-boxes inventory-vehicle-inner-bottom-container">';
				$content .= '<div class="bottom-form-holder"></div>';
				if ( self::$theme_options['theme']['inventory_display']['tags']['display_tags'] ) {
					if ( ! empty( $vehicle['tags'] ) ) {
						$content .= '<div class="bottom-item extra-item bottom-tags">';
						$content .= $this->fn_inventory->build_tag_icons( $vehicle['tags'], $vehicle['vin'] );

						$content .= '</div>';
					}
				}
				$boxes   = $this->extender_clean_box_data( $vehicle, 'list' );
				$content .= '<div class="bottom-item extra-item item-two">';
				if ( $vehicle['autocheck'] || $vehicle['carfax'] ) {
					$content .= ( $vehicle['autocheck'] ? $this->fn_inventory->display_autocheck_image( $vehicle['vin'], $vehicle['saleclass'], 'list' ) : '' );
					if ( ! empty( $vehicle['carfax'] ) || 'used' === strtolower( $vehicle['saleclass'] ) ) {
						$content .= $this->fn_inventory->cdp_display_carfax( $vehicle['vin'], $vehicle['carfax'], $vehicle['carfax_image_url'], 'list' );
					}
				} else {
					$content .= ( $boxes['box_two'] ?? '' );
				}
				$content .= '</div>';
				$content .= '<div class="bottom-item extra-item item-three">' . ( $boxes['box_three'] ?? '' ) . '</div>';
				$content .= '<div class="bottom-item extra-item item-four">' . ( $boxes['box_four'] ?? '' ) . '</div>';
				$content .= '</div>';

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

		return $content;
	}

	public function extender_detail_top_view( $vehicle, $price, $company ) {
		$content = ( empty( $vehicle['headline'] ) ? '' : '<div class="detail-top top-inner-top"><span class="inventory-detail-vehicle-headline">' . $vehicle['headline'] . '</span></div>' );
		$content .= '<div class="detail-top top-inner-left">';
		$content .= '<h1 class="detail-vehicle-header" itemprop="name">';
		$content .= '<span class="header-year form-value vehicle-save" data-name="year" itemprop="modelDate">' . $vehicle['year'] . '</span> ';
		$content .= '<span class="header-make form-value vehicle-save" data-name="make" itemprop="manufacturer">' . $vehicle['make'] . '</span> ';
		$content .= '<span class="header-model form-value vehicle-save" data-name="model" itemprop="model">' . $vehicle['model'] . '</span>';
		$content .= '<span class="header-trim form-value vehicle-save" data-name="trim">' . $vehicle['trim'] . '</span>';
		$content .= '</h1>';
		$content .= '<div class="detail-vehicle-contact" itemprop="brand" itemscope itemtype="https://schema.org/AutoDealer">';
		$content .= '<div class="dealer-contact-wrapper">';
		$content .= $this->contact_wrapper( $vehicle, $company, 'detail' );
		$content .= '</div>';
		$content .= '</div>';
		$content .= '</div>';
		$content .= '<div class="detail-top top-inner-right">';
		$content .= ( new Prices($vehicle) )->price_box_detail_view();
		$content .= '</div>';

		return $content;
	}

	public function extender_detail_body_view( $vehicle ) {
		$content = '<div class="detail-body detail-body-inner-left">';
		$content .= ( new Image_Display() )->detail_thumb_bottom( $vehicle );
		$content .= '</div>';
		$content .= '<div class="detail-body detail-body-inner-right">';
		$content .= '<div class="vehicle-information-attributes">';
		$content .= Vehicle_Attributes::call(
			array(
				'row_color' => true,
				'vehicle'   => $vehicle,
				'layout'    => 'list',
				'page'      => 'detail',
			)
		);
		if ( ! empty( self::$theme_options['theme']['inventory_display']['general']['saved_vehicles']['display'] ) ) {
			if ( ! empty( self::$saved_vehicles ) ) {
				$save_class = ( array_key_exists( $vehicle['vin'], self::$saved_vehicles ) ? 'checked' : '' );
			} else {
				$save_class = '';
			}

			if ( ! empty( self::$compared_vehicles ) ) {
				$compare_class = ( array_key_exists( $vehicle['vin'], self::$compared_vehicles ) ? 'checked' : '' );
			} else {
				$compare_class = '';
			}
			$content .= '<div class="info-item saved-vehicles-container">';
			$content .= '<div class="inventory-vehicle-save ' . $save_class . '">';
			$content .= '<span class="save-text">' . ( empty( $save_class ) ? 'Save Vehicle' : 'Vehicle Saved' ) . '</span>';
			$content .= '<span class="save-checkbox">' . ( empty( $save_class ) ? '' : 'X' ) . '</span>';
			$content .= '</div>';
			$content .= '</div>';

			$content .= '<div class="info-item compare-vehicles-container">';
			$content .= '<div class="inventory-vehicle-compare ' . $compare_class . '">';
			$content .= '<span class="compare-text">' . ( empty( $compare_class ) ? 'Compare Vehicle' : 'Remove Compare' ) . '</span>';
			$content .= '<span class="compare-checkbox">' . ( empty( $compare_class ) ? '' : 'X' ) . '</span>';
			$content .= '</div>';
			$content .= '</div>';
		}
		$content .= '</div>';

		$content .= '<div class="detail-tab-container">';
		$content .= $this->extender_detail_action_tabs( $vehicle );
		$content .= '</div>';
		$content .= '</div>';
		$content .= '<div class="detail-body detail-body-inner-bottom">';
		if ( self::$theme_options['theme']['inventory_display']['tags']['display_tags'] ) {
			if ( ! empty( $vehicle['tags'] ) ) {
				$content .= '<div class="detail-bottom-item item-one bottom-tags">';
				$content .= $this->fn_inventory->build_tag_icons( $vehicle['tags'], $vehicle['vin'] );
				$content .= '</div>';
			} else {
				$content .= '<div class="detail-bottom-item item-one"></div>';
			}
		} else {
			$content .= '<div class="detail-bottom-item item-one"></div>';
		}
		$boxes   = $this->extender_clean_box_data( $vehicle, 'detail' );
		$content .= '<div class="detail-bottom-item extra-item item-two">';
		if ( $vehicle['autocheck'] || $vehicle['carfax'] ) {
			$content .= ( $vehicle['autocheck'] ? $this->fn_inventory->display_autocheck_image( $vehicle['vin'], $vehicle['saleclass'], 'detail' ) : '' );
			if ( ! empty( $vehicle['carfax'] ) || 'used' === strtolower( $vehicle['saleclass'] ) ) {
				$content .= $this->fn_inventory->cdp_display_carfax( $vehicle['vin'], $vehicle['carfax'], $vehicle['carfax_image_url'], 'detail' );
			}
		} else {
			$content .= ( empty( $boxes['box_two'] ) ? '' : $boxes['box_two'] );
		}
		$content .= '</div>';
		$content .= '<div class="detail-bottom-item extra-item item-three">' . ( empty( $boxes['box_three'] ) ? '' : $boxes['box_three'] ) . '</div>';
		$content .= '<div class="detail-bottom-item extra-item item-four">' . ( empty( $boxes['box_four'] ) ? '' : $boxes['box_four'] ) . '</div>';
		$content .= '<div class="detail-bottom-item vehicle-information-container">';
		$content .= $this->extender_detail_info_tabs( $vehicle );
		$content .= '</div>';
		$content .= '</div>';

		return $content;
	}

	public function extender_saved_vehicles() {
		self::$saved_vehicles = array();
		foreach ( $_COOKIE as $key => $value ) {
			if ( strpos( $key, 'vehicleSave' ) !== false ) {
				self::$saved_vehicles[ str_replace( 'CDPvehicleSave_', '', $key ) ] = $value;
			}
		}
	}

	public function extender_saved_vehicle_container() {
		$this->extender_saved_vehicles();
		$class   = ( count( self::$saved_vehicles ) > 0 ? 'saved' : 'empty' );
		$content = '<div id="saved-vehicle-container">';
		$content .= '<div id="saved-vehicle-count-container" class="' . $class . '" >View Saved Vehicles (<span id="saved-vehicle-count">' . count( self::$saved_vehicles ) . '</span>)</div>';
		$content .= '</div>';

		return $content;
	}

	public function extender_compared_vehicles() {
		self::$compared_vehicles = array();
		foreach ( $_COOKIE as $key => $value ) {
			if ( strpos( $key, 'vehicleCompare' ) !== false ) {
				self::$compared_vehicles[ str_replace( 'CDPvehicleCompare_', '', $key ) ] = $value;
			}
		}
	}

	public function extender_compare_vehicle_container() {
		$i = 1;
		$this->extender_compared_vehicles();
		$class   = ( count( self::$compared_vehicles ) > 0 ? 'visible' : 'empty' );
		$content = '<div id="compare-vehicle-container" class="' . $class . '">';
		$content .= '<div id="compare-under-count" style="display:none;">At least two vehicles must be selected before comparing.</div>';
		$content .= '<div id="compare-over-count" style="display:none;">Can only compare 5 vehicles at a time. Remove before adding a new vehicle.</div>';
		if ( count( self::$compared_vehicles ) > 0 ) {
			foreach ( self::$compared_vehicles as $key => $values ) {
				$data    = json_decode( stripslashes( $values ) );
				$content .= '<div class="compare-item item-' . $i . ' compare-' . $key . '">';
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content .= '<div class="compare-main"><img src="' . $data->image . '" alt="compare-img"/></div>';
				$content .= '<div class="compare-sub" style="display:none;">';
				$content .= '<span class="compare-saleclass">' . $data->saleclass . '</span>';
				$content .= '<span class="compare-year">' . $data->year . '</span>';
				$content .= '</br><span class="compare-make">' . $data->make . '</span>';
				$content .= '<span class="compare-model">' . $data->model . '</span>';
				$content .= '</br><span class="compare-trim">' . $data->trim . '</span>';
				$content .= '</div>';
				$content .= '<div class="compare-remove" data-key="' . $key . '">Remove [X]</div>';
				$content .= '</div>';
				$i ++;
			}
		}
		while ( $i <= 5 ) { // Only load 5 spaces.
			$content .= '<div class="compare-item item-' . $i . ' empty"></div>';
			$i ++;
		}
		$content .= '<div id="compare-vehicle-count-container" class="compare-item"><div id="compare-button">View Compared</br>Vehicles (<span id="compare-vehicle-count">' . count( self::$compared_vehicles ) . '</span>)</div></div>';
		$content .= '</div>';

		return $content;
	}

	public function extender_clean_box_data( $vehicle, $page ) {
		$output       = array();
		$boxes        = array();
		$both_boxes   = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'general',
				'both',
				'extra_boxes',
			)
		);
		$list_boxes   = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'list',
				'extra_boxes',
			)
		);
		$detail_boxes = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'detail',
				'extra_boxes',
			)
		);
		$box_content  = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'list',
				'general',
				'buttons',
				'box',
				'content',
			)
		);
		switch ( true ) {
			case 'list' === $page:
				$boxes = array_merge( $both_boxes, array_filter( $list_boxes ) );
				break;
			case 'detail' === $page:
				$boxes = array_merge( $both_boxes, array_filter( $detail_boxes ) );
				break;
			case 'list_box' === $page:
				$boxes = array( 'content' => $box_content );
				break;
		}
		foreach ( $boxes as $key => $data ) {
			$raw_data       = rawurldecode( stripslashes( $data ) );
			$raw_data       = str_replace( '[VIN]', $vehicle['vin'], $raw_data );
			$raw_data       = str_replace( '[STOCK]', $vehicle['stock'], $raw_data );
			$raw_data       = str_replace( '[DEALER]', $vehicle['dealer_id'], $raw_data );
			$output[ $key ] = $raw_data;
		}

		return $output;
	}

	public function extender_detail_info_tabs( $vehicle ) {
		$content            = $tab_labels = $tab_content = $options = '';
		$class              = 'active';
		$tab_layout_options = $tab_layout_description = array(
			'label'   => '',
			'content' => '',
		);
		$value              = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'detail',
				'general',
				'default_info_tab',
			)
		);

		if ( strcasecmp( $value, 'Options' ) === 0 ) {
			if ( ! empty( $vehicle['dealer_options'] ) ) {
				sort( $vehicle['dealer_options'] );
				$tab_layout_options = $this->tab_layout(
					array(
						'idx'            => '0',
						'class'          => $class,
						'tab_name'       => 'Vehicle Options',
						'dealer_options' => $vehicle['dealer_options'],
					)
				);
				$class              = '';
			}
			if ( ! empty( $vehicle['description'] ) ) {
				$tab_layout_description = $this->tab_layout(
					array(
						'idx'      => '1',
						'class'    => $class,
						'tab_name' => 'Vehicle Notes',
						'data'     => $vehicle['description'],
					)
				);
				$class                  = '';
			}
			$tab_labels  = $tab_layout_options['label'] . $tab_layout_description['label'];
			$tab_content = $tab_layout_options['content'] . $tab_layout_description['content'];
		} else {
			if ( ! empty( $vehicle['description'] ) ) {
				$tab_layout_description = $this->tab_layout(
					array(
						'idx'      => '0',
						'class'    => $class,
						'tab_name' => 'Vehicle Notes',
						'data'     => $vehicle['description'],
					)
				);
				$class                  = '';
			}
			if ( ! empty( $vehicle['dealer_options'] ) ) {
				sort( $vehicle['dealer_options'] );
				$tab_layout_options = $this->tab_layout(
					array(
						'idx'            => '1',
						'class'          => $class,
						'tab_name'       => 'Vehicle Options',
						'dealer_options' => $vehicle['dealer_options'],
					)
				);
				$class              = '';
			}
			$tab_labels  = $tab_layout_description['label'] . $tab_layout_options['label'];
			$tab_content = $tab_layout_description['content'] . $tab_layout_options['content'];
		}

		if ( self::$theme_options['theme']['inventory_display']['detail']['general']['show_standard_eq'] ) {
			$equipment = $this->fn_inventory->display_equipment( $vehicle['standard_equipment'], $vehicle['saleclass'] );
			if ( ! empty( $equipment ) ) {
				$tab_labels  .= '<div id="info-tab-2" class="tab-name ' . $class . '">Standard Equipment</div>';
				$tab_content .= '<div id="info-tab-2-content" class="tab-content ' . $class . '"><div class="tab-mobile-button">Standard Equipment <span class="tab-mobile-icon open"></span> </div><div class="standard-equipment-container tab-content-inner">' . $equipment . '</div></div>';
				$class       = '';
			}
		}

		$content .= ( empty( $tab_labels ) ? '' : '<div class="tab-name-container">' . $tab_labels . '</div>' );
		$content .= ( empty( $tab_content ) ? '' : '<div class="tab-content-container">' . $tab_content . '</div>' );

		return $content;
	}

	public function tab_layout( $args ) {
		$tab_label   = '<div id="info-tab-' . $args['idx'] . '" class="tab-name ' . $args['class'] . '">' . $args['tab_name'] . '</div>';
		$tab_content = '<div id="info-tab-' . $args['idx'] . '-content" class="tab-content ' . $args['class'] . '">';
		$tab_content .= '<div class="tab-mobile-button">' . $args['tab_name'] . ' <span class="tab-mobile-icon open"></span> </div>';
		if ( isset( $args['dealer_options'] ) ) {
			$options = '';
			foreach ( $args['dealer_options'] as $option ) {
				$options .= '<div class="dealer-option"><span class="spacer">' . $option . '</span></div>';
			}
			$tab_content .= '<div class="dealer-option-container tab-content-inner">' . $options . '</div></div>';
		} else {
			$tab_content .= '<div class="dealer-notes-container tab-content-inner" itemprop="description">' . $args['data'] . '</div></div>';
		}

		return array(
			'label'   => $tab_label,
			'content' => $tab_content,
		);
	}

	public function extender_detail_action_tabs( $vehicle ) {
		$content = $tab_labels = $tab_content = '';
		$tabs    = array();
		$class   = 'active';
		$counter = 0;
		$tabs[]  = $this->extender_detail_forms( $vehicle );
		$tabs[]  = $this->extender_detail_loan( $vehicle );

		foreach ( $tabs as $tab => $data ) {
			if ( ! empty( $data ) ) {
				foreach ( $data as $item ) {
					$name = esc_html( $item['name'] );
					$form = $item['content'];

					$tab_labels  .= '<div id="body-tab-' . $counter . '" class="tab-name ' . $class . '">' . $name . '</div>';
					$tab_content .= '<div id="body-tab-' . $counter . '-content" class="tab-content ' . $class . '">';
					$tab_content .= '<div class="tab-mobile-button">' . $name . ' <span class="tab-mobile-icon open"></span> </div>';
					$tab_content .= '<div class="tab-content-inner">' . $form . '</div></div>';

					$class = '';
					$counter++;
				}
			}
		}
		$content .= ( empty( $tab_labels ) ? '' : '<div class="tab-name-container">' . $tab_labels . '</div>' );
		$content .= ( empty( $tab_content ) ? '' : '<div class="tab-content-container">' . $tab_content . '</div>' );

		return $content;
	}

	public function extender_detail_forms( $vehicle ) {
		$results = array();
		if ( function_exists( 'gravity_form' ) ) {
			$saleclass = ( 'new' === strtolower( $vehicle['saleclass'] ) ? 'new' : 'used' );
			$forms     = Option::check_for_option(
				'cdp_theme_options',
				array(
					'theme',
					'inventory_display',
					'detail',
					'forms',
				)
			);
			if ( ! empty( $forms[0] ) ) {
				foreach ( $forms as $key => $form ) {
					$form_id = $form['id'];
					$form_code = gravity_form( $form_id, $display_title = false, $display_description = false, $display_inactive = false, $field_values = false, $ajax = true, $tabindex = 0, $echo = false );
					if ( empty( $form['saleclass'] ) || $form['saleclass'] === $saleclass || 'all' === $form['saleclass'] ) {
						$results[] = array(
							'name'    => esc_html($form['title']),
							'content' => $form_code,
						);
					}
				}
			}
		}

		return $results;
	}

	public function extender_detail_loan( $vehicle ) {
		$results         = array();
		$loan_parameters = array(
			'make'      => $vehicle['make'],
			'model'     => $vehicle['model'],
			'trim'      => $vehicle['trim'],
			'year'      => $vehicle['year'],
			'saleclass' => $vehicle['saleclass'],
		);
		$loan_results[0] = array(
			'name'    => 'Payment Calculator',
			'content' => $this->fn_inventory->get_loan_calculator( self::$theme_options['theme']['inventory_display']['payment_calculator'], $vehicle['primary_price'], false, $loan_parameters ),
		);
		$results         = ( empty( $loan_results[0]['content'] ) ? array() : $loan_results );

		return $results;
	}

	public function extender_similar_vehicle_pull( $vehicle ) {
		$content = '';
		if ( ! empty( $vehicle['vehicleclass'] ) ) {
			$similar = array(
				'search_sim'   => 1,
				'photo_view'   => 1,
				'per_page'     => 4,
				'saleclass'    => $vehicle['saleclass'],
				'vehicleclass' => rawurlencode( $vehicle['vehicleclass'] ),
			);
			// Price Check.
			$price_from = ( max( $vehicle['primary_price'] - self::$theme_options['theme']['inventory_display']['detail']['similar_vehicles']['price_subtract'], 0 ) );
			$price_to   = ( max( $vehicle['primary_price'] - self::$theme_options['theme']['inventory_display']['detail']['similar_vehicles']['price_add'], 0 ) );
			if ( ! empty( $price_to ) && $price_from >= 0 ) {
				$similar['price_from'] = $price_from;
				$similar['price_to']   = $price_to;
			} else {
				$similar['make'] = $vehicle['make'];
			}
			// Make Filter Check.
			if ( 0 === strcasecmp( $vehicle['saleclass'], 'new' ) && ! empty( self::$theme_options['theme']['overrides']['makes_new']['included'] ) ) {
				$similar = array_merge( $similar, array( 'make_filters' => self::$theme_options['theme']['overrides']['makes_new']['included'] ) );
			}
			// Get Inventory.
			self::$passed_parameters = $similar;
			$inventory               = $this->extender_inventory_pull();
			if ( 0 === count( $inventory ) && isset( self::$passed_parameters['price_from'] ) ) {
				unset( self::$passed_parameters['price_from'] );
				unset( self::$passed_parameters['price_to'] );
				self::$passed_parameters['make'] = $vehicle['make'];
				$inventory                       = $this->extender_inventory_pull();
			}
			# $inventory returns $vehicle along with any matches
			# if no matches, $vehicle is the only thing returned.
			if ( count( $inventory ) > 1 ) {
				$content = $this->extender_similar_vehicle_view( $inventory, $vehicle );
			} else {
				$content = '<!-- No Similar Vehicles Found -->';
			}
		}

		return $content;
	}

	public function extender_similar_vehicle_view( $vehicles, $parent ) {
		$content     = '<div class="similar-vehicle-container">';
		$sim_counter = 0;
		foreach ( $vehicles as $vehicle ) :
			$link_params               = array(
				'year'   => $vehicle['year'],
				'make'   => $vehicle['make'],
				'model'  => $vehicle['model'],
				'state'  => self::$company['state'],
				'city'   => self::$company['city'],
				'vin'    => $vehicle['vin'],
				'vms_id' => $vehicle['vms_id'],
			);
			$link                      = $this->fn_inventory->generate_inventory_link( array('params' => $link_params, 'type' => 1 ) );
			$sim_generic_vehicle_title = $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'];

			if ( $parent['vin'] !== $vehicle['vin'] && $sim_counter < 3 ) {
				$sim_counter   = $sim_counter + 1;
				$content       .= '<div class="similar-vehicle-item">';
				$content       .= '<a href="' . $link . '" title="' . $sim_generic_vehicle_title . '" >';
				$content       .= '<div class="similar-vehicle similar-image">';
				$image         = $this->fn_inventory->no_photo_replace( $vehicle['thumbnail'] );
				// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
				$content       .= '<img src="' . $image . '" alt="similar-image"/>';
				$content       .= '</div>';
				$content       .= '<div class="similar-vehicle similar-headline" itemprop="isSimilarTo">';
				$content       .= '<span class="similar-year">' . $vehicle['year'] . '</span> ';
				$content       .= '<span class="similar-make">' . $vehicle['make'] . '</span> ';
				$content       .= '<span class="similar-model">' . $vehicle['model'] . '</span> ';
				$content       .= '<span class="similar-trim">' . $vehicle['trim'] . '</span>';
				$content       .= '</div>';
				$display_price = Option::check_for_option(
					'cdp_theme_options',
					array(
						'theme',
						'inventory_display',
						'detail',
						'similar_vehicles',
						'display_price',
					),
				);
				if ( 'on' === $display_price ) {
					$prices  = $this->fn_inventory->get_prices( $vehicle );
					$content .= '<div class="similar-vehicle similar-price" itemprop="offers" itemscope itemtype="https://schema.org/Offer">';
					$content .= '<span class="main-price value">$' . $this->fn_inventory->price_format( $prices['main_price'] ) . '</span> ';
					$content .= '</div>';
				}
				$link_text = Option::check_for_option(
					'cdp_theme_options',
					array(
						'theme',
						'inventory_display',
						'detail',
						'similar_vehicles',
						'link_text',
					),
				);
				$content   .= '<div class="similar-vehicle similar-text-link">';
				$content   .= '<span class="similar-text-value">' . $link_text . '</span>';
				$content   .= '</div>';
				$content   .= '</a>';
				$content   .= '</div>';
			}
		endforeach;
		$content .= '</div>';

		return $content;

	}

	public function extender_map_display() {
		$location = rawurlencode( self::$company['street'] . ' ' . self::$company['city'] . ', ' . self::$company['state'] . ' ' . self::$company['zip'] );
		$content  = '<iframe width="640" height="480" src="https://maps.google.it/maps?q=' . $location . '&output=embed"></iframe>';

		return $content;
	}

	public function extender_google_tag_script( $vehicle = array() ) {
		$data_layer_obj  = '';
		$display         = '';
		$google_tags_key = Option::check_for_option(
			'cdp_admin_options',
			array(
				'admin',
				'general',
				'google_tags',
				'key',
			)
		);
		if ( $google_tags_key ) {
			$pass = array( 'saleclass', 'year', 'make', 'model', 'trim', 'exterior' );
			foreach ( $vehicle as $key => $value ) {
				if ( in_array( $key, $pass, true ) ) {
					$data_layer_obj .= ( empty( $data_layer_obj ) ? '"' . $key . '": "' . $value . '"' : ',"' . $key . '": "' . $value . '"' );
				}
			}
			$display .= '<script>';
			$display .= 'dataLayerVDP = [{' . $data_layer_obj . '}]';
			$display .= '</script>';
			$display .= '<!– Google Tag Manager –>' . "\n";
			$display .= '<noscript>';
			$display .= '<iframe src="//www.googletagmanager.com/ns.html?id=' . self::$admin_options['admin']['general']['google_tags']['key'] . '" height="0" width="0" style="display:none;visibility:hidden"></iframe>';
			$display .= '</noscript>' . "\n";
			$display .= '<script>' . "\n";
			$display .= '(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':new Date().getTime(),event:\'gtm.js\'}); var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\'; j.async=true; j.src=\'//www.googletagmanager.com/gtm.js?id=\'+i+dl;f.parentNode.insertBefore(j,f);})(window,document,\'script\',\'dataLayerVDP\',\'' . self::$admin_options['admin']['general']['google_tags']['key'] . '\');';
			$display .= '</script>' . "\n";
			$display .= '<!– End Google Tag Manager –>' . "\n";
		}

		return $display;
	}

	public function extender_map_generator( $dealer ) {
		$map = '';
		$key = self::$theme_options['theme']['inventory_display']['detail']['maps']['key'];
		if ( $key ) {
			if ( ! empty( self::$theme_options['theme']['inventory_display']['detail']['maps']['custom'] ) ) {
				$map_data = array();
				foreach ( self::$theme_options['theme']['inventory_display']['detail']['maps']['custom'] as $row => $data ) {
					if ( $data['dealer']['dealer_id'] === $dealer ) {
						$map_data = $data;
					}
				}
				$lat  = $map_data['geocode']['results'][0]['geometry']['location']['lat'];
				$long = $map_data['geocode']['results'][0]['geometry']['location']['lng'];
				$zoom = $map_data['dealer']['zoom'] ?? 14;
				$name = $map_data['dealer']['name'];
				// https://developers.google.com/maps/documentation/javascript/load-maps-js-api#javascript.
				$map = '<script>';
				$map .= '(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({';
				$map .= 'key: "' . $key . '",';
				$map .= 'v: "weekly",';
				$map .= '});';
				$map .= '</script>';

				$map .= '<script>';
				$map .= 'let map;';
				$map .= 'async function initMap() {';
				$map .= "const position = {lat: $lat , lng: $long };";
				$map .= 'const { Map } = await google.maps.importLibrary("maps");';
				$map .= 'const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");';
				$map .= 'map = new Map(document.getElementById("map-container"), {';
				$map .= 'mapId: "' . $key . '",';
				$map .= 'center: position,';
				$map .= "zoom: $zoom,";
				$map .= ' });';

				$map .= 'const marker = new google.maps.marker.AdvancedMarkerElement({';
				$map .= 'map: map,';
				$map .= "position: {lat: $lat , lng: $long },";
				$map .= "title: '$name',";
				$map .= '});';

				$map .= 'const infoWindow = new google.maps.InfoWindow();';
				$map .= 'marker.addListener("click", () => {';
				$map .= '	infoWindow.close();';
				$map .= '	infoWindow.setContent(marker.getTitle());';
				$map .= '	infoWindow.open(marker.getMap(), marker);';
				$map .= '});';
				$map .= '}';
				$map .= 'initMap();';
				$map .= '</script>';

			}
		}

		return $map;
	}

	public function build_text_data_list() {
		$data_list = '<datalist id="text-data-list">';
		$keywords  = self::$theme_options['theme']['inventory_display']['list']['keywords']['pot'];
		// $keywords_array = explode( ',', $keywords );
		if ( ! empty( $keywords ) ) {
			foreach ( $keywords as $value ) {
				$data_list .= '<option value="' . $value . '">';
			}
		}
		$data_list .= '</datalist>';

		return $data_list;
	}

	public function extender_create_geo_list() {

		$states = $this->get_state_list();
		$cities = $this->get_city_list();
		// $zips = $this->get_zip_list();
		$dealers     = $this->get_dealer_list();
		$content     = '';
		$display_geo = self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'];
		$geo_options = self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['geo_options'];

		if ( $display_geo && 'geo_dealer_names_only' !== $geo_options ) {
			// State.
			if ( 1 === $states['count'] && ! isset( self::$passed_parameters['geo_state'] ) ) {
				$disable = 'disabled';
			} else {
				$disable = '';
			}
			$content .= '<div class="search-list search-geo-state ' . ( $disable ? 'hidden' : '' ) . '" >';
			$content .= 'side2' === self::$search_view ? '' : '<div class="search-label">State</div>';
			$content .= '<div class="search-content">';
			$content .= '<select class="input-action select-state" name="geo_state" ' . $disable . '>';
			if ( $disable ) {
				$content .= '<option value="' . $states['needle'] . '">' . $states['needle'] . '</option>';
			} else {
				$content .= 'side2' === self::$search_view ? '<option value="0">All State\'s</option>' : '<option value="0">All</option>';
				$state   = self::$passed_parameters['geo_state'] ?? $states['needle'];
				foreach ( $states['data'] as $value ) {
					$content .= '<option value="' . $value . '" ' . ( $state === $value ? 'selected' : '' ) . '>' . $value . ' (' . $states['dataCount'][ $value ] . ') </option>';
				}
			}
			$content .= '</select>';
			$content .= '</div>';
			$content .= '</div>';
			// City.
			if ( 'geo_hide_cities' !== $geo_options ) {
				$content .= '<div class="search-list search-geo-city">';
				$content .= 'side2' === self::$search_view ? '' : '<div class="search-label">City</div>';
				$content .= '<div class="search-content">';
				$disable = ( $cities['count'] <= 1 || empty( $states['needle'] ) ? 'disabled' : '' );
				$content .= '<select class="input-action select-city" name="geo_city" ' . $disable . '>';
				if ( $disable ) {
					$city    = ( $cities['needle'] ? $cities['needle'] : 'Cities' );
					$content .= '<option value="' . $city . '">' . $city . '</option>';
				} else {
					$content .= 'side2' === self::$search_view ? '<option value="0">All Cities</option>' : '<option value="0">All</option>';
					$city    = self::$passed_parameters['geo_city'] ?? '';
					foreach ( $cities['data'] as $value ) {
						$content .= '<option value="' . $value . '" ' . ( $city === $value ? 'selected' : '' ) . '>' . $value . ' (' . $cities['dataCount'][ $value ] . ') </option>';
					}
				}
				$content .= '</select>';
				$content .= '</div>';
				$content .= '</div>';
			}
			// Zip.
			/*
			if( $states['needle'] && $cities['needle'] && self::$cdp_settings['vehicle_management_system']['theme']['geo_dealer_names'] ){
				$content .= '<div class="search-list search-geo-zip">';
					$content .= '<div class="search-label">Zip Codes</div>';
					$content .= '<div class="search-content">';
						$disable = ($zips['count'] == 1? 'disabled': '');
						$content .= '<select class="input-action select-zip" name="geo_zip" '.$disable.'>';
							if( $disable ){
								$content .= '<option value="'.$zips['needle'].'">'.$zips['needle'].'</option>';
							} else {
								$content .= '<option value="0">All Zips</option>';
								foreach($zips['data'] as $value){
									$content .= '<option value="'.$value.'" '.(self::$passed_parameters['geo_zip'] == $value ? 'selected':'').'>'.$value.'</option>';
								}
							}
						$content .= '</select>';
					$content .= '</div>';
				$content .= '</div>';
			}*/
		}
		// Dealer.
		if ( ( 'geo_add_dealer_names' === $geo_options || 'geo_dealer_names_only' === $geo_options ) ) {
			$content .= '<div class="search-list search-geo-dealer">';
			$content .= 'side2' === self::$search_view ? '' : '<div class="search-label">Dealers</div>';
			$content .= '<div class="search-content">';
			$disable = ( ( 'geo_dealer_names_only' === $geo_options ) ? '' : ( ( $dealers['count'] <= 1 || ( empty( $states['needle'] ) || empty( $cities['needle'] ) ) ) ? 'disabled' : '' ) );
			$content .= '<select class="input-action select-dealer" name="dealer" ' . $disable . '>';
			if ( $disable ) {
				$dealer  = ( $dealers['needle'] ? $dealers['needle'] : 'Dealers' );
				$content .= '<option value="' . $dealer . '">' . $dealer . '</option>';
			} else {
				$content .= 'side2' === self::$search_view ? '<option value="0">Dealerships</option>' : '<option value="0">All</option>';
				$dealer  = self::$passed_parameters['dealer'] ?? '';
				foreach ( $dealers['data'] as $value ) {
					$content .= '<option value="' . $value . '" ' . ( $dealer === $value ? 'selected' : '' ) . '>' . $value . ' (' . $dealers['dataCount'][ $value ] . ') </option>';
				}
			}
			$content .= '</select>';
			$content .= '</div>';
			$content .= '</div>';
		}

		return $content;
	}

	public function extender_create_sort_dropdown() {
		$content = '<div class="sort-container">';
		$content .= '<div class="inventory-sort-item sort-item-label">Sort:</div>';
		$content .= '<div class="inventory-sort-item">';
		$content .= '<select class="input-action select-sort" name="manual_sort">';
		$content .= '<option value="">Default</option>';
		$content .= '<option value="yearA">Year Low -> High</option>';
		$content .= '<option value="yearD">Year High -> Low</option>';
		$content .= '<option value="odometerA">Odometer Low -> High</option>';
		$content .= '<option value="odometerD">Odometer High -> Low</option>';
		$content .= '<option value="priceA">Price Low -> High</option>';
		$content .= '<option value="priceD">Price High -> Low</option>';
		$content .= '<option value="makeModel">Make/Model A -> Z</option>';
		$content .= '<option value="makeModelD">Make/Model Z -> A</option>';
		$content .= '</select>';
		$content .= '</div>';
		$content .= '</div>';

		return $content;
	}

	public function get_lists( $name ) {
		$common_list = array( 'drivetrain', 'vehicleclass', 'body', 'color', 'color_int', 'year', 'transmission','saleclass', 'fuel_type' );
		if (in_array( $name, $common_list, true )) {
			$results = $this->get_list( $name );
		} else {
			$get_data = 'get_' . $name . '_list';
			$results  = $this->$get_data();
		}

		return $results;
	}

//	public function extender_create_dropdown_list( $type = array() ) {
//		$content = '';
//		if ( empty( $type ) ) {
//			return $content;
//		}
//		foreach ( $type as $name ) {
//			$dropdown_name = '';
//			$content       .= '<div class="search-list search-' . $name . '">';
//			switch ( $name ) {
//				case 'saleclass':
//					$dropdown_name = 'Sale Class';
//					break;
//				case 'vehicleclass':
//					$dropdown_name = 'Vehicle Class';
//					break;
//				case 'bodystyle':
//					$dropdown_name .= 'Body Type';
//					$name = 'body';
//					break;
//				case 'color':
//					$dropdown_name .= 'Color Exterior';
//					break;
//				case 'color_int':
//					$dropdown_name .= 'Color Interior';
//					break;
//				default:
//					$dropdown_name .= ucfirst( $name );
//			}
//			$content .= '<div class="search-label">' . $dropdown_name . '</div>';
//			$results = $this->get_lists( $name );
//			$content .= '<div class="search-content">';
//			$content .= '<select class="input-action select-' . $name . '" name="' . $name . '" ' . ( empty( $results['disable'] ) ? '' : 'disabled' ) . '>';
//			if ( count( $results['data'] ) > 0 ) {
//				$content .= '<option value="All">' . ( 'side2' === self::$search_view ? $dropdown_name : 'All' ) . '</option>';
//				foreach ( $results['data'] as $value ) {
//					if ( $value ) {
//						$content .= '<option ' . ( $results['needle'] === $value ? 'selected' : '' ) . ' value="' . ucfirst($value) . '">';
//						$content .= ucfirst($value ) . ( isset( $results['dataCount'][ $value ] ) ? ' (' . $results['dataCount'][ $value ] . ')' : '' );
//						$content .= '</option>';
//					}
//				}
//			} else {
//				$content .= '<option>' . ucfirst( $name ) . '</option>';
//			}
//			$content .= '</select>';
//			$content .= '</div>';
//			$content .= '</div>';
//		}
//
//		return $content;
//	}

	public function get_make_list() {
		$results   = array(
			'needle'    => '',
			'data'      => array(),
			'disable'   => 0,
			'dataCount' => array(),
		);
		$data_list = array();
		$data      = $this->db_request->cdp_db_init( 'make', self::$passed_parameters );
		if ( $data ) {
			foreach ( $data as $value ) {
				$data_list[]              = $value['make'];
				$counts[ $value['make'] ] = $value['Total'];
			}
			$results['data']      = $data_list;
			$results['dataCount'] = $counts;
			if ( isset( self::$passed_parameters['make'] ) && in_array( rawurldecode( self::$passed_parameters['make'] ), $results['data'], true ) ) {
				$results['needle'] = self::$passed_parameters['make'];
			} elseif ( count( $results['data'] ) === 1 ) {
				self::$passed_parameters['make'] = $results['needle'] = $results['data'][0];
			} else {
				unset( self::$passed_parameters['make'] );
			}
		}

		return $results;
	}

	public function get_model_list() {
		$results   = array(
			'needle'    => '',
			'data'      => array(),
			'disable'   => 0,
			'dataCount' => array(),
		);
		$data_list = array();
		if ( isset( self::$passed_parameters['make'] ) && 'all' !== self::$passed_parameters['make'] ) { // Get Models.
			$data = $this->db_request->cdp_db_init( 'model', self::$passed_parameters );

			foreach ( $data as $value ) {
				$data_list[]               = $value['model'];
				$counts[ $value['model'] ] = $value['Total'];
			}
			$results['data']      = $data_list;
			$results['dataCount'] = $counts;
			if ( isset( self::$passed_parameters['model'] ) && in_array( rawurldecode( self::$passed_parameters['model'] ), $results['data'], true ) ) {
				$results['needle'] = self::$passed_parameters['model'];
			} elseif ( count( $results['data'] ) === 1 ) {
				self::$passed_parameters['model'] = $results['needle'] = $results['data'][0];
			} else {
				unset( self::$passed_parameters['model'] );
			}
		} else {
			$results['disable'] = 1;
		}

		return $results;
	}

	public function get_trim_list() {
		$results   = array(
			'count'     => 0,
			'needle'    => '',
			'data'      => array(),
			'disable'   => 0,
			'dataCount' => array(),
		);
		$data_list = array();
		if ( isset( self::$passed_parameters['make'] ) && ( isset( self::$passed_parameters['model'] ) && 'all' !== self::$passed_parameters['model'] ) ) { // Get Models
			$data = $this->db_request->cdp_db_init( 'trim', self::$passed_parameters );

			foreach ( $data as $value ) {
				$data_list[]              = $value['trim'];
				$counts[ $value['trim'] ] = $value['Total'];
			}
			$results['data']      = $data_list;
			$results['dataCount'] = $counts;
			if ( isset( self::$passed_parameters['trim'] ) && in_array( rawurldecode( self::$passed_parameters['trim'] ), $results['data'], true ) ) {
				$results['needle'] = self::$passed_parameters['trim'];
			} elseif ( count( $results['data'] ) === 1 ) {
				self::$passed_parameters['trim'] = $results['needle'] = $results['data'][0];
			} else {
				unset( self::$passed_parameters['trim'] );
			}
		} else {
			$results['disable'] = 1;
		}

		return $results;
	}

	// Drivetrain, vehicleclass, Body, Color, Color_int, saleclass, fuel_type
	public function get_list( $name ) {
		$results   = array(
			'count'     => 0,
			'needle'    => '',
			'data'      => array(),
			'disable'   => 0,
			'dataCount' => array(),
		);
		$data_list = array();
		$data      = $this->db_request->cdp_db_init( $name, self::$passed_parameters );
		if ( $data ) {
			foreach ( $data as $value ) {
				$data_list[]                          = $value[ $name ];
				$counts[ $value[ $name ] ] = $value['Total'];
			}
			$results['data']      = $data_list;
			$results['dataCount'] = $counts;
			if ( isset( self::$passed_parameters[ $name ] ) && in_array( rawurldecode( self::$passed_parameters[ $name ] ), $results['data'], true ) ) {
				$results['needle'] = self::$passed_parameters[ $name ];
			} elseif ( count( $results['data'] ) === 1 ) {
				self::$passed_parameters[ $name ] = $results['needle'] = $results['data'][0];
			} else {
				unset( self::$passed_parameters[ $name ] );
			}
		}

		return $results;
	}

	// 'features'
	public function get_tag_list() {
		$results      = [];
		$current_tags = ( isset( self::$passed_parameters['tags'] ) ? explode( ',', self::$passed_parameters['tags'] ) : array() );
		$exclude_tags = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'tags',
				'exclude',
			),
			array()
		);
		$data         = $this->db_request->cdp_db_init( 'tags', self::$passed_parameters );
		$replace      = array( '_', '-' );
		if ( $data ) {
			foreach ( $data as $tag ) {
				if ( $tag && ! in_array( $tag, $exclude_tags, true ) ) {
					$checked  = ( in_array( $tag, $current_tags, true ) ? 'checked' : '' );
					$human = ucwords( str_replace( $replace, ' ', $tag ));
					$results[] = array('tag' => $tag, 'human' => $human, 'checked' => $checked);
				}
			}
		}

		return $results;
	}

	// city and state same.
	public function get_state_list() {
		$results   = array(
			'count'   => 0,
			'needle'  => '',
			'data'    => array(),
			'disable' => 0,
		);
		$data_list = array();
		if ( self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo']
		     && 'geo_dealer_names_only' !== self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['geo_options']
		) {
			$data = $this->db_request->cdp_db_init( 'states', self::$passed_parameters );
			if ( $data ) {
				foreach ( $data as $value ) {
					$data_list[]                   = $value['geo_state'];
					$counts[ $value['geo_state'] ] = $value['Total'];
				}
				$results['count']     = count( $data_list );
				$results['data']      = $data_list;
				$results['dataCount'] = $counts;
				if ( isset( self::$passed_parameters['geo_state'] ) && in_array( rawurldecode( self::$passed_parameters['geo_state'] ), $results['data'], true ) ) {
					$results['needle'] = self::$passed_parameters['geo_state'];
				} elseif ( count( $results['data'] ) === 1 ) {
					self::$passed_parameters['geo_state'] = $results['needle'] = $results['data'][0];
				} else {
					unset( self::$passed_parameters['geo_state'] );
				}
			}
		}

		return $results;

	}

	public function get_city_list() {
		$results   = array(
			'count'   => 0,
			'needle'  => '',
			'data'    => array(),
			'disable' => 0,
		);
		$data_list = array();
		if ( self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'] && 'geo_dealer_names_only' !== self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['geo_options'] && isset( self::$passed_parameters['geo_state'] ) ) {

			$data = $this->db_request->cdp_db_init( 'cities', self::$passed_parameters );
			if ( $data ) {
				foreach ( $data as $value ) {
					$data_list[]                  = $value['geo_city'];
					$counts[ $value['geo_city'] ] = $value['Total'];
				}
				$results['count']     = count( $data_list );
				$results['data']      = $data_list;
				$results['dataCount'] = $counts;
				if ( isset( self::$passed_parameters['geo_city'] ) && in_array( rawurldecode( self::$passed_parameters['geo_city'] ), $results['data'], true ) ) {
					$results['needle'] = self::$passed_parameters['geo_city'];
				} elseif ( count( $results['data'] ) === 1 ) {
					self::$passed_parameters['geo_city'] = $results['needle'] = $results['data'][0];
				} else {
					unset( self::$passed_parameters['geo_city'] );
				}
			}

			return $results;
		} else {
			return $results;
		}

	}

	public function get_zip_list() {
		if ( self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'] ) {
			$results = array(
				'count'   => 0,
				'needle'  => '',
				'data'    => array(),
				'disable' => 0,
			);
			$data    = $this->db_request->cdp_db_init( 'zips', self::$passed_parameters );
			if ( $data ) {
				foreach ( $data as $value ) {
					$list[]                      = $value['geo_zip'];
					$counts[ $value['geo_zip'] ] = $value['Total'];
				}
				$results['count']     = count( $list );
				$results['data']      = $list;
				$results['dataCount'] = $counts;
				if ( isset( self::$passed_parameters['geo_zip'] ) && in_array( rawurldecode( self::$passed_parameters['geo_zip'] ), $results['data'], true ) ) {
					$results['needle'] = self::$passed_parameters['geo_zip'];
				} elseif ( count( $results['data'] ) === 1 ) {
					self::$passed_parameters['geo_zip'] = $results['needle'] = $results['data'][0];
				} else {
					unset( self::$passed_parameters['geo_zip'] );
				}
			}

			return $results;
		} else {
			return array( 'data' => array() );
		}

	}

	public function get_dealer_list() {
		$results     = array(
			'count'   => 0,
			'needle'  => '',
			'data'    => array(),
			'disable' => 0,
		);
		$data_list   = array();
		$geo_options = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'list',
				'search_filters',
				'geo_search',
			),
			array()
		);

		if ( 'geo_dealer_names_only' === $geo_options['geo_options'] || ( $geo_options['display_geo'] && ( isset( self::$passed_parameters['geo_city'] ) && 'all' !== self::$passed_parameters['geo_city'] ) ) ) {
			$data = $this->db_request->cdp_db_init( 'dealers', self::$passed_parameters );
			if ( $data ) {
				foreach ( $data as $value ) {
					$data_list[]                = $value['Dealer'];
					$counts[ $value['Dealer'] ] = $value['Total'];
				}
				$results['count']     = count( $data_list );
				$results['data']      = $data_list;
				$results['dataCount'] = $counts;
				if ( isset( self::$passed_parameters['dealer'] ) && in_array( rawurldecode( self::$passed_parameters['dealer'] ), $results['data'], true ) ) {
					$results['needle'] = self::$passed_parameters['dealer'];
				} elseif ( count( $results['data'] ) === 1 ) {
					self::$passed_parameters['dealer'] = $results['needle'] = $results['data'][0];
				} else {
					unset( self::$passed_parameters['dealer'] );
				}
			}

			return $results;
		} else {
			return $results;
		}

	}



	public function extender_remove_tag_list() {
		$tags               = '';
		$unwanted_tags      = array(
			'taxonomy',
			'per_page',
			'page',
			'saleclass',
			'dealer_id',
			'geo_search',
			'manual_sort',
		);
		$show_saleclass_tag = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'list',
				'search_filters',
				'general',
				'show_saleclass_tag',
			)
		);
		if ( $show_saleclass_tag ) {
			unset( $unwanted_tags[3] ); // Saleclass needs to stay as 3.
		}
		if ( ! self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'] ) {
			$unwanted_tags = array_merge( $unwanted_tags, array( 'geo_state', 'geo_city', 'geo_zip' ) );
			if ( ! self::$theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['geo_options'] ) {
				$unwanted_tags = array_merge( $unwanted_tags, array( 'dealer' ) );
			}
		}
		foreach ( self::$passed_parameters as $key => $value ) {
			if ( 'color' === $key && '' === $value ) {
				$unwanted_tags = array_merge( $unwanted_tags, array( 'color' ) );
			}
			if ( ! in_array( $key, $unwanted_tags, true ) && ( '' !== $value ) ) { // Parameters are showing up with no value but a key? (body is example not sure how it bing populated).
				$tags .= '<div class="tag-item remove-action" data-name="' . $key . '">';
				$tags .= '<span class="tag-name">' . ( 'tags' === $key ? 'Features' : ucwords( str_replace( '_', ' ', $key ) ) ) . '</span>: ';
				$tags .= '<span class="tag-value">' . ( 'tags' === $key ? 'Clear All' : ucfirst( urldecode( $value ) ) ) . '</span>';
				$tags .= '<span class="round-button">x</span></div>';
			}
		}

		return $tags;
	}

	public function extender_construct_parameter_update() {
		// Edge Cases.

		if ( isset( self::$request_data['saleclass'] ) || ! isset( self::$passed_parameters['saleclass'] ) ) {
			if ( isset( self::$request_data['saleclass'] ) && 'certified' === self::$request_data['saleclass'] ) {
				self::$passed_parameters['certified'] = 'Yes';
				self::$request_data['saleclass']      = 'Used';
			} else {
				unset( self::$passed_parameters['certified'] );
			}
			if ( self::$request_data['saleclass'] !== self::$passed_parameters['saleclass'] || ! isset( self::$passed_parameters['saleclass'] ) ) {
				unset( self::$passed_parameters['vehicleclass'] );
				unset( self::$passed_parameters['make'] );
				unset( self::$passed_parameters['model'] );
				unset( self::$passed_parameters['trim'] );
			}
		}
		if ( isset( self::$request_data['vehicleclass'] ) ) {
			unset( self::$passed_parameters['make'] );
			unset( self::$passed_parameters['body'] );
		}
		if ( isset( self::$request_data['make'] ) || ! isset( self::$passed_parameters['make'] ) ) {
			unset( self::$passed_parameters['model'] );
			unset( self::$passed_parameters['trim'] );
		}
		if ( isset( self::$request_data['model'] ) || ! isset( self::$passed_parameters['model'] ) ) {
			unset( self::$passed_parameters['trim'] );
		}
		if ( isset( self::$request_data['geo_state'] ) ) {
			unset( self::$passed_parameters['geo_city'] );
			unset( self::$passed_parameters['dealer'] );
		}
		if ( isset( self::$request_data['geo_city'] ) ) {
			unset( self::$passed_parameters['dealer'] );
		}
		if ( isset( self::$request_data['dealer'] ) ) {
			// dealer name has an apostrophe in it. example Lee's Automotivie
			// WordPress automatically doing Lee\'s Automotive
			self::$request_data['dealer'] = sanitize_text_field( stripslashes( self::$request_data['dealer'] ) );
		}
		// Clear out params if make is All.
		if ( isset( self::$request_data['make'] ) && isset( self::$passed_parameters['make'] ) ) {
			if ( self::$request_data['make'] === self::$passed_parameters['make'] ) {
				if ( 'all' === self::$request_data['make'] && 'all' === self::$passed_parameters['make'] ) {
					unset( self::$passed_parameters['make'] );
					unset( self::$passed_parameters['model'] );
					unset( self::$passed_parameters['trim'] );
					unset( self::$request_data['make'] );
					unset( self::$request_data['model'] );
					unset( self::$request_data['trim'] );
				}
			}
		}
		// Clear out params if switching makes.
		if ( isset( self::$request_data['make'] ) && isset( self::$passed_parameters['make'] ) ) {
			if ( self::$request_data['make'] !== self::$passed_parameters['make'] ) {
				$wanted = array( 'saleclass', 'per_page', 'make', 'vehicleclass' );
				foreach ( self::$passed_parameters as $key => $value ) {
					if ( in_array( $key, $wanted, true ) ) {
						// Don't do anything we want to keep the keys.
					} else {
						unset( self::$passed_parameters[ $key ] );
						unset( self::$request_data[ $key ] );
					}
				}
			}
		}
		// Update Parameters.
		foreach ( self::$request_data as $key => $value ) {
			if ( empty( $value ) ) {
				unset( self::$passed_parameters[ $key ] );
			} elseif ( ! empty( $key ) ) {
				self::$passed_parameters[ $key ] = $value;
			}
		}

		return self::$passed_parameters;
	}


	public function extender_dropdown_update() {
		$search_view   = self::$theme_options['theme']['inventory_display']['list']['search_filters']['general']['search_view'] . '_search';
		$filters = self::$theme_options['theme']['inventory_display']['list']['search_filters']['general']['filters'];

		$results       = array();
		$update_list   = array(
			'saleclass',
			'make',
			'model',
			'trim',
			'geo_state',
			'geo_city',
			'dealer',
			'vehicleclass',
			'tags',
			'body',
			'color',
			'color_int',
			'year_to',
			'year_from',
			'drivetrain',
			'transmission',
			'price_to',
			'price_from',
			'odometer_to',
			'odometer_from',
			'highway_to',
			'highway_from',
			'city_to',
			'city_from',
			'fuel_type'
		);
		$dropdown_list = array(
			'saleclass',
			'vehicleclass',
			'make',
			'model',
			'trim',
			'state',
			'city',
			'dealer',
			'body',
			'color',
			'color_int',
			'year_to',
			'year_from',
			'drivetrain',
			'transmission',
			'price_to',
			'price_from',
			'odometer_to',
			'odometer_from',
			'highway_to',
			'highway_from',
			'city_to',
			'city_from',
			'fuel_type',
		);
		$nonce_check = isset( $_REQUEST['nonce'] ) && wp_verify_nonce( sanitize_key( $_REQUEST['nonce'] ), 'cdp-nonce' );
		if ( isset( $_REQUEST['extra'] ) && 'clear' === $_REQUEST['extra'] && $nonce_check ) {
			self::$request_data = array( 'vehicleclass' => '' );
		}
		foreach ( self::$request_data as $request => $value ) {
			//if ( in_array( $request, $update_list, true ) ) {  // all of these are being updated. on each request.
				foreach ( $dropdown_list as $key ) {
					switch ( $key ) {
						case (bool) preg_match( '/year|city|highway/i', $key ) :
							$new_key = preg_replace('/_from|_to/i', '', $key);
							$needle  = self::$passed_parameters[$key] ?? '';
							$data    = $this->get_range_list($new_key);
							foreach (['from', 'to'] as $suffix) {
								if (stripos($key, $suffix) !== false) {
									$results["{$new_key}_{$suffix}"]['needle'] = $needle;
								}
							}
							if ( ! empty( $data['data'] ) ) {
								$results["{$new_key}_from"]['data']       = array_reverse( $data['data'] );
								$results["{$new_key}_from"]['dataCount'] = ( isset( $data['dataCount'] ) && $data['dataCount'] ? $data['dataCount'] : array() );

								$results["{$new_key}_to"]['data']      = $data['data'];
								$results["{$new_key}_to"]['dataCount'] = ( isset( $data['dataCount'] ) && $data['dataCount'] ? $data['dataCount'] : array() );
							}
							break;
						case (bool) preg_match( '/odometer|price/i', $key ) :
							$new_key = preg_replace('/_from|_to/i', '', $key);
							$needle  = self::$passed_parameters[$key] ?? '';
							$data    = $this->get_range_list($new_key);
							$buckets = [];
							foreach (['from', 'to'] as $suffix) {
								if (stripos($key, $suffix) !== false) {
									$results["{$new_key}_{$suffix}"]['needle'] = $needle;
								}
							}
							$bucket_size = 	self::$theme_options['theme']['inventory_display']['list']['search_filters']['general'][$new_key.'_step'];
							if (!empty($data['data'])) {
								$buckets = List_Search_Filters::range_buckets($data['data'], $bucket_size);

								$results["{$new_key}_from"]['data']      = $buckets;
								$results["{$new_key}_from"]['dataCount'] = [];

								$results["{$new_key}_to"]['data']        = array_reverse($buckets);
								$results["{$new_key}_to"]['dataCount']   = [];
							}
							break;
						default:
							$data = $this->get_lists( $key );
							if ( ! empty( $data['data'] ) ) {
								$results[ $key ]['data']      = $data['data'];
								$results[ $key ]['needle']    = $data['needle'];
								$results[ $key ]['dataCount'] = ( isset( $data['dataCount'] ) && $data['dataCount'] ? $data['dataCount'] : array() );
							}
					}
				}
			//}
		}

		return $results;
	}

	public function get_range_list( $name, $reverse = false ) {

		$results   = array(
			'count'   => 0,
			'needle'  => '',
			'data'    => array(),
			'disable' => 0,
		);
		$data_list = array();
		$data      = $this->db_request->cdp_db_init( $name, self::$passed_parameters );

		if ( $data ) {
			foreach ( $data as $value ) {
				if ( 'price' === $name ) {
					$data_list[]              = $value['sortprice'];
					$counts[ $value[ 'sortprice' ] ] = $value['Total'];
				} else {
					$data_list[]              = $value[$name];
					$counts[ $value[ $name ] ] = $value['Total'];
				}
			}
			$results['count']     = count( $data_list );
			$results['data']      = $data_list;
			$results['dataCount'] = $counts;
			$param     = ( $reverse ? $name .'_to' : $name .'_from' );

			$results['needle'] = self::$passed_parameters[ $param ] ?? '';
		}

		return $results;
	}

	public function extender_inventory_pagination() {
		$vehicle_count = $this->db_request->cdp_db_init( 'searchtotal', self::$passed_parameters );
		$on_page       = ( self::$passed_parameters['page'] ?? 1 );
		$per_page      = self::$theme_options['theme']['overrides']['per_page'];
		$page_total    = ( $vehicle_count > 0 ? ceil( $vehicle_count / $per_page ) : 1 );

		$result = '<div class="pagination-container">';
		$result .= '<div class="pagination-cdp page-control-button"><span class="input-page-action previous" data-name="previous"><span class="page-arrow">&lsaquo;</span> Previous</span></div>';
		$result .= '<div class="pagination-cdp page-count-container">';
		$result .= '<input class="inner-count pagination-current input-page-action" type="number" name="page" min="1" max="' . $page_total . '" value="' . $on_page . '">';
		$result .= '<div class="inner-count pagination-divider">/</div>';
		$result .= '<div class="inner-count pagination-max-page">' . $page_total . '</div>';
		$result .= '</div>';
		$result .= '<div class="pagination-cdp page-control-button"><span class="input-page-action next" data-name="next">Next <span class="page-arrow">&rsaquo;</span></span></div>';
		$result .= '</div>';

		return $result;

	}

	public function extender_inventory_count() {
		$vehicle_count = $this->db_request->cdp_db_init( 'searchtotal', self::$passed_parameters );

		return $vehicle_count;
	}

	public function extender_inventory_pull() {
		// $inventory = self::$vms_caller->get_inventory()->please(self::$passed_parameters);
		$inventory = ( new Requests() )->cdp_db_init( 'inventory', self::$passed_parameters );

		return $inventory;
	}

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

					return $value;
				}
			);
		}
	}

	public function extender_create_gravity_hooks( $data ) {
		$result = array();
		foreach ( $data as $key => $value ) {
			$result[ 'dt_' . $key ] = $value;
		}

		return $result;
	}

	// Get Gravity Form, on List page.
	public function extender_get_gravity_form() {
		$this->extender_apply_gravity_hooks( self::$request_data['hooks'] );
		$form_id         = self::$theme_options['theme']['inventory_display']['list']['general']['buttons']['form']['gform_id'];
		$form            = gravity_form( $form_id, $display_title = false, $display_description = false, $display_inactive = false, $field_values = false, $ajax = true, $tabindex = 0, $echo = false );
		$results['form'] = '<div id="form-active"><div id="form-close">X</div><div id="form-container">' . $form . '</div></div>';

		return $results;
	}

	public function extender_populate_content() {
		$results = array();
		// Dropdown Update.
		$dropdown_data            = $this->extender_dropdown_update();
		$results['dropdown_data'] = ( empty( $dropdown_data ) ? array() : $dropdown_data );
		// Tag Data List.
		$tag_data            = $this->get_tag_list();
		$results['tag_data'] = ( empty( $tag_data ) ? '' : $tag_data );
		// Remove Tags.
		$remove_tags            = $this->extender_remove_tag_list();
		$results['remove_tags'] = ( empty( $remove_tags ) ? '' : $remove_tags );
		// Inventory Count.
		$inventory_count            = $this->extender_inventory_count();
		$results['inventory_count'] = ( empty( $inventory_count ) ? 0 : $inventory_count );
		// Remove Tags.
		$remove_tags = $this->extender_remove_tag_list();
		if (intval($inventory_count) === 1) {
			$remove_tags = array();
		}
		$results['remove_tags'] = ( empty( $remove_tags ) ? '' : $remove_tags );
		// Inventory Update.
		// $inventory = $this->extender_inventory_pull();
		switch ( self::$srp_view ) {
			case 'list':
				$results['inventory'] = $this->extender_inventory_list_view();
				break;
			case 'grid':
				$results['inventory'] = $this->extender_inventory_list_view_grid();
				break;
		}
		$results['pagination'] = $this->extender_inventory_pagination();
		// Banner Update.
		if ( ! empty( self::$theme_options['theme']['inventory_display']['banners'] ) ) {
			$banners                  = self::$theme_options['theme']['inventory_display']['banners'];
			$params                   = self::$passed_parameters;
			$results['top_banner']    = $this->fn_inventory->cdp_get_banners( 'list', 'top', $banners, $params );
			$results['bottom_banner'] = $this->fn_inventory->cdp_get_banners( 'list', 'bottom', $banners, $params );
		}

		return $results;
	}

	public function extender_construct_url( $args = array() ) {
		$params = empty($args) ? self::$passed_parameters : $args;
		$rules    = get_option( 'rewrite_rules' );
		$url_rule = isset( $rules['^(inventory)'] );
		// Parameters are showing up with no value but a key? (body is example not sure where it is coming in from).
		foreach ( $params as $key => $value ) {
			if ( '' === $value ) {
				unset( $params[ $key ] );
			}
		}
		if ( isset( $rules['^(inventory)'] ) ) {
			// Pretty URL.
			$pretty_url_parameters = array( 'saleclass', 'make', 'model' );
			$base               = '/inventory/';
			$query_encoded = array();
			foreach ( $pretty_url_parameters as $value ) {
				$base .= isset( $params[ $value ] ) ? rawurlencode( trim( $params[ $value ] ) ) . '/' : '';
			}
			foreach ( $params as $key => $value ) {
				if ( ! in_array( $key, $pretty_url_parameters, true ) ) {
					$query_encoded[urlencode($key)] = urlencode($value);
				}
			}
			$results = esc_url_raw( add_query_arg($query_encoded, $base) );
		} else {
			// Ugly URL.
			$results = '?taxonomy=inventory';
			foreach ( $params as $key => $value ) {
				$results = esc_url_raw(add_query_arg( array( $key => rawurlencode( trim( $value ) ) ), $results ));
			}
		}
		// Remove Unwanted Parameters.
		$path         = wp_parse_url( $results, PHP_URL_PATH );
		$query        = wp_parse_url( $results, PHP_URL_QUERY );
		$query_string = str_replace( explode( "?", $results )[0] . "?", '', $results );
		parse_str( $query_string, $arr );
		$filtered  = array_filter( $arr, function ( $v, $k ) {
			return $v != null;
		}, ARRAY_FILTER_USE_BOTH );
		$final_url = $path;
		if ( $query ) {
			$final_url .= '?' . http_build_query( $filtered );
		}

		return $final_url;
	}
}
