<?php

namespace CarDealerPress\Includes\Functions;

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

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

class Show_Theme {
	use Logger;


	public $theme_options;
	public $admin_options;
	public $company;
	private $compare_vehicles;
	private $saved_vehicles;
	private $print_page;
	private $autocheck_flag;
	private $parameters;
	/**
	 * @var int|mixed|string
	 */
	private $autocheck_vin;
	/**
	 * @var array|null|string
	 */
	private $taxonomy;
	/**
	 * @var VehicleManagementSystem
	 */
	private $vms;
	public $db_requests;
	public $db_vehicle;
	public $sanitized_get;

	public function __construct() {
		// @codingStandardsIgnoreStart
		$this->sanitized_get = helpers::sanitize_get($_GET);
		// @codingStandardsIgnoreEnd
		$this->set_option_variables();
		$this->vms = new VehicleManagementSystem( $this->admin_options['admin']['help']['host'], helpers::company_id() );
		$this->queue_templates();
	}

	public function set_option_variables() {
		$this->theme_options = Option::get_cdp_theme_options();
		$this->admin_options = Option::get_cdp_admin_options();
		$this->db_requests   = new Requests();
		$db_company          = $this->db_requests->cdp_company_request();
		if ( $db_company ) {
			$this->company = $db_company[0];
		} else {
			$this->company = array();
		}
	}


	public function queue_templates() {
		add_action( 'template_redirect', array( &$this, 'routes' ), 100 );
	}

	public function routes() {
		global $wp_query;
		$debug_mode = $this->admin_options['admin']['general']['debug_plugin_info'] ?? null;
		if ('on' === $debug_mode) {
			$this->log_error_page();
		}
		$query = $wp_query->query_vars;
		// GET has the params for sc inventory_detail shortcode form.
		// @codingStandardsIgnoreStart
		$query_and_get = array_merge($query, $this->sanitized_get);
		// @codingStandardsIgnoreEnd
		$yoast_sitemap = ( isset( $query_and_get['sitemap'] ) ) ? $query_and_get['sitemap'] : '';
		$this->taxonomy = ( isset( $query_and_get['taxonomy'] ) ) ? $query_and_get['taxonomy'] : $yoast_sitemap;

		// todo future vms is legacy, should find another way to check for inventory, maybe db check?
		if ( $this->vms && $this->taxonomy ) {
			switch ( $this->taxonomy ) {
				case 'inventory';
					if ( $this->admin_options['admin']['help']['host'] ) {

						$this->parameters = $this->get_parameters();
						$this->fix_bad_wordpress_assumption();

						$current_theme = apply_filters( 'cdp_theme_name', $this->theme_options['theme']['general']['name'] );
						$theme_path    = CDP_DIR_PATH . 'templates/inventory/' . $current_theme;
						$theme_path    = apply_filters( 'cdp_theme_path', $theme_path );

						if ( $this->autocheck_flag ) {
							include_once CDP_DIR_PATH . 'templates/inventory/autocheck.php';
						} elseif ( $this->print_page ) {
							$file = CDP_DIR_PATH . 'templates/inventory/print.php';
							$file = apply_filters( 'cdp_print', $file );
							include_once $file;
						} elseif ( $this->saved_vehicles ) {
							$file = CDP_DIR_PATH . 'templates/inventory/saved.php';
							include_once $file;
						} elseif ( $this->compare_vehicles ) {
							$file = CDP_DIR_PATH . 'templates/inventory/compare.php';
							include_once $file;
						} else {
							if ( isset( $this->parameters['vin'] ) || isset( $this->parameters['vms_id'] ) ) {
								add_action( 'wp_head', array( $this, 'cdp_add_canonical_link' ) );
							}

							if ( $handle = opendir( CDP_DIR_PATH . 'templates/inventory' ) ) {
								while ( false !== ( $file = readdir( $handle ) ) ) {
									include_once CDP_DIR_PATH . 'templates/inventory/invdb-index.php';
								}
								closedir( $handle );
							} else {
								helpers::output_wp_kses(__FUNCTION__ . ' Could not open directory at: ' . $theme_path );

								return false;
							}
						}

						$this->stop_wordpress();
					}
					break;
				case (bool) preg_match( '/new|used|video/', $this->taxonomy ):
					if ( ! empty( $this->company['seo'] ) ) {
						$sitemap_path = CDP_DIR_PATH . 'templates/sitemap';
						$handle = opendir( $sitemap_path );
						if ( $handle ) {
							while ( false !== ( $file = readdir( $handle ) ) ) {
								if ( 'index.php' === $file ) {
									include_once $sitemap_path . '/index.php';
								}
							}
							closedir( $handle );
						} else {
							$this->append_log( array( 'message' => 'CDP Error: Sitemap' .__FUNCTION__ . ' Could not open directory at: ' . $sitemap_path ) );
							// @codingStandardsIgnoreStart
							error_log( __FUNCTION__ . ' Could not open directory at: ' . $sitemap_path);
							// @codingStandardsIgnoreEnd

							return false;
						}

						$this->stop_wordpress();
					}
					break;
			}
		}
		// Handle Gravity Form Pop-up.

		if ( isset( $query_and_get['name'] ) && 'cdp-form-display' === $query_and_get['name'] && isset( $query_and_get['form_id'] ) ) {
			include_once CDP_DIR_PATH . 'templates/form-popup.php';
			$this->stop_wordpress();
		}
	}

	public function cdp_add_canonical_link() {
		$link_params    = array(
			'year'  => $this->parameters['year'],
			'make'  => $this->parameters['make'],
			'model' => $this->parameters['model'],
			'state' => $this->company['state'],
			'city'  => $this->company['city'],
			'vin'   => $this->parameters['vin'] ?? '',
			'vms_id'    => $this->parameters['vms_id'] ?? '',
		);
		$canonical_link = ( new Fn_Inventory() )->generate_inventory_link(array('params' => $link_params, 'type' => 1 ) );

		echo '<link href="' . esc_url(site_url() . $canonical_link) . '" rel="canonical" />';
	}

	public function get_parameters() {
		global $wp;
		global $wp_rewrite;

		$permalink_parameters = ! empty( $wp_rewrite->permalink_structure ) ? preg_split( "#[/]#", $wp->request) : array();
		# TODO refactor for robustness, need to keep the model_name together if it has a '-' in it, F-150, CR-V.
//		$permalink_parameters = ! empty( $wp_rewrite->permalink_structure ) ? preg_split( "#[/\-]#", $wp->request) : array();
//		if (isset($permalink_parameters[3])) {
//			if ( preg_match( '/Ford|Honda|Mazda/i', $permalink_parameters[2] ) ) {
//				if ( preg_match( '/(F)|(CR)|(HR)|(EX)|(CX)/', $permalink_parameters[3] ) ) {
//					$model = "$permalink_parameters[3]-$permalink_parameters[4]";
//					unset( $permalink_parameters[3] );
//					unset( $permalink_parameters[4] );
//					$permalink_parameters[3] = $model;
//				}
//				ksort( $permalink_parameters );
//				$permalink_parameters = array_values( $permalink_parameters );
//			}
//		}
		//$server_parameters    = isset( $this->sanitize_get ) ? array_map( array( &$this, 'sanitize_inputs' ), $this->sanitize_get ) : null;
		$server_parameters    = $this->sanitized_get ?? null;

		if ( isset( $server_parameters['trim'] ) ) {
			$server_parameters['trim'] = ( $this->sanitized_get['trim'] ?? '' );
		}
		$parameters             = array();
		$this->compare_vehicles = false;
		$this->saved_vehicles   = false;
		$this->print_page       = false;
		$this->autocheck_flag   = false;

		if ( 'inventory' === $this->taxonomy ) {
			$server_parameters['per_page'] = $this->theme_options['theme']['overrides']['per_page'];

			switch ( $this->theme_options['theme']['overrides']['saleclass'] ) {
				case 'new':
					$server_parameters['saleclass'] = 'New';
					break;
				case 'used':
					$server_parameters['saleclass'] = 'Used';
					break;
				case 'certified':
					$server_parameters['saleclass'] = 'Used';
					$server_parameters['certified'] = 'yes';
					break;
			}
			if ( isset( $permalink_parameters[1] ) && 'autocheck' === $permalink_parameters[1] ) {
				$this->autocheck_flag = true;
				$this->autocheck_vin  = ( isset( $permalink_parameters[2] ) ) ? $permalink_parameters[2] : 0;
			} elseif ( isset( $permalink_parameters[1] ) && 'saved-vehicles' === $permalink_parameters[1] ) {
				$this->saved_vehicles = true;
			} elseif ( isset( $permalink_parameters[1] ) && 'compare-vehicles' === $permalink_parameters[1] ) {
				$this->compare_vehicles = true;
			} else {
				foreach ( $permalink_parameters as $key => $value ) {
					switch ( $key ) {
						case 0:
							$index = 'taxonomy';
							break;
						case 1:
							if ( is_numeric( $value ) ) {
								$index = 'year';
							} else {
								$index = 'saleclass';
							}
							break;
						case 2:
							$index = 'make';
							break;
						case 3:
							$index = 'model';
							break;
						case 4:
							$index = 'state';
							break;
						case 5:
							$index = 'city';
							break;
						case 6:
							if ( 17 === strlen( $value ) ) {
								$index = 'vin';
							} else {
								$index = 'vms_id';
							}
							break;
						default:
							return;
							break;
					}
					$parameters[ $index ] = $value;
				}
				if ( isset( $server_parameters['print_page'] ) ) {
					$this->print_page = true;
				}
			}
		}
		// Need to add both vin and id to parameters.
		if ( isset( $parameters['vms_id'] ) ) {
			$vehicle_id = $parameters['vms_id'];
			$db_vehicle = $this->db_requests->cdp_inventory_special_request( 'vin', ' vms_id=' . $vehicle_id  );
			if ( ! empty( $db_vehicle ) ) {
				$parameters['vin'] = $db_vehicle[0]['vin'];
			}
		}

		return array_merge( $parameters, $server_parameters );
	}

	public function fix_bad_wordpress_assumption() {
		global $wp_query;
		$wp_query->is_home = false;
	}

	public function stop_wordpress() {
		exit;
	}

	public function log_error_page() {
		if ( function_exists( 'http_response_code' ) ) {
			$page_response = http_response_code();
			if ( 200 !== $page_response ) {
				$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;
				$referer       = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_REFERER'])) : '';
				$error_message = 'Response Code: ' . $page_response . ' | Page URL: ' . $page_url . ( ! empty( $referer ) ? ' | Referer: ' . $referer : '' );
				$this->append_log( array( 'message' => 'CDP Response Code Error Message (' . CDP_VERSION . ') - ' ) );
				$this->append_log( array( 'message' => $error_message ) );
			}
		}
	}

	public function sanitize_inputs( $input ) {
		if ( is_array( $input ) ) {
			foreach ( $input as $key => $value ) {
				$input[ $key ] = is_scalar( $value )
					? wp_kses_data( $value )
					: array_map(
						array(
							&$this,
							'sanitize_inputs',
						),
						$value
					);
			}
		} else {
			$input = wp_kses_data( $input );
		}

		return $input;
	}


}
