<?php

namespace CarDealerPress\Templates\Inventory;

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

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\functions\Extender_Functions;
use CarDealerPress\includes\functions\Fn_Inventory;
use CarDealerPress\includes\helpers\Allowed_Html;
use CarDealerPress\includes\helpers\helpers as helpers;
use CarDealerPress\Includes\Helpers\{Option, Remote_Requests};
use CarDealerPress\includes\helpers\Dynamic_Site_Headers;

( new Allowed_Html() );

$this->parameters['saleclass'] = isset( $this->parameters['saleclass'] ) ? ucwords( $this->parameters['saleclass'] ) : 'All';

$ext_functions = new Extender_Functions();
$ext_functions->load_parameters( $this->parameters );
$fn_inventory = new Fn_Inventory();
$db_requests  = new Requests();
$search_error = '';

// Cookie URL.
$rules    = get_option( 'rewrite_rules' );
$url_rule = isset( $rules['^(inventory)'] );

$host               = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
$request_uri        = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
$page_url           = 'http' . ( isset( $_SERVER['HTTPS'] ) ? 's' : '' ) . '://' . $host . $request_uri;
$page_referer       = isset( $_SERVER['HTTP_REFERER'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '';
$urlparts           = wp_parse_url( site_url() );
$domain             = $urlparts['host'];
$arr_cookie_options = array(
        'expires'  => 0,
        'path'     => '/',
        'domain'   => $domain, // leading dot for compatibility or use subdomain
        'secure'   => true,     // or false
        'httponly' => true,    // or false
        'samesite' => 'None' // None || Lax  || Strict
);
setcookie( 'cdp_page_url', $page_url, $arr_cookie_options );
$site_url       = site_url();
$traffic_source = isset( $_COOKIE['cardealerpress-traffic-source'] ) ? sanitize_text_field( wp_unslash( $_COOKIE['cardealerpress-traffic-source'] ) ) : false;
$traffic_source = $this->sanitize_inputs( $traffic_source );
$page           = isset( $this->parameters['vin'] ) || isset( $this->parameters['vms_id'] ) ? 'detail' : 'list';


// legacy themes.
$dealer_geo = array();
$geo_params = array();
if ( 'on' === $this->theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'] ) {
    $dealer_geo = $this->vms->get_automall_geo_data_db();
    $fn_inventory->decode_geo_query( $dealer_geo, $this->parameters, $geo_params );
}

$do_not_carry     = esc_url( remove_query_arg( 'page' ) );
$tmp_do_not_carry = esc_url( remove_query_arg( 'certified', $do_not_carry ) );

$certified = $this->parameters['certified'] ?? null;  // cobra, dolphin only.
$all_link  = ( isset( $rules['^(inventory)'] ) ) ? '/inventory/' : esc_url( add_query_arg( array( 'taxonomy' => 'inventory' ), $tmp_do_not_carry ) );  // only cobra,dolphin.
$new_link  = ( isset( $rules['^(inventory)'] ) ) ? '/inventory/New/' : esc_url( add_query_arg( array( 'saleclass' => 'New' ), $tmp_do_not_carry ) );
$used_link = ( isset( $rules['^(inventory)'] ) ) ? '/inventory/Used/' : esc_url( add_query_arg( array( 'saleclass' => 'Used' ) ) );
$cert_link = ( isset( $rules['^(inventory)'] ) )
        ? esc_url( add_query_arg( 'certified', 'yes', '/inventory/Used/' ) )
        : esc_url( add_query_arg(
                        array(
                                'saleclass' => 'Used',
                                'certified' => 'yes',
                        ) )
        );

$filters = array(
        'vehicleclass' => $this->parameters['vehicleclass'] ?? null,
        'price_to'     => $this->parameters['price_to'] ?? null,
        'price_from'   => $this->parameters['price_from'] ?? null,
        'certified'    => $this->parameters['certified'] ?? null,
        'search'       => $this->parameters['search'] ?? null,
        'year_to'      => $this->parameters['year_to'] ?? null,
        'year_from'    => $this->parameters['year_from'] ?? null,
        'mileage_to'   => $this->parameters['mileage_to'] ?? null,
        'mileage_from' => $this->parameters['mileage_from'] ?? null,
        'saleclass'    => $this->parameters['saleclass'] ?? null,
        'make'         => $this->parameters['make'] ?? null,
        'model'        => $this->parameters['model'] ?? null,
        'trim'         => $this->parameters['trim'] ?? null,
        'geo_state'    => $this->parameters['geo_state'] ?? null,
        'geo_city'     => $this->parameters['geo_city'] ?? null,
        'per_page'     => $this->parameters['per_page'] ?? null,
);
foreach ( $filters as $key => $filter ) {
    if ( empty( $filter ) ) {
        unset( $filters[ $key ] );
    }
}
$this->vms->tracer = 'Obtaining a list of makes.';
if ( 0 === strcasecmp( $this->parameters['saleclass'], 'new' ) && ! empty( $this->theme_options['theme']['overrides']['makes_new']['included'] ) ) { // Get Makes.
    $makes = $this->theme_options['theme']['overrides']['makes_new']['included'];
} else {
    $makes = $this->vms->get_makes( array( 'parameters' => $filters ) );
}

$make_count  = count( $makes );
$model_count = 0;
$trim_count  = 0;

if ( isset( $this->parameters['make'] ) && 'all' !== $this->parameters['make'] ) { // Get Models.
    $this->vms->tracer = 'Obtaining a list of models.';
    $tmp_do_not_carry  = esc_url( remove_query_arg( 'make', $do_not_carry ) );
    $models            = $this->vms->get_models( array( 'parameters' => $filters ) );
    if ( isset( $this->parameters['model'] ) ) {
        if ( ! in_array( rawurldecode( $this->parameters['model'] ), $models, true ) && ! empty( $this->parameters['model'] ) ) {
            $search_error = 'The current model(' . $this->parameters['model'] . ') could not be found with current search parameters. Reset search or adjust search parameters. ';
        }
    }

    $model_count = count( $models );
    $model       = $this->parameters['model'] ?? 'all';
    if ( 'all' === $model ) {
        unset( $this->parameters['model'] );
    } else {
        $this->parameters['model'] = $model;
    }
    $model_text = 'All Models';
} else {
    $model_text = 'Select a Make';
}

if ( isset( $this->parameters['model'] ) && 'all' !== $this->parameters['model'] ) { // Get Trims.
    $this->vms->tracer = 'Obtaining a list of trims.';
    $tmp_do_not_carry  = esc_url( remove_query_arg( array( 'make', 'model' ), $do_not_carry ) );
    $trims             = $this->vms->get_trims( array( 'parameters' => $filters ) );
    if ( isset( $this->parameters['trim'] ) ) {
        if ( ! in_array( rawurldecode( $this->parameters['trim'] ), $trims, true ) && ! empty( $this->parameters['trim'] ) ) {
            $search_error = 'The current trim(' . $this->parameters['trim'] . ') could not be found with current search parameters. Reset search or adjust search parameters. ';
        }
    }

    $trim_count = count( $trims );
    $trim       = $this->parameters['trim'] ?? 'all';
    if ( 'all' === $trim ) {
        unset( $this->parameters['trim'] );
    } else {
        $this->parameters['trim'] = $trim;
    }
    $trim_text = 'All Trims';
} else {
    $trim_text = 'Select a Model';
}
// @codingStandardsIgnoreStart
$safe = helpers::sanitize_get( $_GET );
// @codingStandardsIgnoreEnd
$sort = $safe['manual_sort'] ?? null;
switch ( $sort ) {
    case 'yearA':
        $sort_year_class = 'asc';
        break;
    case 'yearD':
        $sort_year_class = 'desc';
        break;
    case 'priceA':
        $sort_price_class = 'asc';
        break;
    case 'priceD':
        $sort_price_class = 'desc';
        break;
    case 'odometerA':
        $sort_mileage_class = 'asc';
        break;
    case 'odometerD':
        $sort_mileage_class = 'desc';
        break;
    case 'makeA':
        $sort_make_class = 'asc';
        break;
    case 'makeD':
        $sort_make_class = 'desc';
        break;
    default:
        $sort_year_class = $sort_price_class = $sort_mileage_class = $sort_make_class = null;
        break;
}
$sort_year    = 'yearA' !== $sort ? 'yearA' : 'yearD';
$sort_mileage = 'odometerA' !== $sort ? 'odometerA' : 'odometerD';
$sort_price   = 'priceA' !== $sort ? 'priceA' : 'priceD';
$sort_make    = 'makeModel' !== $sort ? 'makeModel' : 'makeModelD';

// end legacy themes.

if ( $this->company ) {
    $company_zip  = $this->company['zip'];
    $city         = $this->company['city'];
    $state        = $this->company['state'];
    $company_name = strtoupper( $this->company['name'] );
    $country_code = $this->company['country_code'];
}

$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_style( 'cdp_jquery_ui_style', CDP_CSS . 'jquery-css/jquery-css.css', array(), CDP_VERSION );
// jQuery Cookie.
wp_enqueue_script( 'cdp_jquery_cookie', CDP_JS . 'jquery-cookie/js.cookie.js', array( 'jquery' ), '2.1.3', true );

$extensions    = array( 'css', 'scss' );
$filename_url  = CDP_CSS . 'templates/inventory/' . $current_theme . '/' . $current_theme;
$filename_path = CARDEALERPRESS_PATH . 'assets/css/templates/inventory/' . $current_theme . '/' . $current_theme;
foreach ( $extensions as $ext ) {
    $filename_url_ext  = $filename_url . '.' . $ext;
    $filename_path_ext = $filename_path . '.' . $ext;
    if ( file_exists( $filename_path_ext ) ) {
        $inventory_style_url = apply_filters( 'cdp_inventory_style_url', $filename_url_ext );
        wp_enqueue_style( 'cdp_inventory', $inventory_style_url, array(), CDP_VERSION );
    }
}

$inventory_style_url_common = CDP_CSS . 'templates/inventory/common.css';
$inventory_style_url_common = apply_filters( 'cdp_inventory_style_url', $inventory_style_url_common );

wp_enqueue_style( 'cdp_inventory_common', $inventory_style_url_common, array(), CDP_VERSION );

$inventory_script_url = CDP_JS . 'templates/inventory/' . $current_theme . '/' . $current_theme . '.js';
$inventory_script_url = apply_filters( 'cdp_inventory_script_url', $inventory_script_url );
wp_register_script( 'cdp_inventory_js', $inventory_script_url, $dependent_scripts, CDP_VERSION, true );
$ajax_script = admin_url( 'admin-ajax.php' );
wp_localize_script(
        'cdp_inventory_js',
        'ajax_object',
        array(
                'url'   => $ajax_script,
                'nonce' => wp_create_nonce( 'cdp_nonce' ),
        )
);
wp_enqueue_script( 'cdp_inventory_js' );


$gform_class = '';
switch ( $page ) {
    case 'detail':
        wp_enqueue_script( 'cdp_inventory_cycle_js', CDP_JS . 'jquery-cycle/cycle2.js', array( 'jquery' ), '2.1.5', true );
        wp_enqueue_script( 'cdp_inventory_light_js', CDP_JS . 'jquery-lightbox/2.0/js/lightbox.js', array( 'jquery' ), '2.11.3', true );
        wp_enqueue_style( 'cdp_inventory_light', CDP_JS . 'jquery-lightbox/2.0/css/lightbox.css', array(), '2.11.3' );

        if ( function_exists( 'gravity_form_enqueue_scripts' ) ) {
            if ( ! empty(
            Option::check_for_option(
                    'cdp_theme_options',
                    array(
                            'theme',
                            'inventory_display',
                            'detail',
                            'forms',
                            0,
                    )
            )
            )
            ) {
                $form_id       = Option::check_for_option(
                        'cdp_theme_options',
                        array(
                                'theme',
                                'inventory_display',
                                'detail',
                                'forms',
                                0,
                                'id',
                        )
                );
                $gform_element = "<div style='display: none;' id='inventory-gform-id-$form_id' data-form='$form_id'></div>";
                $gform_class   = 'inventory_get_gform';
                gravity_form_enqueue_scripts( $form_id, true );
            }
        }

        wp_register_script( 'cdp_inventory_calc_js', CDP_JS . 'templates/inventory/loan-calculator.js', 'jquery', CDP_VERSION, true );
        if ( 'all' === $this->parameters['saleclass'] ) {
            $days_to_first_payment = 0;
        } else {
            $days_to_first_payment = Option::check_for_option(
                    'cdp_theme_options',
                    array(
                            'theme',
                            'inventory_display',
                            'payment_calculator',
                            lcfirst( $this->parameters['saleclass'] ),
                            'default',
                            'days_to_payment',
                    )
            ) ?? 0;
        }
        wp_localize_script( 'cdp_inventory_calc_js', 'days_to_first', array( $days_to_first_payment ) );
        wp_enqueue_script( 'cdp_inventory_calc_js' );

        $vin        = ( isset( $this->parameters['vin'] ) ? array( 'vin' => $this->parameters['vin'] ) : array() );
        $vehicle_id = ( isset( $this->parameters['vms_id'] ) ? array( 'vms_id' => $this->parameters['vms_id'] ) : array() );
        // db vehicle.
        $vehicle_identifier = ! empty( $vehicle_id ) ? $vehicle_id : $vin;
        $db_vehicle_result  = $db_requests->cdp_db_init( 'inventory', $vehicle_identifier );
        $db_vehicle         = $db_vehicle_result ? $db_vehicle_result[0] : array();
        $vin                = ( isset( $db_vehicle['vin'] ) ? array( 'vin' => $db_vehicle['vin'] ) : array() );

        // Redirect if not found.
        $site_url = site_url();
        $rules    = get_option( 'rewrite_rules' );
        $url_rule = isset( $rules['^(inventory)'] );
        if ( empty( $db_vehicle ) && ( empty( $vin ) || empty( $vehicle_id ) ) ) {
            $redirect_class = 'new' === strtolower( $this->theme_options['theme']['overrides']['saleclass'] ) ? 'New' : 'Used';
            if ( $url_rule ) {
                wp_safe_redirect( $site_url . '/inventory/' . $redirect_class, 301 );
            } else {
                wp_safe_redirect( $site_url . '?taxonomy=inventory&saleclass=' . $redirect_class, 301 );
            }
            exit;
        }

        if ( ! empty( $this->company['seo'] ) ) {
            ( new Dynamic_Site_Headers( $db_vehicle['dealer_id'] ) )->apply_headers( $this->parameters );
        }

        $this->parameters['saleclass']    = ( isset( $db_vehicle ) ? $db_vehicle['saleclass'] : 'all' );
        $this->parameters['vehicleclass'] = ( isset( $db_vehicle ) ? $db_vehicle['vehicleclass'] : '' );
        $this->parameters['dealer']       = ( isset( $db_vehicle ) ? $db_vehicle['dealer'] : '' );
        $this->parameters['dealer_id']    = ( isset( $db_vehicle ) ? $db_vehicle['dealer_id'] : '' );

        // get photos, standard_equipment, dealer_options from api and merge into db vehicle.
        $api_vehicle = Remote_Requests::api_vehicle_vdp_call( $db_vehicle['dealer_id'], $vin['vin'] );
        $vehicle     = array_merge( $db_vehicle, $api_vehicle );

        $contact_info = array(
                'dealer_id'   => $vehicle['dealer_id'],
                'greeting'    => 'For more information', // TODO need to add an option.
                'dealer_name' => $this->company['name'],
                'phone'       => $this->company['phone'],
        );

        $saleclass                = $vehicle['saleclass'];
        $price                    = $fn_inventory->get_price_display(
                array(
                        'company' => $this->company,
                        'vehicle' => $vehicle,
                        'theme'   => 'inventory',
                )
        );
        $vehicle['primary_price'] = $price['primary_price'];
        // $parameters['saleclass']  = $saleclass;
        $loan_parameters = array(
                'make'      => $vehicle['make'],
                'model'     => $vehicle['model'],
                'trim'      => $vehicle['trim'],
                'year'      => $vehicle['year'],
                'saleclass' => $saleclass,
        );
        $fuel_economy    = array(
                'city'    => $vehicle['city'],
                'highway' => $vehicle['highway'],
        );

        $fn_inventory->apply_gravity_form_hooks( $vehicle );

        if ( ! empty( $vehicle ) ) {
            if ( $this->theme_options['theme']['inventory_display']['detail']['general']['social']['facebook']['enable'] ) {
                if ( 'used' === $vehicle['saleclass'] && $vehicle['certified'] ) {
                    $fb_saleclass = 'Certified Pre-Owned';
                } elseif ( 'used' === $vehicle['saleclass'] ) {
                    $fb_saleclass = 'Pre-Owned';
                } else {
                    $fb_saleclass = 'New';
                }
                $this->fb_title = $fb_saleclass . ' ' . $vehicle['year'] . ' ' . $vehicle['make'] . ' ' . $vehicle['model'] . ' ' . $vehicle['trim'];
                $wp_head_args   = array(
                        'url'      => $page_url,
                        'fb_title' => $this->fb_title,
                        'fb_desc'  => $this->fb_title . ' from ' . $company_name . ' in ' . $this->company['city'] . ', ' . $this->company['state'],
                        'fb_image' => $fn_inventory->no_photo_replace( $vehicle['thumbnail'] ),
                );
                add_action(
                        'wp_head',
                        function () use ( $wp_head_args ) {
                            $content = '<meta property="og:url" content="' . $wp_head_args['url'] . '" />' . "\n";
                            $content .= '<meta property="og:type" content="website" />' . "\n";
                            $content .= '<meta property="og:title" content="' . $wp_head_args['fb_title'] . '" />' . "\n";
                            $content .= '<meta property="og:image" content="' . $wp_head_args['fb_image'] . '" />' . "\n";
                            helpers::output_wp_kses( $content );

                        }
                );
            }
        }
        break;
    case 'list':
        wp_enqueue_style( 'cdp_inventory_range_slider_css', CDP_CSS . 'templates/inventory/range_slider.css', array(), CDP_VERSION );
        // The seo_hack was in the initial setup.
        if ( ! empty( $this->company['seo'] ) ) {
            ( new Dynamic_Site_Headers( $this->company['dealer_id'] ) )->apply_headers( $this->parameters );
        }
        $custom_sort = Option::check_for_option(
                'cdp_theme_options',
                array(
                        'theme',
                        'inventory_display',
                        'list',
                        'sort',
                        'custom',
                )
        );
        $db_requests->cdp_admin_update_sort( $custom_sort );
        $vehicles            = $db_requests->cdp_db_init( 'inventory', $this->parameters );
        $vehicle_total_found = $db_requests->cdp_db_init( 'searchtotal', $this->parameters );
        $on_page             = ( $this->parameters['page'] ?? 1 );
        $per_page            = Option::check_for_option(
                'cdp_theme_options',
                array(
                        'theme',
                        'overrides',
                        'per_page',
                )
        );
        $page_total          = ( $vehicle_total_found > 0 ? ceil( $vehicle_total_found / $per_page ) : 1 );
        $args                = array(
                'base'      => add_query_arg( 'page', '%#%' ),
                'current'   => $on_page,
                'total'     => $page_total,
                'next_text' => __( 'Next &raquo;', 'cardealerpress' ),
                'prev_text' => __( '&laquo; Previous', 'cardealerpress' ),
                'show_all'  => false,
                'type'      => 'plain',
                'add_args'  => false,
        );

        $search_input_class = '';
        if ( Option::check_for_option(
                'cdp_theme_options',
                array(
                        'theme',
                        'inventory_display',
                        'list',
                        'keywords',
                        'enable',
                )
        )
        ) {
            wp_enqueue_script( 'cdp_inventory_typeahead_js', CDP_JS . 'jquery-typeahead/typeahead.js', array( 'jquery' ), '0.11.1', true );
            wp_register_script( 'cdp_inventory_general_js', CDP_JS . 'templates/inventory/general.js', array( 'jquery' ), CDP_VERSION, true );
            $typeahead_keywords = Option::check_for_option(
                    'cdp_theme_options',
                    array(
                            'theme',
                            'inventory_display',
                            'list',
                            'keywords',
                            'pot',
                    )
            ) ?? array();
            wp_localize_script( 'cdp_inventory_general_js', 'cdp_keywords', $typeahead_keywords );
            wp_enqueue_script( 'cdp_inventory_general_js' );
            $search_input_class = 'search-typeahead';
        }

        if ( function_exists( 'gravity_form_enqueue_scripts' ) ) {
            $gform_id = Option::check_for_option(
                    'cdp_theme_options',
                    array(
                            'theme',
                            'inventory_display',
                            'list',
                            'general',
                            'buttons',
                            'form',
                            'gform_id',
                    )
            );
            if ( $gform_id ) {
                $gform_element = "<div style='display: none;' id='inventory-gform-id' data-form='$gform_id'></div>";
                $gform_class   = 'inventory_get_gform';
                gravity_form_enqueue_scripts( $gform_id, true );
            }
        }
        break;
}


$script_assets = Option::check_for_option( 'cdp_theme_options', array(
        'theme',
        'inventory_display',
        'script_assets'
) );
if ( $script_assets ) {
    $fn_inventory->cdp_apply_setting_scripts( $script_assets, $page, $this->parameters['saleclass'] );
}
$style_assets = Option::check_for_option( 'cdp_theme_options', array( 'theme', 'inventory_display', 'style_assets' ) );
if ( $style_assets ) {
    $fn_inventory->cdp_apply_setting_styles( $style_assets, $page, $this->parameters['saleclass'] );
}

get_header();
flush();


$content = "\n <!-- [CDP Version] : " . CDP_VERSION . " --> \n";
$content .= '<div id="cardealerpress-inventory" class="' . $current_theme . '-theme-wrapper db-version" theme="' . $current_theme . '" data-saleclass="' . ( isset( $vehicle ) ? ucfirst( $vehicle['saleclass'] ) : $this->parameters['saleclass'] ) . '" >';
helpers::output_wp_kses( $content );

/*********
 * Header Banner Add
 */
$banners = Option::check_for_option( 'cdp_theme_options', array( 'theme', 'inventory_display', 'banners' ) );
if ( ! empty( $banners ) && $page !== 'detail' ) {
    $content        = '<div id="cdp-banner-top-container">';
    $banner_results = $fn_inventory->cdp_get_banners( $page, 'top', $banners, $this->parameters );
    foreach ( $banner_results as $banner ) {
        $content .= $banner;
    }
    $content .= '</div>';
    helpers::output_wp_kses( $content );
}
/*********
 * Gravity Form Add
 */
echo wp_kses_post( ! empty( $gform_element ) ? $gform_element : '' );
/*********
 * Facebook SDK
 */
if ( Option::check_for_option(
        'cdp_theme_options',
        array(
                'theme',
                'inventory_display',
                'detail',
                'general',
                'social',
                'facebook',
                'enable',
        )
)
) {
    ?>
    <div id="fb-root"></div>
    <script>(function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id;
            js.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.11';
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));</script>
    <?php
}

/*********
 * Inventory Content
 */
require $theme_path . '/' . $page . '.php';
/*********
 * Footer Banner Add
 */
if ( ! empty( $banners ) ) {
    $content        = '<div id="cdp-banner-bottom-container">';
    $banner_results = $fn_inventory->cdp_get_banners( $page, 'bottom', $banners, $this->parameters );
    foreach ( $banner_results as $banner ) {
        $content .= $banner;
    }
    $content .= '</div>';
    helpers::output_wp_kses( $content );

}
helpers::output_wp_kses( '</div>' );


$scripts = Option::check_for_option(
        'cdp_theme_options',
        array(
                'theme',
                'inventory_display',
                $page,
                'scripts',
                'inject',
        )
);
if ( $scripts ) {
    $script_data = urldecode( stripslashes( $scripts ) );
    if ( 'detail' === $page ) {
        $script_data = str_replace( '[VIN]', $vehicle['vin'], $script_data );
        $script_data = str_replace( '[STOCK]', $vehicle['stock'], $script_data );
    }
    echo '<div id="cdp-inventory-injected-script-' . esc_attr( $page ) . '">';
    wp_register_script( 'cdp_injector_js', CDP_JS . 'templates/inventory/injector.js', 'jquery', CDP_VERSION, true ); //injector.js is a placeholder file.
    wp_enqueue_script( 'cdp_injector_js' );
    wp_add_inline_script( 'cdp_injector_js', $script_data );
    echo '</div>';
}

$both_styles   = Option::check_for_option(
        'cdp_theme_options',
        array(
                'theme',
                'inventory_display',
                'general',
                'both',
                'styles',
        )
);
$list_styles   = Option::check_for_option(
        'cdp_theme_options',
        array(
                'theme',
                'inventory_display',
                'list',
                'styles',
        )
);
$detail_styles = Option::check_for_option(
        'cdp_theme_options',
        array(
                'theme',
                'inventory_display',
                'detail',
                'styles',
        )
);
switch ( true ) {
    case 'list' === $page:
        $styles = array_merge( $both_styles, array_filter( $list_styles ) );
        break;
    case 'detail' === $page:
        $styles = array_merge( $both_styles, array_filter( $detail_styles ) );
        break;
}
if ( $styles['inject'] ) {
    $content = '<div id="cdp-inventory-injected-style-' . $page . '">';
    $content .= '<style>' . urldecode( stripslashes( $styles['inject'] ) ) . '</style>';
    $content .= '</div>';
    echo wp_kses( $content, array( 'style' => array(), 'div' => array( 'id' => array() ) ) );
}


if ( Option::check_for_option( 'cdp_admin_options', array( 'admin', 'general', 'debug_plugin_info' ) ) ) {
    echo "\n" . '<!--' . "\n";
    echo '########' . "\n";
    if ( 'list' == $page ) {
        $dynamic_site_headers = new Dynamic_Site_Headers( $this->company['dealer_id'] );
    } else {
        $dynamic_site_headers = new Dynamic_Site_Headers( $db_vehicle['dealer_id'] );
    }
    $dynamic_site_headers->apply_headers( $this->parameters );
    if ( isset( $dynamic_site_headers->request_stack['url'] ) ) {
        echo 'SEO Helper Url: ' . esc_url( $dynamic_site_headers->request_stack['url'] ) . "\n";
    }
    echo 'Company: ' . wp_json_encode( $this->company ) . "\n";
    echo 'VMS: ' . wp_json_encode( $this->vms ) . "\n";
    echo '########' . "\n";
    echo '-->' . "\n";
}

flush();
get_footer();
?>
