<?php

namespace CarDealerPress\templates\partials\inventory;

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\functions\Extender_Functions;
use CarDealerPress\Includes\Functions\Fn_Inventory;
use CarDealerPress\includes\helpers\helpers;
use CarDealerPress\Includes\Helpers\Option;

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

// for ajax themes
class List_Search_Filters {
	// search - year, odometer, price.
	public static function range_dropdown( $args ) {
		// initial creates dropdowns
		$theme_options = Option::get_cdp_theme_options();
		$label = $args['display_label'];
		$name    = esc_html($args['name']);
		$data         = (new Extender_Functions())->get_range_list( $name );
		$content     = "<div id='filter-$name' class='search-list search-$name search-wrapper-dropdown'>";

		$content .= 'on' === $label ? "<div id='$name-range' >" : "";
		$content .= 'on' === $label ? "<div class='search-label show-label'>".ucfirst( $name )."</div>" : "";
		$content .= "<div class='range-dropdown-container search-dropdown'>";
		$content .= '<div class="search-content from">';
		// from
		$content .= '<select class="input-action select-' . $name . '_from ignore" name=' . $name . '_from>';
		$content .= sprintf(
			'<option value="0">%s</option>',
			'' === $label ? ucfirst( $name ) . ' From' : 'From'
		);
$buckets = [];
		if ( preg_match('/odometer|price/i',$name)) {
			$bucket_size = $theme_options['theme']['inventory_display']['list']['search_filters']['general'][$name.'_step'];
			$buckets = self::range_buckets( $data['data'], $bucket_size );
		} else {
			$buckets = $data['dataCount'] ?? array();
		}
		if ( $buckets ) {
			foreach ( $buckets as $item => $value ) {
				$content .= self::range_option( $name, $item, $value );
			}
		}
		$content .= '</select>';
		$content .= '</div>';
		// To.
		$content .= '<div class="search-content to">';
		$content .= '<select class="input-action select-' . $name . '_to ignore" name=' . $name . '_to>';
		$content .= sprintf(
			'<option value="0">%s</option>',
			'' === $label ? ucfirst( $name ) . ' To' : 'To'
		);

		$data_reverse = array_reverse( $buckets, true );
		foreach ( $data_reverse as $item => $value ) {
			$content .= self::range_option( $name, $item, $value );
		}
		$content .= '</select>';
		$content .= '</div>';

		$content .= '</div>';
		$content .= '</div>';
		$content .= '' === $label ? "" : "</div>";

		return $content;
	}

	public static function range_option( $name, $value, $count = null ) {
		$content = '';
		if (!preg_match('/year|city|highway/i', $name) ) {
			$value = $count;
		}
		switch ( true ) {
			case preg_match('/year|city|highway/i', $name):
				$content = sprintf(
					'<option value="%d">%d (%d)</option>',$value, $value, $count);
				break;
			case 'odometer' === $name:
				$content = "<option value='$value'>".self::range_number_format( $value )."</option>";
				break;
			case 'price' === $name:
				$content = "<option value='$value'>$".self::range_number_format( $value )."</option>";
				break;
		}

		return $content;
	}

	public static function range_number_format( $value ) {
		return number_format( $value, 0, '', ',' );
	}

	public static function range_buckets( $data, $bucket_size ) {
		$buckets = [];
		sort( $data, SORT_NUMERIC );
		foreach ( $data as $value ) {
			$val = (int) $value;
			// Round down to nearest $bucket_size
			$bucket    = floor( $val / $bucket_size ) * $bucket_size;
			$buckets[] = (string) $bucket;
		}
		// make sure last bucket is ceiled
		$last      = array_pop( $data );
		$bucket    = ceil( (int) $last / $bucket_size ) * $bucket_size;
		$buckets[] = (string) $bucket;

		$buckets = array_unique( $buckets );
		sort( $buckets, SORT_NUMERIC );
		if ( empty( $buckets ) ) {
			$buckets = [ '0' ];
		}

		return $buckets;
	}

	public static function range_sliders($args) {
		$name       = $args['name'];
		$label      = isset($args['display_label']) ? 'show-label' : '' ;
		$content    = '<div class="search-list search-' . $name . ' search-wrapper-slider">';
			$content    .= "<div class='search-label $label'>" . ucfirst( $name ) . "</div>";
			$content    .= '<div class="search-content">';
				$content    .= "<input type='text' id='$name-range-values' class='search-values' readonly/>";
			$content    .= "</div>";
			$content    .= "<div id='$name-range-slider' class='range-slider' data-name='$name'></div>";

			$data_results  = ( new Extender_Functions() )->get_range_list( $name );
			$theme_options = Option::get_cdp_theme_options();
			$bucket_size   = 1;
			if ( 'year' !== $name ) {
				$bucket_size = $theme_options['theme']['inventory_display']['list']['search_filters']['general'][ $name . '_step' ];
			}
			$buckets = self::range_buckets( $data_results['data'], $bucket_size );
			if ( count( $buckets ) === 1 ) {
				$low = $high = array_shift( $buckets );
			} else {
				$low  = array_shift( $buckets );
				$high = array_pop( $buckets );
			}

			//$content .= "<div id='$name-range-slider-details' class='range-slider-details' data-name='$name' data-step='$bucket_size' data-low='$low' data-high='$high'></div>";
		$content .= "</div>";

		$range_data = array(
			'type'    => $name,
			'step'    => $bucket_size,
			'default' => array(
				'low'  => $low,
				'high' => $high,
			),
		);
		$content    .= ( new Fn_Inventory() )->build_slider_script( $range_data );
		return $content;
	}

	public static function dropdown_checkbox( $args ) {
		$name = $args['name'];
		$label      = $args['display_label'] ? 'show-label' : '' ;
		$content       = "<div id='filter-$name' class='search-list search-$name search-action'>";
		$content .= '' === $label ? '' : "<div id='search-multi-select-$name' class='search-label $label'>" . ucfirst( $name ) . "</div>";
		$content .= "<div class='dropdown-section' >";
		if ('features' === $name ) {
			$name = 'tags';
		}
		$content .= "<div class='search-content'>";
		$content .= "<div class='multi-select' data-placeholder='placeholder' data-name='$name'>";
			$content .= "<div class='select-trigger'>";
			$placeholder = '' === $label ? "Features" : 'Select Options';
			$content .= "<span class='select-text placeholder'>$placeholder</span>";
			$content .= "<div class='arrow'></div>";
			$content .= "</div>";
			$content .= "<div class='dropdown-list filters' data-name='$name'>";
		$passed_parameters = $args['parameters'];
		$data         = (new Requests())->cdp_db_init( $name, $passed_parameters );
		$exclude = array();
		$current = array();
		if ( 'tags' === $name ) {
			$current      = ( isset( $passed_parameters[ 'tags' ] ) ? explode( ',', $passed_parameters['tags'] ) : array() );
			$exclude = Option::check_for_option(
				'cdp_theme_options',
				array(
					'theme',
					'inventory_display',
					'tags',
					'exclude',
				),
				array()
			);
		}
		$replace      = array( '_', '-' );
		if ( $data ) {
			foreach ( $data as $item ) {
				if ( $item && ! in_array( $item, $exclude, true ) ) {
					$item_value = ucwords( str_replace( $replace, ' ', $item ) );
					$content .= "<div class='dropdown-item' data-name='$item'>";
					$content .= "<label for='$item'>$item_value</label>";
					$content .= "<input type='checkbox' id='$item' name='$item' value='$item_value' class='input-$name'>";
					$content .= '</div>';
				}
			}
		}
		$content .= '</div>'; // #dropdownList
		$content .= '</div>'; // .search-content
		$content .= '</div>'; // .multi-select
		$content .= '</div>'; // .dropdown-section
		$content .= '</div>'; // #filter

		return $content;

	}

	public static function dropdown_list( $args ) {
		$label = $args['display_label'];
		$name    = esc_html($args['name']);
		$dropdown_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;
			case 'fuel_type':
				$dropdown_name .= 'Fuel Type';
				break;
			default:
				$dropdown_name .= esc_html(ucfirst( $name ));
		}
		$results = ( new Extender_Functions() )->get_lists( $name );
		$content       = "<div id='filter-$name' class='search-list search-$name search-dropdown'>";
		$content .= 'on' === $label ? "<div class='search-label show-label'>" . $dropdown_name . "</div>" : '';
		$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">' . ( '' === $label ? $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>';
		if ('color' == $name){
			$content .= List_Search_Filters::dropdown_list( array('name' => 'color_int', 'display_label' => $label));
		}
		return $content;
	}

	public static function range_mpg_dropdown( $args ) {
		// initial creates dropdowns
		$label = $args[0];
		$content       = "<div id='filter-mpg' class='search-mpg search-wrapper-dropdown'>";
		$content .= '<div class="mpg-container input-radio mpg-search-radio-wrapper">';

		array_shift( $args );
		foreach ( $args as $item ) {
			$name  = esc_html( $item );
			$data  = ( new Extender_Functions() )->get_range_list( $name );
			$temp         = $data['data'];
			$data['data'] = array_values( array_filter( $temp, fn( $v ) => $v !== "" ) );
			$content .= "<div id='filter-$name' class='search-list search-$name search-wrapper-dropdown'>";

			$content .= 'on' === $label ? "<div id='$name-range' >" : "";
			$content .= 'on' === $label ? "<div class='search-label show-label'>MPG " . ucfirst( $name ) . "</div>" : "";
			$content .= "<div class='range-dropdown-container search-dropdown'>";
			$content .= '<div class="search-content from">';
			// from
			$content .= '<select class="input-action select-' . $name . '_from ignore" name=' . $name . '_from>';
			$content .= sprintf(
				'<option value="0">%s</option>',
				'on' === $label ? 'From' : ucfirst( $name ) . ' From'
			);
			$buckets = [];
			$buckets = $data['dataCount'] ?? array();
			foreach ( $buckets as $item => $value ) {
				$content .= self::range_option( $name, $item, $value );
			}

			$content .= '</select>';
			$content .= '</div>';
			// To.
			$content .= '<div class="search-content to">';
			$content .= '<select class="input-action select-' . $name . '_to ignore" name=' . $name . '_to>';
			$content .= sprintf(
				'<option value="0">%s</option>',
				'on' === $label ? 'To' : ucfirst( $name ) . ' To'
			);

			$data_reverse = array_reverse( $buckets, true );
			foreach ( $data_reverse as $item => $value ) {
				$content .= self::range_option( $name, $item, $value );
			}
			$content .= '</select>';
			$content .= '</div>';

			$content .= '</div>';
			$content .= '</div>';
			$content .= 'on' === $label ? "</div>" : "";
		}
		$content .= '</div>'; // end container
		$content .= '</div>'; // end filter wrapper

		return $content;
	}

}