<?php
$matchingItemNumberFirst = true;

include_once 'itemsearch.class.php';

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

$strings = explode(' ', $searchString);
if (count($strings) == 1) {
    $searchString = trim($searchString);
}
else {
    $searchString = '';
    $string_type = 0;
    $strings = array_reverse($strings);
    foreach ($strings as $str) {
        $str = trim($str);
        // ganzzahl
        if (ctype_digit($str)) {
            $searchString = $str;
            $string_type = 2;
        }
        elseif (!ctype_alpha($str) && $string_type != 2) {
            $searchString = $str;
            $string_type = 1;
        }
        elseif ($string_type == 0) {
            $searchString = $str;
        }
        
    }
}

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

$ItemsClass->makeHistory();

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
		";
	}
}

