<?php
/*
 * @version			$Id: index.php 10381 2008-06-01 03:35:53Z $
 * @package			Carteasy
 * @copyright		Copyright (C) 2005 - 2011 Wlanium
 * @license			proprietary
 * @author			Thomas Bartelt
 * Carteasy is a web shop system
 */

class ItemInventory {

	private $item_id;
	private $db;
	private $error;

	function __construct() {
		$this->base_object = Registry::get('base');
		$this->db = Registry::get('base')->db;
		$this->error = '';
	} // end constructor

	public function get_type_name($type_id) {
		$name = '';
		switch ($type_id) {
			case 1:
				$name = 'Ladenverkauf';
				break;
			case 2:
				$name = 'Wareneingang';
				break;
			case 3:
				$name = 'Verlust';
				break;
			case 4:
				$name = 'Eigenverbrauch';
				break;
			case 5:
				$name = 'Onlineverkauf';
				break;
		}
		return $name;
	}


	public function get_by_id($id) {
		$sql = "SELECT *
			FROM item_inventory
			WHERE id = $id";

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

		if ($result->num_rows > 0) {
			$data = $result->fetch_object();

			return $data;
		}

		return false;
	} // end get_by_id

	// object id description:
	// 1: Ladenverkauf
	// 2: Wareneingang
	// 3: Verlust
	// 4: Eigenverbrauch
	// 5: Onlineverkauf
	public function get_by_object_id($object_id, $type_id) {
		$sql = "SELECT *
		FROM item_inventory
		WHERE inventory_object_id = $object_id AND inventory_object_type_id = $type_id";

		$result = $this->db->query($sql);
		$data = array();
		while ($obj = $result->fetch_object()) {
			//$obj->item_tax_sum = $obj->price_sum * $obj->item_tax / 100;
			$obj->item_tax_sum = $obj->price_sum / (100 + $obj->item_tax) * $obj->item_tax;
			$data[] = $obj;
		}

		return $data;
	} // end get_by_id


	public function get_all_item_inventory($item_id) {
		$sql = "SELECT *
			FROM item_inventory
			WHERE item_id = $item_id ORDER BY created DESC
		";

		$result = $this->db->query($sql);
		$data = array();
		while ($obj = $result->fetch_object()) {
			if ($obj->inventory_object_type_id == 2) {
				// get costs with shipping costs
				include_once './core/incomming_goods.class.php';
				$incomming_goods_object = new Incomming_goods($this->base_object);
				$incomming_data = $incomming_goods_object->get_by_id($obj->inventory_object_id);
				foreach ($incomming_data->item_list as $incomming_item) {
					if ($incomming_item->id == $obj->id) {
						$obj->price_sum = $incomming_item->item_price_ek;
					}
				}

				$obj->price_sum *= $obj->amount;
			}
			//$obj->item_tax_sum = $obj->price_sum * $obj->item_tax / 100;
			$obj->item_tax_sum = $obj->price_sum / (100 + $obj->item_tax) * $obj->item_tax;
			if ($obj->inventory_object_type_id != 2) {
				$obj->price_sum = $obj->price_sum - $obj->item_tax_sum;
			}
			$obj->type_name = $this->get_type_name($obj->inventory_object_type_id);
			$data[] = $obj;
		}

		return $data;
	} // end get_by_id

	public function add($data) {
		// 🚀 FIX: Lightweight item data query - verhindert 504 Timeouts!
		// Statt vollständigem Item->get_data() nur benötigte Felder laden
		$sql = "SELECT id, number, name, tax_id FROM items WHERE id = " .
			   $this->db->real_escape_string($data['item_id']) . " LIMIT 1";
		$result = $this->db->query($sql);

		if (!$result || $result->num_rows === 0) {
			$this->error = 'Item not found with ID: ' . $data['item_id'];
			return false;
		}

		$item = $result->fetch_object();

		if (!isset($data['inventory_object_id'])) {
			$data['inventory_object_id'] = 0;
		}
		if (!isset($data['price_sum'])) {
			$data['price_sum'] = 0;
		}
		if (!isset($data['create_time'])) {
			$data['create_time'] = 'CURRENT_TIMESTAMP';
		} else {
			$data['create_time'] = "'".$this->db->real_escape_string($data['create_time'])."'";
		}

		// clear old inventory
		if (isset($data['update']) && $data['update'] == 1) {
			$sql = "
				DELETE FROM item_inventory
				WHERE item_id=".$this->db->real_escape_string($item->id)." 
				AND inventory_object_type_id=".$this->db->real_escape_string($data['inventory_object_type_id'])."
				AND inventory_object_id=".$this->db->real_escape_string($data['inventory_object_id']);
			$this->db->query($sql);
		}

		$sql = "INSERT INTO item_inventory
			(
				item_id,
				item_number,
				item_name,
				item_tax,
				inventory_object_type_id,
				inventory_object_id,
				amount,
				price_sum,
				created
			) VALUES (
				'".$this->db->real_escape_string($item->id)."',
				'".$this->db->real_escape_string($item->number)."',
				'".$this->db->real_escape_string($item->name)."',
				'".$this->db->real_escape_string($item->tax_id)."',
				'".$this->db->real_escape_string($data['inventory_object_type_id'])."',
				'".$this->db->real_escape_string($data['inventory_object_id'])."',
				'".$this->db->real_escape_string($data['amount'])."',
				'".$this->db->real_escape_string($data['price_sum'])."',
				".$data['create_time']."
			)
		";
		$this->db->query($sql);

		// 🚀 FIX: Lightweight inventory update - keine full Item-Instanz nötig
		$count = $this->get_item_inventory_count($item->id);
		$sql = "UPDATE items SET inventory = " . intval($count) .
			   " WHERE id = " . $this->db->real_escape_string($item->id);
		$this->db->query($sql);

		return 1;
	}

	public function remove($data) {
		// 🚀 FIX: Lightweight - kein vollständiges Item-Objekt nötig!
		$item_id = intval($data['item_id']);

		if (!isset($data['inventory_object_id'])) {
			$data['inventory_object_id'] = 0;
		}

		// clear old inventory
		if (isset($data['update']) && $data['update'] == 1) {
			$sql = "DELETE FROM item_inventory
					WHERE item_id = " . $this->db->real_escape_string($item_id) . "
					AND inventory_object_type_id = " . $this->db->real_escape_string($data['inventory_object_type_id']) . "
					AND inventory_object_id = " . $this->db->real_escape_string($data['inventory_object_id']);
			$this->db->query($sql);
		}

		// 🚀 FIX: Lightweight inventory update - keine full Item-Instanz nötig
		$count = $this->get_item_inventory_count($item_id);
		$sql = "UPDATE items SET inventory = " . intval($count) .
			   " WHERE id = " . $this->db->real_escape_string($item_id);
		$this->db->query($sql);

		return 1;
	}

	public function get_item_inventory_count($item_id) {
		$count = 0;

		// Ensure item_id is valid
		if (!$item_id || !is_numeric($item_id)) {
			return 0;
		}

		$sql = "SELECT amount, inventory_object_type_id
		FROM item_inventory
		WHERE item_id = ".intval($item_id);

		$result = $this->db->query($sql);
		if ($result && $result->num_rows > 0) {
			while ($obj = $result->fetch_object()) {
				// Ensure amount is numeric
				$amount = is_numeric($obj->amount) ? floatval($obj->amount) : 0;
				
				if ($obj->inventory_object_type_id == 2) {
					// wareneingang
					$count += $amount;
				} else {
					// warenausgang
					$count -= $amount;
				}
			}
		}
		return $count;
	}

	public function update($data) {
		$sql = "UPDATE item_inventory
			SET ";
			foreach ($data as $var_name => $value) {
				$value = $this->db->real_escape_string($value);

				if ($this->theme_fields[$var_name] == 'integer') {
					$sql .= $var_name.'='.$value.', ';
				} else {
					$sql .= $var_name.'="'.$value.'", ';
				}
			}

		$sql = substr($sql, 0, -2);
		$sql .= ' WHERE id='.$this->id;
		$this->db->query($sql);

		// update item inventory count
		$item_id = $this->get_item_id($this->id);
		include_once './core/item.class.php';
		$item_object = new Item($this->base_object);
		$item_object->id = $item_id;
		$count = $this->get_item_inventory_count($item_id);
		$item_object->set_inventory($count);

		return 1;
	}

	public function delete($id) {
		// get item id for item update befor item inventory deleted
		$item_id = $this->get_item_id($id);

		// delete
		$sql = "DELETE FROM item_inventory WHERE id = ".$this->db->real_escape_string($id);
		$this->db->query($sql);

		// update item inventory count
		include_once './core/item.class.php';
		$item_object = new Item($this->base_object);
		$item_object->id = $item_id;
		$count = $this->get_item_inventory_count($item_id);
		$item_object->set_inventory($count);

		return 1;
	}

	public function get_item_id($inventory_id) {
		$sql = "SELECT item_id
			FROM item_inventory
			WHERE id = ".$this->db->real_escape_string($inventory_id);
		$result = $this->db->query($sql);
		if ($result) {
			$obj = $result->fetch_object();
			return $obj->item_id;
		} else {
			return 0;
		}
	}

}
