<?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
 * 
 * MODIFIED: PHP 8 Debug Fix - PFC Claude
 * Added silent error logging for price update debugging
 */

// DEBUG: Show only real errors, not deprecated spam!
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);  // DEBUG: Show errors temporarily!

// FIX PATHS für Testshop
set_include_path(get_include_path() . PATH_SEPARATOR . '/var/www/vhosts/newmail.intelectra.de/httpdocs/');

// Log in erlaubtem Verzeichnis
ini_set('log_errors', 1);
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/debug_price_update.log');

include_once './core/item.class.php';
include_once './core/manufacturer.class.php';
include_once './core/tax.class.php';
include_once './core/structure.class.php';
include_once './core/customer_group.class.php';
include_once './modules/list_and_edit.class.php';
include_once './core/vendors/edit.class.php';
include_once './core/item_inventory.class.php';
include_once './core/shipping_area.class.php';

class admin_item_editor {

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

	private $item_object;
	private $vendor_object;

	function __construct($base_object, $layout_object) {
		$this->base_object = $base_object;
		$this->config = $base_object->config;
		$this->layout_object = $layout_object;

		$this->db = $base_object->db;

		$this->item_object = new Item($this->base_object,false,0);

		$this->list_object = new ListAndEdit($base_object, $layout_object);
		$this->vendor_object = new Vendors_Edit($base_object);
	}

	function run() {
		if (isset($_GET['id']) && $_GET['id']) {
			$has_id = true;
			$id = intval($_GET['id']);
		} else if (isset($_POST['id']) && $_POST['id']) {
			$has_id = true;
			$id = intval($_POST['id']);
		} else {
			$has_id = false;
			$id = false;
		}

		$this->id = $id;

		if (isset($_POST['submit'])) {
			$is_submitted = true;
		} else {
			$is_submitted = false;
		}

		if (isset($_POST['show_price_and_marketing']) && $_POST['show_price_and_marketing']) {
			$this->layout_object->assign('show_price_and_marketing', 1);
		}
		if (isset($_POST['show_attributes']) && $_POST['show_attributes']) {
			$this->layout_object->assign('show_attributes', 1);
		}
		if (isset($_POST['show_versand']) && $_POST['show_versand']) {
			$this->layout_object->assign('show_versand', 1);
		}
		if (isset($_POST['show_seo']) && $_POST['show_seo']) {
			$this->layout_object->assign('show_seo', 1);
		}
		if (isset($_POST['show_lager']) && $_POST['show_lager']) {
			$this->layout_object->assign('show_lager', 1);
		}
		if (isset($_POST['show_price_variants']) && $_POST['show_price_variants']) {
			$this->layout_object->assign('show_price_variants', 1);
		}

		// Lade alle Lieferanten
		// $vendors = $this->vendor_object->get_all();
		$vendors = $this->vendor_object->get_dropdown_data();
		$this->layout_object->assign('vendors', $vendors);

		// decide what CRUD method to call and call it in ListAndEdit
		if (isset($_POST['mod']) && $_POST['mod'] == 'rename_item_document') {
			self::rename_item_document();
		} else if (isset($_POST['mod']) && $_POST['mod'] == 'delete_item_document') {
			self::delete_item_document();
		} else if (isset($_POST['mod']) && $_POST['mod'] == 'add_item_type') {
			self::add_item_type();
		} else if ($is_submitted && !$has_id) {
			// create
			self::save_item_types();

			// abort if Item Number already exists and reroute to existing item form
			$newId = $this->item_object->get_by_number($_POST['form_field']['number']);
			if ($newId != false) {
				header('location: http://'.$_SERVER["SERVER_NAME"].'/index.php?admin_modul=admin_item_editor&action=edit&id='.$newId);
				return;
			} else {
				$form_data = $this->item_object->data_filter($_POST['form_field']);
				$saved = $this->item_object->create($form_data, $_POST['form_field_prices']);
			}

			if ($saved) {
				self::save_item_types();
				// reroute to form with id in saved
				header('location: http://'.$_SERVER["SERVER_NAME"].'/index.php?admin_modul=admin_item_editor&action=edit&id='.$saved);
			} else {
				// reroute to empty form
				header('location: http://'.$_SERVER["SERVER_NAME"].'/index.php?admin_modul=admin_item_editor&action=add_item');
			}

		} // copy
		else if ($has_id && isset($_GET['mod']) && $_GET['mod'] == 'copy') {
			$this->item_object->id = $_GET['id'];
			$this->item_object->copy();

			if ($this->item_object->id) {
				self::save_item_types();
				// reroute to form with id in saved
				header('location: http://'.$_SERVER["SERVER_NAME"].'/index.php?admin_modul=admin_item_editor&action=edit&id='.$this->item_object->id);
			} else {
				// reroute to empty form
				header('location: http://'.$_SERVER["SERVER_NAME"].'/index.php?admin_modul=admin_item_editor&action=add_item');
			}

		} // delete file
		else if ($has_id && isset($_POST['mod']) && $_POST['mod'] == 'delete_file') {
			$this->item_object->id = $_POST['id'];
			$this->item_object->delete_file($_POST['pic_id']);

		} // upload file
		else if ($has_id && isset($_POST['mod']) && $_POST['mod'] == 'add_file') {
			self::upload_file();
		return; // FIX: Stop execution after upload to prevent unnecessary processing

		} // upload file
		else if ($has_id && isset($_POST['mod']) && $_POST['mod'] == 'get_file_list') {
			$this->item_object->id = $_POST['id'];
			$file_list = $this->item_object->get_file_list(0);
			$this->layout_object->assign('file_list', $file_list);
			self::get_item_variants($_POST['id']);
			return $this->layout_object->fetch('admin_item_editor_filelist.tpl');

		} // sort images
		else if ($has_id && isset($_POST['mod']) && $_POST['mod'] == 'sort_image_list') {
			$this->item_object->id = $_POST['id'];
			$this->item_object->sort_image_list($_POST['pics']);
			return;

		} // read
		else if ($has_id && isset($_POST['mod']) && $_POST['mod'] == 'remove_default_image') {
			$this->item_object->id = $_POST['id'];
			$this->item_object->remove_default_image();
			return;

		} // remove default image
		else if ($has_id && !$is_submitted && (!isset($_GET['mod']) || $_GET['mod'] != 'delete')) {
			// template variable name
			$this->item_object->id = $_GET['id'];
			$data = $this->item_object->get_data(1, false);
			if ($data->variant_price_type == 1) {
					$this->layout_object->assign('default_variant_price_type', '1');
			} else {
				$this->layout_object->assign('default_variant_price_type', '0');
			}

			if (!empty($data->available_from) && $data->available_from != '0000-00-00') {
				$tmp = explode('-', $data->available_from);
				$data->available_from = (count($tmp) === 3)
					? $tmp[2].'.'.$tmp[1].'.'.$tmp[0]
					: '';
			} else {
				$data->available_from = '';
			}

			if (!empty($data->available_till) && $data->available_till != '0000-00-00') {
				$tmp = explode('-', $data->available_till);
				$data->available_till = (count($tmp) === 3)
					? $tmp[2].'.'.$tmp[1].'.'.$tmp[0]
					: '';
			} else {
				$data->available_till = '';
			}

			// Ensure last_change_user is always an object
			if (!isset($data->last_change_user) || $data->last_change_user === null) {
				$data->last_change_user = new stdClass();
				$data->last_change_user->firstname = '';
				$data->last_change_user->surname = '';
			}
			
			// Clean up files array - remove any false/null entries
			if (isset($data->files) && is_array($data->files)) {
				$data->files = array_filter($data->files, function($file) {
					return $file !== false && $file !== null && is_object($file);
				});
				// Re-index array to ensure proper iteration
				$data->files = array_values($data->files);
			} else {
				$data->files = array();
			}
			
			$this->layout_object->assign('item_data', $data);
			$this->layout_object->assign('item_structure_assignment', $this->item_object->getStructureAssignment());
			
			// Load file list for item
			$file_list = $this->item_object->get_file_list(0);
			if (!$file_list || !is_array($file_list)) {
				$file_list = array(); // Fallback to empty array if false or not array
			} else {
				// Filter out any false/null entries from the array
				$file_list = array_filter($file_list, function($file) {
					return $file !== false && $file !== null && is_object($file);
				});
			}
			$this->layout_object->assign('file_list', $file_list);

		} else if ($has_id && $is_submitted && (!isset($_GET['mod']) || $_GET['mod'] != 'delete')) { // update
			self::save_item_types();
			self::upload_file();
			$this->item_object->id = $_POST['id'];
			$form_data = $this->item_object ->data_filter($_POST['form_field']);
			// Only set structure_id to 0 for NEW items, not for existing ones
			if (!isset($form_data['structure_id']) && !$_POST['id']) {
				$form_data['structure_id'] = 0;
			}
			// DEBUG: Log before price update (silent logging only)
// DISABLED: 			error_log("DEBUG PRICE UPDATE: Starting update for item ID: " . $this->item_object->id);
// DISABLED: 			error_log("DEBUG PRICE UPDATE: Form data: " . print_r($form_data, true));
// DISABLED: 			error_log("DEBUG PRICE UPDATE: Price data: " . print_r($_POST['form_field_prices'], true));
			
			try {
				$this->item_object->update($form_data, $_POST['form_field_prices']);
// DISABLED: 				error_log("DEBUG PRICE UPDATE: Update completed successfully");
				// Preserve the active tab if we came from documents tab
				$redirect_url = $_SERVER['HTTP_REFERER'];
				if (strpos($redirect_url, '#documents') === false && isset($_POST['active_tab']) && $_POST['active_tab'] == 'documents') {
					$redirect_url .= '#documents';
				}
				header('location: '.$redirect_url);
			} catch (Exception $e) {
// DISABLED: 				error_log("DEBUG PRICE UPDATE: FATAL ERROR - " . $e->getMessage());
// DISABLED: 				error_log("DEBUG PRICE UPDATE: Stack trace: " . $e->getTraceAsString());
				// Silent redirect to prevent user seeing error
				header('location: '.$_SERVER['HTTP_REFERER']);
			}

		} else if ($has_id && isset($_GET['mod']) && $_GET['mod'] == 'delete') { // delete
			$this->item_object ->id = $_GET['id'];
			$this->item_object ->delete();

		} else {
			// new item
			$config_object = new Config($this->base_object);

			if ($config_object->is_set('variant_price_type')) {
				if ($config_object->get_value('variant_price_type') == 'additional_charge') {
					$this->layout_object->assign('default_variant_price_type', '1');
				}
			} else {
				$this->layout_object->assign('default_variant_price_type', '0');
			}

			$this->layout_object->assign('default_shippable', '1');
			$this->layout_object->assign('default_price_type', '1');
			$this->layout_object->assign('default_state', '1');

			// Standardmäßig "Preis zeigen" Sektion bei Neuanlage aktiviert
			$this->layout_object->assign('show_price_and_marketing', 1);

		}

		// set document path
		$document_path = str_replace('//', '/', './web/'.SHOP_SYSTEM.'/documents/article/');
		$this->layout_object->assign('document_path', $document_path);

		// get manufacturer
		$manufacturer_object = new Manufacturer($this->base_object);
		$manufacturers = $manufacturer_object->get_all();
		$this->layout_object->assign('manufacturers', $manufacturers);

		// get tax
		$tax_object = new Tax($this->base_object);
		$taxes = $tax_object->get_all();
		$this->layout_object->assign('taxes', $taxes);

		// get structure
		$structure_object = new Structure($this->base_object);
		$structure_tree = $structure_object->get_all_tree_full_path(null, '/');
		//echo '<pre style="text-align:left;">';print_r($structure_tree);
		$this->layout_object->assign('structure_tree', $structure_tree);

		// get schema
		$schemas = $this->item_object ->get_all_item_schemas();
		$this->layout_object->assign('schemas', $schemas);

		// get customer groups
		$customerGroups_object = new Customer_group($this->base_object);
		$customerGroups = $customerGroups_object->get_all_price_groups();
		$groups = array();
		foreach ($customerGroups as $group) {
			if ($id) {
				$group->prices = $this->item_object->getPricesForCustomerGroup($group->id);
			} else {
				// For new items, create empty prices object
				$group->prices = new stdClass();
				$group->prices->graduated_prices = false;
				// Manually add all price properties with numeric defaults (for calculations)
				$group->prices->price_1 = 0; $group->prices->quantity_1 = 1; $group->prices->bargain_price_1 = 0;
				$group->prices->price_2 = 0; $group->prices->quantity_2 = 0; $group->prices->bargain_price_2 = 0;
				$group->prices->price_3 = 0; $group->prices->quantity_3 = 0; $group->prices->bargain_price_3 = 0;
				$group->prices->price_4 = 0; $group->prices->quantity_4 = 0; $group->prices->bargain_price_4 = 0;
				$group->prices->price_5 = 0; $group->prices->quantity_5 = 0; $group->prices->bargain_price_5 = 0;
			}
			$groups[] = $group;
		}
		$this->layout_object->assign('customerGroups', $groups);

		// get accessories
		if ($id) {
			$item_items = $this->item_object ->get_all_item_items(1, $id, 1);
			$this->layout_object->assign('item_items', $item_items);

			$item_items2 = $this->item_object ->get_all_item_items(2, $id, 1);
			$this->layout_object->assign('item_items2', $item_items2);

			$item_items3 = $this->item_object ->get_all_item_items(3, $id, 1);
			$this->layout_object->assign('item_items3', $item_items3);
		}

		// get accessories childs
		if ($id) {
			$item_items = $this->item_object ->get_all_item_items(1, $id, 0);
			$this->layout_object->assign('item_item_child', $item_items);

			$item_items2 = $this->item_object ->get_all_item_items(2, $id, 0);
			$this->layout_object->assign('item_item_child2', $item_items2);

			$item_items3 = $this->item_object ->get_all_item_items(3, $id, 0);
			$this->layout_object->assign('item_item_child3', $item_items3);
		}

		// get shipping areas
		$shipping_area_object = new Shipping_area($this->base_object);
		$shipping_areas = $shipping_area_object->get_all();
		$this->layout_object->assign('shipping_areas', $shipping_areas);

		// get google item categories
		$google_item_categories1 = $this->item_object ->get_all_google_item_categories();
		$this->layout_object->assign('google_item_categories1', $google_item_categories1);

		// get item type definitions
		$item_type_definitions = self::get_item_type_definitions();
		$this->layout_object->assign('item_type_definitions', $item_type_definitions);

		// get item types
		if ($this->item_object) {
			$item_types = $this->item_object->get_item_types();
		} else {
			$item_types = array(); // For new items
		}
		$this->layout_object->assign('item_types', $item_types);

		// item opinion
		if ($id) {
			$opinion = $this->item_object->get_opinion_list($id);
			$this->layout_object->assign('item_opinion', $opinion);
		}

		// item inventory
		if ($id) {
			$inventory_object = new ItemInventory($this->base_object);
			$inventory = $inventory_object->get_all_item_inventory($id);
			$price_sum_output = 0;
			$price_sum_input = 0;
			foreach ($inventory as $item_inventory) {
				if ($item_inventory->inventory_object_type_id == 2) {
					$price_sum_input += $item_inventory->price_sum;
				} else {
					$price_sum_output += $item_inventory->price_sum;
				}
			}
			$this->layout_object->assign('item_inventory_stats', array('price_sum_input' => $price_sum_input, 'price_sum_output' => $price_sum_output));
			$this->layout_object->assign('item_inventory', $inventory);
		}

		// get variant configuration
		include './web/'.SHOP_SYSTEM.'/config/item_variant_schema.inc.php';
		$this->layout_object->assign('item_variant_config', $item_fields);

		// Ensure item_data is always set (default values for new items)  
		if (!$this->layout_object->getTemplateVars('item_data')) {
			// Create comprehensive default item object with all needed properties
			$default_item_data = new stdClass();
			$default_item_data->id = '';
			$default_item_data->parent_id = 0;
			$default_item_data->structure_id = 0;
			$default_item_data->schema_id = 0;
			$default_item_data->manufacturer_id = 0;
			$default_item_data->name = '';
			$default_item_data->name_en = '';
			$default_item_data->number = '';
			$default_item_data->tax_id = 0;
			$default_item_data->short_description = '';
			$default_item_data->short_description_en = '';
			$default_item_data->detail_description = '';
			$default_item_data->detail_description_en = '';
			$default_item_data->manufacturer_item_number = '';
			$default_item_data->default_image_file_name = '';
			$default_item_data->seo_title = '';
			$default_item_data->seo_description = '';
			$default_item_data->seo_keywords = '';
			$default_item_data->short_uri = '';
			$default_item_data->ean_code = '';
			$default_item_data->price_type = '';
			$default_item_data->shipping_cost_type = '';
			$default_item_data->shipping_item_type = '';
			$default_item_data->shipping_weight = '';
			$default_item_data->available_from = '';
			$default_item_data->available_till = '';
			$default_item_data->base_price = '';
			$default_item_data->buy_quantity = '';
			$default_item_data->google_product_category = '';
			$default_item_data->inventory_min = '';
			$default_item_data->inventory_number = '';
			$default_item_data->inventory_order_quantity = '';
			$default_item_data->inventory_rack_number = '';
			$default_item_data->min_quantity = '';
			$default_item_data->price_je_vpe = '';
			$default_prices = new stdClass();
			$default_prices->value = 0;
			$default_item_data->prices = $default_prices;
			$default_item_data->uvp = '';
			$default_item_data->uvp_netto = '';
			$default_item_data->vpe_amount = '';
			$default_item_data->vpe_unit = '';
			$default_item_data->youtube_video = '';
			$default_item_data->vendor_id = 0;
			$default_item_data->vendor_item_number = '';
			$default_item_data->price_1 = '';
			$default_item_data->has_user_data = 0;
			$default_item_data->shippable = 1;
			$default_item_data->shippable_inventory = 1;
			$default_item_data->bargain_price_type = 0;
			// Create empty last_change_user object for new items
			$default_last_change_user = new stdClass();
			$default_last_change_user->firstname = '';
			$default_last_change_user->surname = '';
			$default_item_data->last_change_user = $default_last_change_user;
			$default_item_data->last_change_date = '';
			$default_item_data->schema_data_attributes = array();
			$default_item_data->variant_structure = array();
			$this->layout_object->assign('item_data', $default_item_data);
		}
		
		// Ensure message variables are always set as arrays
		if (!$this->layout_object->getTemplateVars('warning_message')) {
			$this->layout_object->assign('warning_message', array());
		}
		if (!$this->layout_object->getTemplateVars('error_message')) {
			$this->layout_object->assign('error_message', array());
		}
		if (!$this->layout_object->getTemplateVars('info_message')) {
			$this->layout_object->assign('info_message', array());
		}
		
		// Ensure item_structure_assignment is always set
		if (!$this->layout_object->getTemplateVars('item_structure_assignment')) {
			$this->layout_object->assign('item_structure_assignment', array());
		}
		
		// Ensure itemsTax is always set as numeric value for calculations
		if (!$this->layout_object->getTemplateVars('itemsTax')) {
			$this->layout_object->assign('itemsTax', 0);
		}
		
		// Ensure item_types is always set as array
		if (!$this->layout_object->getTemplateVars('item_types')) {
			$this->layout_object->assign('item_types', array());
		}
		
		// Ensure all show_* variables are set as integers for template conditions
		$show_vars = ['show_price_and_marketing', 'show_attributes', 'show_versand', 'show_seo', 'show_lager', 'show_price_variants'];
		foreach ($show_vars as $var_name) {
			if (!$this->layout_object->getTemplateVars($var_name)) {
				$this->layout_object->assign($var_name, 0);
			}
		}
		
		// Ensure base_dir and info object are set for all icon paths
		if (!$this->layout_object->getTemplateVars('base_dir')) {
			$this->layout_object->assign('base_dir', '.');
		}
		if (!$this->layout_object->getTemplateVars('info')) {
			$info = new stdClass();
			$info->base_url = '.';
			$this->layout_object->assign('info', $info);
		}

		return $this->layout_object->fetch('admin_item_editor.tpl');
	}

	private function save_item_types() {
		$this->db->autocommit(false);

		self::update_item_types();
		self::insert_item_types();
		self::delete_item_types();

		$result = $this->db->commit();
		$this->db->autocommit(true);
	} // end save_item_types

	private function update_item_types() {
		if (!isset($_POST['item_type'])) {
			return; // No item_type data to update
		}
		$data = $_POST['item_type'];
		$len = (isset($data['item_type_id']) && is_array($data['item_type_id'])) ? count($data['item_type_id']) : 0;
		
		for ($i = 0; $i < $len; $i++) {
			if ($data['item_type_id'][$i] != '') {
				if (!$data['item_type_available_from'][$i]) {
					$data['item_type_available_from'][$i] = '0000-00-00';
				}
				if (!$data['item_type_available_until'][$i]) {
					$data['item_type_available_until'][$i] = '0000-00-00';
				}

				$sql  = 'UPDATE
							item_types
						SET
							item_type_definition_id='.$this->db->real_escape_string($data['item_type_definition_id'][$i]);
				$sql .= " , item_type_text='".$this->db->real_escape_string($data['item_type_text'][$i])."'";
				$sql .= " , item_type_available_from='".$this->db->real_escape_string($data['item_type_available_from'][$i])."'";
				$sql .= " , item_type_available_until='".$this->db->real_escape_string($data['item_type_available_until'][$i])."'";
				$sql .= ' WHERE item_type_id='.$this->db->real_escape_string($data['item_type_id'][$i]);
				$sql .= ' AND item_id='.$this->id;
				$this->db->query($sql);
			}
		}
	} // end update_item_types

	private function insert_item_types() {
		if (!isset($_POST['item_type'])) {
			return; // No item_type data to insert
		}
		$data = $_POST['item_type'];
		$len = (isset($data['item_type_id']) && is_array($data['item_type_id'])) ? count($data['item_type_id']) : 0;

		$sql = 'INSERT INTO item_types (item_id, item_type_definition_id, item_type_text, item_type_available_from, item_type_available_until) VALUES ';
		$first = true;
		for ($i = 0; $i < $len; $i++) {
			if ($data['item_type_id'][$i] == '') {
				if ($first) {
					$first = false;
				} else {
					$sql .= ', ';
				}

				// Fix: Check if array keys exist before accessing them
				if (!isset($data['item_type_available_from'][$i]) || !$data['item_type_available_from'][$i]) {
					$data['item_type_available_from'][$i] = '0000-00-00';
				}
				if (!isset($data['item_type_available_until'][$i]) || !$data['item_type_available_until'][$i]) {
					$data['item_type_available_until'][$i] = '0000-00-00';
				}

				$sql .= " ('".
					$this->db->real_escape_string($this->id)."', '".
					$this->db->real_escape_string($data['item_type_definition_id'][$i])."', '".
					$this->db->real_escape_string($data['item_type_text'][$i] ?? '')."', '".
					$this->db->real_escape_string($data['item_type_available_from'][$i])."', '".
					$this->db->real_escape_string($data['item_type_available_until'][$i])."') ";
			}
		}

		if (!$first) {
			$this->db->query($sql);
		}

		return '';
	} // end insert_item_types

	private function delete_item_types() {
		if (isset($_POST['deletable_item_types'])) {
			$data = implode(', ',  $_POST['deletable_item_types']);

			$sql = 'DELETE FROM
						item_types
					WHERE
						item_type_id IN ('.$data.')
					AND
						item_id='.$this->id.';';

			$this->db->query($sql);
		}
	} // end delete_item_types

	private function get_item_type_definitions() {
		$sql = 'SELECT
					*
				FROM
					item_type_definitions';

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

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

			return $data;
		}

		return false;
	} // end get_item_type_definitions

	private function add_item_type() {
		$item_type_definitions = self::get_item_type_definitions();
		$this->layout_object->assign('item_type_definitions', $item_type_definitions);
		
		// Create empty item_type object for new item type
		$item_type = new stdClass();
		$item_type->item_type_ordering = '';
		$item_type->item_type_id = '';
		$item_type->item_type_definition_id = '';
		$item_type->item_type_text = '';
		$item_type->item_type_definition_type = 0;
		$item_type->item_type_available_from = '';
		$item_type->item_type_available_until = '';
		$this->layout_object->assign('item_type', $item_type);
		
		// Ensure all show_* variables are set for snippet template
		$show_vars = ['show_price_and_marketing', 'show_attributes', 'show_versand', 'show_seo', 'show_lager', 'show_price_variants'];
		foreach ($show_vars as $var_name) {
			if (!$this->layout_object->getTemplateVars($var_name)) {
				$this->layout_object->assign($var_name, 0);
			}
		}
		
		// Ensure base_dir and info object are set for icon paths in snippet template
		if (!$this->layout_object->getTemplateVars('base_dir')) {
			$this->layout_object->assign('base_dir', '.');
		}
		if (!$this->layout_object->getTemplateVars('info')) {
			$info = new stdClass();
			$info->base_url = '.';
			$this->layout_object->assign('info', $info);
		}

		echo $this->layout_object->fetch('snipet_item_type.tpl');
		exit();
	} // end add_item_type

	protected function rename_item_document() {
		if (isset($_POST['document_id']) && isset($_POST['new_name'])) {
			$document_id = $_POST['document_id'];
			$new_name = $_POST['new_name'];

			if ($new_name != '') {
				if (!stristr('.pdf', $new_name)) {
					$new_name.'.pdf';
				}

				$sql = "UPDATE
							item_files
						SET
							alt='".$this->db->real_escape_string($new_name)."'
						WHERE
							id=".$this->db->real_escape_string($document_id);

				$this->db->query($sql);
			}
		}

		echo " ";
		exit();
	}

	protected function delete_item_document() {
		if (isset($_POST['document_id']) && isset($_POST['item_id'])) {
			$item_id = $_POST['item_id'];
			$document_id = $_POST['document_id'];

			$result = $this->item_object->delete_file($document_id, $item_id);

			if ($result) {
				$return_array = array('status' => 'success');
			} else {
				$return_array = array('status' => 'error');
			}
		} else {
			$return_array = array('status' => 'error');
		}

		echo json_encode($return_array);

		exit();
	}

	protected function upload_file() {
		// DEBUG: Log upload attempt mit Timestamps
		$debug_log = '/var/www/vhosts/intelectra.de/httpdocs/logs/upload_debug.log';
		$start = microtime(true);
		file_put_contents($debug_log, date('Y-m-d H:i:s') . " === UPLOAD_FILE START ===\n", FILE_APPEND);
		file_put_contents($debug_log, date('Y-m-d H:i:s') . " POST submit: " . (isset($_POST['submit']) ? $_POST['submit'] : 'NOT SET') . "\n", FILE_APPEND);
		file_put_contents($debug_log, date('Y-m-d H:i:s') . " FILES name: " . (isset($_FILES['Filedata']['name']) ? $_FILES['Filedata']['name'] : 'NOT SET') . "\n", FILE_APPEND);
		file_put_contents($debug_log, date('Y-m-d H:i:s') . " FILES size: " . (isset($_FILES['Filedata']['size']) ? $_FILES['Filedata']['size'] : 'NOT SET') . "\n", FILE_APPEND);
		file_put_contents($debug_log, date('Y-m-d H:i:s') . " FILES tmp_name: " . (isset($_FILES['Filedata']['tmp_name']) ? $_FILES['Filedata']['tmp_name'] : 'NOT SET') . "\n", FILE_APPEND);
		file_put_contents($debug_log, date('Y-m-d H:i:s') . " Item ID: " . (isset($_POST['id']) ? $_POST['id'] : 'NOT SET') . "\n", FILE_APPEND);

		$this->item_object->id = $_POST['id'];

		if ($_FILES['Filedata']['tmp_name'] != "") { // check if a file has been set
			file_put_contents($debug_log, date('Y-m-d H:i:s') . " [1] File found, starting processing...\n", FILE_APPEND);

			if (substr($_FILES['Filedata']['name'], -3) == 'pdf') { // check if file is pdf
				file_put_contents($debug_log, date('Y-m-d H:i:s') . " [2] PDF detected, calling add_uploaded_pdf\n", FILE_APPEND);
				$return_object = $this->item_object ->add_uploaded_pdf($_FILES);
			} else {
				file_put_contents($debug_log, date('Y-m-d H:i:s') . " [2] Image detected, calling add_uploaded_file\n", FILE_APPEND);
				$return_object = $this->item_object ->add_uploaded_file($_FILES, $_POST['watermark_activ']);
			}

			file_put_contents($debug_log, date('Y-m-d H:i:s') . " [3] Upload function returned: " . ($return_object ? 'SUCCESS' : 'FAILED') . "\n", FILE_APPEND);

			if ($return_object) {
				$return_data = array('status' => 'success', 'data' => $return_object);
			} else {
				$return_data = array('status' => 'error');
			}

			// 🔥 FIX: Bei Datei-Upload sofort Response senden und beenden!
			file_put_contents($debug_log, date('Y-m-d H:i:s') . " [4] Checking exit - submit=" . $_POST['submit'] . "\n", FILE_APPEND);
			if (isset($_POST['submit']) && $_POST['submit'] == 'Datei hochladen') {
				$elapsed = round((microtime(true) - $start) * 1000, 2);
				file_put_contents($debug_log, date('Y-m-d H:i:s') . " [5] EXIT - redirecting! (took {$elapsed}ms)\n", FILE_APPEND);
				header('Location: ./index.php?admin_modul=admin_item_editor&id=' . $this->item_object->id);
				exit();
			}
			file_put_contents($debug_log, date('Y-m-d H:i:s') . " [5] NO EXIT - continuing to update()!\n", FILE_APPEND);
		}

		return;
	}

	private function get_item_variants($item_id) {
		$sql = "SELECT
					items.*,
					item_schema.selectable_attribute_1,
					item_schema.selectable_attribute_2
				FROM
					items
				LEFT JOIN
					item_schema
				ON
					items.schema_id = item_schema.id
				WHERE
					items.id=".$this->db->real_escape_string($item_id);

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

		$attributes_array_1 = false;
		$attributes_array_2 = false;
		$return_array = false;

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

			if (isset($data->selectable_attribute_1) && $data->selectable_attribute_1 != '0') {
				$attributes_array_1 = explode(';', $data->{'attribute_'.$data->selectable_attribute_1});
				$this->layout_object->assign('item_variants_1', $attributes_array_1);
			}

			if (isset($data->selectable_attribute_2) && $data->selectable_attribute_2 != '0') {
				$attributes_array_2 = explode(';', $data->{'attribute_'.$data->selectable_attribute_2});
				$this->layout_object->assign('item_variants_2', $attributes_array_2);
			}
		}
	} // end get_item_variants
}

?>
