<?php

$matchingItemNumberFirst = true;

include_once 'itemsearch.class.php';

$searchString = $search['search_item'];
$ItemsClass = new ItemSearch($this->base_object);

$searchString = trim($searchString);

// Simple fix: Keep full string for multi-word searches
$strings = explode(' ', $searchString);
if (count($strings) > 1) {
	// For multi-word searches, keep original string if it looks like device model
	if (preg_match('/^[A-Z]{2,4}\s+[A-Z0-9+]{2,6}\s+[A-Z+]{1,4}(\s+[A-Z]{2,4})?$/i', $searchString)) {
		// Keep original device model string like "WTV 8734 XCM" or "KR 19F4 A++ IN"
		$searchString = trim($searchString);
	} else {
		// Fallback to old logic for other multi-word searches
		$searchString = '';
		$string_type = 0;
		$strings = array_reverse($strings);
		foreach ($strings as $str) {
			$str = trim($str);
			if (ctype_digit($str)) {
				$searchString = $str;
				$string_type = 2;
			} else if (!ctype_alpha($str) && $string_type != 2) {
				$searchString = $str;
				$string_type = 1;
			} else if ($string_type == 0) {
				$searchString = $str;
			}
		}
	}
}

$result = $ItemsClass->searchItems($searchString);

if (!isset($this->db)) {
	$this->db = $this->base_object->db;
}

if ($result['data'] && count($result['data']) > 0) {
	if (isset($search['item_category']) && $search['item_category'] > 0) {
		$sql = "
			SELECT
				i.*,
				i.default_image_file_name AS file_name,
				ip.price_1, ip.bargain_price_1
			FROM
				item_prices ip
			RIGHT JOIN
				items i
			ON
				i.id = ip.item_id
			AND
				ip.customergroup_id = ".$this->db->real_escape_string($this->base_object->customer_group->price_group_id)." 
			RIGHT JOIN
				item_structure_assign isa
			ON
				i.id = isa.item_id
			WHERE
				i.active = 1
			AND
				i.id IN (".implode(',', $result['data']).")
			AND 
				i.parent_id = 0
			AND 
				isa.structure_id = ".$this->db->real_escape_string($search['item_category'])."
			GROUP BY 
				i.id 
			ORDER BY 
				i.name DESC
		";
	} else {
		$sql = "
			SELECT
				i.*,
				i.default_image_file_name AS file_name,
				ip.price_1, ip.bargain_price_1
			FROM
				item_prices ip
			RIGHT JOIN
				items i
			ON
				i.id = ip.item_id
			AND
				ip.customergroup_id = ".$this->db->real_escape_string($this->base_object->customer_group->price_group_id)." 
			WHERE
				i.active = 1
			AND 
				i.id IN (".implode(',', $result['data']).")
			AND 
				parent_id = 0
			GROUP BY 
				i.id 
			ORDER BY 
				i.name DESC
		";
	}
}
