<?php

namespace CarDealerPress\Includes\Functions;

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

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

class Sc_Ajax {
	private $options;
	private $vms;
	private $company;

	public function __construct( $options, $vms, $company ) {
		$this->options = $options;
		$this->vms     = $vms;
		$this->company = $company;
	}

	public function sc_ajax_handler() {
		$data_request = array();
		$nonce_check = isset( $_REQUEST['nonce'] ) && wp_verify_nonce( sanitize_key($_REQUEST['nonce']), 'cdp_nonce' );
		if ($nonce_check ){
			$data_request = $_REQUEST;
		}
		$handler      = $data_request['handler'] ?? '';
		$request_data = $data_request['data'] ?? array();
		switch ( $handler ) {
			case 'search_shortcode':
				$output = array();
				switch ( $data_request['request'] ) {
					case 'saleclass':
						$data_request['params']['make'] = '';
						$data_request['params']['model'] = '';
						$data_request['params']['trim'] = '';
						$data_request['params']['model_code'] = '';
						break;
					case 'make':
						if ( '0' === $data_request['params']['make'] ) {
							$data_request['params']['trim'] = '';
							$data_request['params']['model_code'] = '';
						}
						$data_request['params']['model'] = '';
						break;
					case 'model':
						if ( '0' === $data_request['params']['model'] ) {
							$data_request['params']['trim'] = '';
							$data_request['params']['model_code'] = '';
						}
						break;
					case 'model_code':
						if ( '0' === $data_request['params']['model_code'] ) {
							$data_request['params']['trim'] = '';
						}
						break;
				}
				if ( 'Certified' === $data_request['params']['saleclass'] ) {
					$data_request['params']['saleclass'] = 'Used';
					$data_request['params']['certified'] = 'Yes';
				}
				if ( ! empty( $data_request['params'] ) && 'search' !== $data_request['request'] ) {
					foreach ( $data_request['params'] as $key => $value ) {
						if ( 'search' !== $key && 'saleclass' !== $key && 'certified' !== $key ) {
							$output['content']['dropdown'][ $key ] = ( new Fn_Inventory() )->cdp_get_db_dropdown_data( $key, $data_request['params'] );

							if ( $key === $data_request['request'] && empty( $output['content']['dropdown'][ $key ]['needle'] ) ) {
								$output['content']['dropdown'][ $key ]['needle'] = ( $data_request['params'][ $key ] ?? '' );
							}

							if ( $output['content']['dropdown'][ $key ]['needle'] && empty( $data_request['params'][ $key ] ) ) {
								$data_request['params'][ $key ] = $output['content']['dropdown'][ $key ]['needle'];
								switch ( $key ) {
									case 'make':
										//$data_request['params']['model'] = '';
										break;
									case 'model':
										//$data_request['params']['trim'] = '';
										break;
								}
							}
						}
					}

				}
				$output['url'] = ( new Fn_Inventory() )->cdp_construct_url( $data_request['params'] );
				break;
			case 'get_gform':
				$output['id'] = $data_request['params']['key'];
				( new Saved_Ajax() )->apply_ajax_gravity_hooks( $data_request['params']['hooks'] );
				$form              = gravity_form( $data_request['params']['form'], $display_title = false, $display_description = false, $display_inactive = false, $field_values = false, $ajax = true, $tabindex = 0, $echo = false );
				$output['content'] = '<div class="list-form-wrapper active">' . $form . '</div>';
				break;
			case 'get_vehicle_details':
				$output['id'] = $data_request['params']['key'];
				$params       = array( 'vin' => $data_request['params']['key'] );

				$vin = ( isset( $params['vin'] ) ? array( 'vin' => $params['vin'] ) : '' );
				// db vehicle
				$db_vehicle = ( $vin ? ( new Requests() )->cdp_db_init( 'inventory', $vin )[0] : array() );
				// 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 );
				switch ( $data_request['params']['tag'] ) {
					case 'info':
						$flags             = array( 'show_eq' => $this->options['theme']['inventory_display']['detail']['general']['show_standard_eq'] );
						$output['content'] = ( new Sc_Views() )->get_sc_detail_vehicle_info_display( $vehicle, $flags );
						break;
					case 'images':
						$output['content'] = ( new Sc_Views() )->get_sc_detail_images_display( $vehicle );
						break;
					default:
						$output['content'] = 'ERROR: Requesting selected inventory. Vehicle may be sold or is no longer in the system.';
						break;
				}

				break;
			case 'get_more_vehicles':
				$atts    = $data_request['params']['atts'];
				$form    = ( isset( $atts['form'] ) ? $atts['form'] : '' );
				$display = ( isset( $atts['display'] ) ? '_' . $atts['display'] : '' );
				unset( $atts['form'] );
				if ( 'certified' === $atts['saleclass'] ) {
					$atts['saleclass'] = 'used';
					$atts['certified'] = 'yes';
				}
				$vehicle_data      = $this->get_vehicle_inventory( $atts );
				$output['content'] = '';
				if ( is_array( $vehicle_data ) && ! empty( $vehicle_data ) ) {
					foreach ( $vehicle_data as $vehicle ) {
						$caller             = 'get_sc_detail' . $display . '_vehicles';
						$output['content'] .= ( new Sc_Views() )->$caller( $vehicle, $this->company, $this->options, $this->options['theme']['overrides']['custom_contact'], $form );
					}
				} elseif ( empty( $vehicle_data ) ) {
					$output['content'] = '<div id="cdp-ajax-end">All Vehicles have been loaded.</div>';
				} else {
					$output['content'] = 'ERROR: Requesting selected inventory. Vehicle may be sold or is no longer in the system.';
				}
				break;
			case 'update_dropdowns':
				$atts = $data_request['params']['atts'];
				if ( 'certified' === $atts['saleclass'] ) {
					$atts['saleclass'] = 'used';
					$atts['certified'] = 'yes';
				}
				switch ( $data_request['params']['filter'] ) {
					case 'saleclass':
						$stack = array( 'make', 'model', 'trim' );
						break;
					case 'make':
						$stack = array( 'model', 'trim' );
						break;
					case 'model':
						$stack = array( 'trim' );
						break;
					default:
						$stack = array(); // Trim Doesn't require a DD Update
						break;
				}
				$output = $this->dropdown_handler( $stack, $atts );
				break;
			default:
				$output['id']    = '';
				$output['error'] = 'That is not a valid FN parameter. Please check your string and try again.';
				break;
		}

		echo wp_json_encode( $output );
		wp_die();
	}

	public function get_vehicle_inventory( $params ) {
		$this->vms->tracer = 'Obtaining requested inventory. Ajax from SC Detail.';
		$inventory         = $this->vms->get_inventory( array( 'parameters' => $params ) );

		return $inventory;
	}

	public function dropdown_handler( $requests, $atts ) {
		$alt_id = $atts['dealer_id'] ?? 0;
		if ( ! empty( $requests ) ) {
			foreach ( $requests as $request ) {
				switch ( $request ) {
					case 'make':
						$data = ( new Fn_Inventory() )->cdp_generate_make_options( $this->vms, $atts['saleclass'], $this->options['theme']['overrides']['makes_new']['included'], false, $alt_id );
						if ( isset( $data['val'] ) ) {
							$atts['make']           = $data['val'];
							$results['make']['att'] = $data['val'];
						}
						$results['make']['display'] = $data['display'];
						break;
					case 'model':
						$data = ( new Fn_Inventory() )->cdp_generate_model_options( $this->vms, $atts['saleclass'], $atts['make'], false, $alt_id );
						if ( isset( $data['val'] ) ) {
							$atts['model']           = $data['val'];
							$results['model']['att'] = $data['val'];
						}
						if ( isset( $data['disabled'] ) ) {
							$results['model']['disabled'] = $data['disabled'];
						}
						$results['model']['display'] = $data['display'];
						break;
					case 'trim':
						$data = ( new Fn_Inventory() )->cdp_generate_trim_options( $this->vms, $atts['saleclass'], $atts['make'], $atts['model'], false, $alt_id );
						if ( isset( $data['val'] ) ) {
							$atts['trim']           = $data['val'];
							$results['trim']['att'] = $data['val'];
						}
						if ( isset( $data['disabled'] ) ) {
							$results['trim']['disabled'] = $data['disabled'];
						}
						$results['trim']['display'] = $data['display'];
						break;
				}
			}
		}

		return $results;
	}

}
