<?php

namespace CarDealerPress\Templates\Inventory;

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

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\functions\Fn_Inventory;
use CarDealerPress\includes\helpers\Dynamic_Site_Headers;
use CarDealerPress\includes\helpers\helpers;

$this->compared_vehicles = $this->saved_vehicles = array();
$fn_inventory            = new Fn_Inventory();

$content              = '';
$dynamic_site_headers = new Dynamic_Site_Headers( $this->company['dealer_id'] );
$dynamic_site_headers->apply_headers( $this->parameters );

// Load Dependent Scripts.
$dependent_scripts = array( 'jquery', 'jquery-ui-core', 'jquery-ui-tabs', 'jquery-ui-dialog', 'jquery-ui-slider' );
foreach ( $dependent_scripts as $dependent ) {
	wp_enqueue_script( $dependent );
}
wp_enqueue_script( 'cdp_jquery_cookie', CDP_JS . 'jquery-cookie/js.cookie.js', array( 'jquery' ), '2.1.3', true );

// Load Save Form.
if ( function_exists( 'gravity_form_enqueue_scripts' ) ) {
	$form_id = $this->theme_options['theme']['inventory_display']['general']['saved_vehicles']['form'] ?? '';
	if ( $form_id ) {
		$gform_element = '<div style="display: none;" id="saved-gform-id" data-form="' . $form_id . '"></div>';
		$gform_class   = 'saved_get_gform';
		gravity_form_enqueue_scripts( $form_id, true );
	}
}

// Load Page Style/Script.
$saved_style_url  = CDP_CSS . 'templates/inventory/save-page.css';
$saved_style_url  = apply_filters( 'cdp_save_style_url', $saved_style_url );
$saved_script_url = CDP_JS . 'templates/inventory/save-compare.js';
$saved_script_url = apply_filters( 'cdp_save_script_url', $saved_script_url );

wp_enqueue_style( 'cdp_saved', $saved_style_url, array(), CDP_VERSION );
wp_register_script( 'cdp_saved_js', $saved_script_url, $dependent_scripts, CDP_VERSION, true );
$ajax_script = admin_url( 'admin-ajax.php' );
wp_localize_script(
	'cdp_saved_js',
	'ajax_object',
	array(
		'url'   => $ajax_script,
		'nonce' => wp_create_nonce( 'cdp_nonce' ),
	)
);
wp_enqueue_script( 'cdp_saved_js' );

// Get Save Cookies.
foreach ( $_COOKIE as $key => $value ) {
	if ( strpos( $key, 'vehicleSave' ) !== false ) {
		$this->saved_vehicles[ str_replace( 'CDPvehicleSave_', '', $key ) ] = $value;
	}
}

// Get Compare Cookies.
foreach ( $_COOKIE as $key => $value ) {
	if ( strpos( $key, 'vehicleCompare' ) !== false ) {
		$this->compared_vehicles[ str_replace( 'CDPvehicleCompare_', '', $key ) ] = $value;
	}
}

// Build Save Display.
$content .= '<div id="saved-vehicle-container">';
if ( ! empty( $this->saved_vehicles ) ) {
	$content .= '<div id="saved-vehicle-inner-container">';
	foreach ( $this->saved_vehicles as $key => $values ) {
		$vehicle_raw = ( new Requests() )->cdp_db_init( 'inventory', array( 'vin' => $key ) );

		$saved_data       = json_decode( stripslashes( $values ) );
		$saved_data_array = array_merge( json_decode( json_encode( $saved_data ), true ), array(
			'state' => $this->company['state'],
			'city'  => $this->company['city']
		) );
		$vdp_link         = $fn_inventory->generate_inventory_link( array(
			'params' => $saved_data_array,
			'type'   => 1
		) );
		if ( ! empty( $vehicle_raw ) ) {
			$vehicle = $vehicle_raw[0];
			$content .= '<div id="' . $key . '" class="saved-vehicle-item">'; // saved-vehicle-item Open.
			$content .= '<div class="saved-vehicle-content">'; // saved-vehicle-content Open.
			$content .= '<div class="saved-left-content">'; // saved-left-content Open.
			$image   = $vehicle['thumbnail'];
			if ( ( empty( $image ) || strstr( $image, '_no_photo' ) ) && ! empty( $this->theme_options['theme']['overrides']['default_no_image'] ) ) {
				$image = $this->theme_options['theme']['overrides']['default_no_image'];
			}

			// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
			$content .= '<img class="saved-vehicle-image" src="' . str_replace( '_small', '_medium', $image ) . '" />';
			$content .= '</div>'; // saved-left-content Close.

			$content      .= '<div class="saved-right-content">'; // saved-right-content Open.
			$content      .= '<div data-key="CDPvehicleSave_' . $key . '" class="saved-remove right-item">Remove [X]</div>';
			$content      .= '<div class="saved-headline">';
			$content      .= '<span class="saleclass form-value" data-name="saleclass">' . ucfirst( $vehicle['saleclass'] ) . '</span>';
			$content      .= '<span class="year form-value" data-name="year">' . $vehicle['year'] . '</span>';
			$content      .= '<span class="make form-value" data-name="make">' . $vehicle['make'] . '</span>';
			$content      .= '<span class="model form-value" data-name="model">' . $vehicle['model'] . '</span>';
			$content      .= '<span class="trim form-value" data-name="trim">' . $vehicle['trim'] . '</span>';
			$content      .= '</div>';
			$content      .= '<div class="saved-hidden-values" style="display: none;">';
			$content      .= '<span class="form-value" data-name="stock">' . $vehicle['stock'] . '</span>';
			$content      .= '<span class="form-value" data-name="vin">' . $vehicle['vin'] . '</span>';
			$content      .= '<span class="form-value" data-name="exterior">' . $vehicle['exterior'] . '</span>';
			$content      .= '<span class="form-value" data-name="interior">' . $vehicle['interior'] . '</span>';
			$content      .= '<span class="form-value" data-name="odometer">' . $vehicle['odometer'] . '</span>';
			$phone_number = $this->theme_options['theme']['overrides']['custom_contact']['phone'][ strtolower( $vehicle['saleclass'] ) ] ?? $this->company['phone'];
			$dealer_name  = $this->theme_options['theme']['overrides']['custom_contact']['contact_name'][ strtolower( $vehicle['saleclass'] ) ] ?? $this->company['name'];
			$content      .= '<span class="form-value" data-name="dealer">' . $dealer_name . '</span>';
			$content      .= '<span class="form-value" data-name="phone">' . $phone_number . '</span>';
			$content      .= '<span class="form-value" data-name="dealer_id">' . $this->company['dealer_id'] . '</span>';
			$content      .= '<span class="form-value" data-name="location">' . $this->company['street'] . ' ' . $this->company['city'] . ' ' . $this->company['state'] . ' ' . $this->company['zip'] . '</span>';
			$content      .= '<span class="form-value" data-name="dealer_id">' . $this->company['dealer_id'] . '</span>';
			$content      .= $fn_inventory->get_automall_email( $this->company['dealer_id'], $vehicle['saleclass'] );
			$content      .= '<span class="is-adf form-value" data-name="is_adf" >' . $fn_inventory->get_automall_email_adf( $this->company['dealer_id'], $vehicle['saleclass'] ) . '</span>';
			$content      .= '</div>';
			$content      .= '<div class="saved-buttons">';
			$content      .= '<div class="saved-more-details"><a href="' . $vdp_link . '">More Details</a></div>';
			if ( ! empty( $this->theme_options['theme']['inventory_display']['general']['saved_vehicles']['form'] ) ) {
				$content .= '<div class="saved-form-action" data-key="' . $vehicle['vin'] . '">Get Today\'s Price</div>';
			}

			if ( ! empty( $this->compared_vehicles ) ) {
				$compare_class = ( array_key_exists( $vehicle['vin'], $this->compared_vehicles ) ? 'checked' : '' );
			} else {
				$compare_class = '';
			}

			$content .= '<div class="saved-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="saved-prices">'; // saved-prices Open.
			$price   = $fn_inventory->get_price_display(
				array(
					'company' => $this->company,
					'vehicle' => $vehicle,
					'theme'   => 'saved',
				)
			);

			$content .= '<div class="saved-vehicle-pricing">';    // saved-vehicle-pricing Open.
			$content .= ( empty( $price['msrp_text'] ) || 'new' !== strtolower( $vehicle['saleclass'] ) ? '' : '<div class="price-item price-msrp">' . $price['msrp_text'] . '</div>' );
			// First Discount if New and Has MSRP.
			$content .= ( ! empty( $vehicle['prices']['msrp'] ) && $price['discount_text'] ? '<div class="price-item price-discount">' . $price['discount_text'] . '</div>' : '' );
			$content .= ( empty( $price['compare_price_text'] ) ? '' : '<div class="price-item price-compare">' . $price['compare_price_text'] . '</div>' );
			// Second Discount if Sale Price listed.
			$content .= ( empty( $price['discount_text'] ) ? '' : '<div class="price-item price-discount">' . $price['discount_text'] . '</div>' );
			$content .= ( empty( $price['primary_text'] ) ? '' : '<div class="price-item price-primary">' . $price['primary_text'] . '</div>' );
			$content .= ( empty( $price['expire_text'] ) ? '' : '<div class="price-item price-expire">' . $price['expire_text'] . '</div>' );
			$content .= '<div class="price-item price-hidden-values">' . $price['hidden_prices'] . '</div>';
			$content .= '</div>'; // saved-vehicle-pricing Close.
			$content .= '</div>'; // saved-price Close.
			$content .= '<div class="saved-vehicle-form-holder" style="display: none;"></div>';
			$content .= '</div>'; // saved-right-content Close.
			$content .= '</div>'; // saved-vehicle-content Close.
			$content .= '<div class="removed-saved-vehicle-content" style="display: none;">'; // removed-saved-vehicle-content Open.
			$content .= '<div class="removed-vehicle-headline">'; // removed-vehicle-headline Open.
			$content .= '<span data-name="saleclass" class="removed-item removed-saleclass">' . ucfirst( $vehicle['saleclass'] ) . '</span>';
			$content .= '<span data-name="year" class="removed-item removed-year">' . $vehicle['year'] . '</span>';
			$content .= '<span data-name="make" class="removed-item removed-make">' . $vehicle['make'] . '</span>';
			$content .= '<span data-name="model" class="removed-item removed-model">' . $vehicle['model'] . '</span>';
			$content .= '<span data-name="trim" class="removed-item removed-trim" style="display: none">' . $vehicle['trim'] . '</span>';
			$content .= '<span data-name="image" class="removed-item removed-image" style="display: none">' . $image . '</span>';
			$content .= '<span data-name="link" class="removed-item removed-link" style="display: none">' . $vdp_link . '</span>';
			$content .= '<span data-name="price" class="removed-item removed-price" style="display: none">' . $price['primary_price'] . '</span>';
			$content .= 'has been removed.';
			$content .= '<div data-key="CDPvehicleSave_' . $key . '" class="restore-saved-vehicle">Restore Removed Vehicle</div>'; // Open/Close.
			$content .= '</div>'; // removed-vehicle-headline Close.
			$content .= '</div>'; // removed-saved-vehicle-content Close.
			$content .= '</div>'; // saved-vehicle-item Close.
		}
	}
	$content .= '</div>';
	// Build Compare Display.
	$i       = 1;
	$class   = ( count( $this->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( $this->compared_vehicles ) > 0 ) {
		foreach ( $this->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="image"/></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( $this->compared_vehicles ) . '</span>)</div></div>';
	$content .= '</div>';


} else {
	$content .= '<div id="saved-not-found">No Vehicles have been saved or are no longer saved.</div>';
}
$content .= '</div>';

get_header();
helpers::output_wp_kses( $content );
helpers::output_wp_kses( ! empty( $gform_element ) ? $gform_element : '' );
get_footer();
