<?php

include_once './core/item.class.php';

class admin_item {

	private $base_object;
	private $db;
	private $config;
	private $layout_object;

	public function __construct($base_object, $layout_object) {
		$this->base_object = $base_object;
		$this->db = $base_object->db;
		$this->config = $base_object->config_object;
		$this->layout_object = $layout_object;
	}

	public function run() {
		if (isset($_GET['action'])) {
			$action = $_GET['action'];
		} else {
			$this->default_action();
		}

		if ($action == 'get_by_string') {
			$this->get_by_string();
		} else if ($action == 'get_by_id') {
			$this->get_by_id();
		} else {
			$this->default_action();
		}
	}

	private function default_action() {
		$return['status'] = 'error';
		$return['message'] = "ERROR: Unbekannter Methodenaufruf.";

		echo json_encode($return);
	}

	private function get_by_string() {
		if (isset($_GET['data'])) {
			$search = $_GET['data'];
		} else {
			$search = false;
		}

		if ($search) {
			$safe = $this->db->real_escape_string($search);

			$sql = "SELECT
						i.*,
						m.name AS manufacturer
					FROM
						items i
					LEFT JOIN
						manufacturers m
					ON 
						m.id = i.manufacturer_id
					WHERE
						i.number LIKE '%".$safe."%'
					OR
						i.name LIKE '%".$safe."%'
					OR
						i.ean_code LIKE '%".$safe."%'
					OR
						i.vendor_item_number LIKE '%".$safe."%'
					OR
						i.short_description LIKE '%".$safe."%'
					OR
						m.name LIKE '%".$safe."%'";

			$result = $this->db->query($sql);

			$hits = $result->num_rows;
			$data = array();
			if ($hits) {
				$i = 0;
				while ($obj = $result->fetch_object()) {
					$data[] = $obj;
					if ($i++ == 5) {
						break;
					}
				}
			}

			$return_data = array('status' => 'success', 'data' => $data, 'hits' => $hits);
		} else {
			$return_data = array('status' => 'no_argument_data', 'message' => 'Keine Daten &Uuml;bergeben.');
		}

		echo json_encode($return_data);
	}

}
