<?php
class ControllerCommonMenu extends Controller {
	public function index() {
		$this->load->language('common/menu');

		// Menu
		$this->load->model('catalog/category');

		$this->load->model('catalog/product');
		
		// Load custom fields model for categories
		$this->load->model('catalog/custom_fields');

		$data['logged'] = $this->customer->isLogged();

		$data['categories'] = array();

		$categories = $this->model_catalog_category->getCategories(0);

		foreach ($categories as $category) {
			if ($category['top']) {
				// Level 2
				$children_data = array();

				$children = $this->model_catalog_category->getCategories($category['category_id']);

				foreach ($children as $child) {
					$filter_data = array(
						'filter_category_id'  => $child['category_id'],
						'filter_sub_category' => true
					);

					// Level 3 - Get grandchildren
					$grandchildren_data = array();
					$grandchildren = $this->model_catalog_category->getCategories($child['category_id']);
					
					foreach ($grandchildren as $grandchild) {
						$grandchildren_data[] = array(
							'name'  => html_entity_decode($grandchild['name'], ENT_QUOTES, 'UTF-8'),
							'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $grandchild['category_id'])
						);
					}

					$children_data[] = array(
						'name'  => html_entity_decode($child['name'], ENT_QUOTES, 'UTF-8'),
						'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
						'children' => $grandchildren_data
					); 
				}

				// Get manufacturers for this category
				$manufacturer_list = array();
				$cache_key = 'category.manufacturer.'. (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' .  $category['category_id'];
				
				$cached_manufacturers = $this->cache->get($cache_key);
				
				if (!$cached_manufacturers) {
					// Get products from this category to extract manufacturers
					$filter_data = array(
						'filter_category_id'  => $category['category_id'],
						'filter_sub_category' => true,
						'start' => 0,
						'limit' => 1000 // Get more products to find manufacturers
					);
					
					$products = $this->model_catalog_product->getProducts($filter_data);
					
					if ($products) {
						$manufacturers = array();
						
						foreach($products as $product) {
							// Only add if manufacturer exists and has valid data (exclude empty strings, null, and whitespace-only)
							if (!empty($product['manufacturer_id']) && 
								!empty($product['manufacturer']) && 
								trim($product['manufacturer']) !== '' && 
								$product['manufacturer'] !== null && 
								$product['manufacturer'] !== '') {
								
								$manufacturer_name = trim($product['manufacturer']);
								
								$manufacturers[] = array(
									'id' => $product['manufacturer_id'],
									'name' => $manufacturer_name,
									'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '&mfp=manufacturers[' . $product['manufacturer_id'] . ']')
								);
							}
						}
						
						// Remove duplicates and sort
						if (!empty($manufacturers)) {
							$unique_manufacturers = array();
							$seen_ids = array();
							
							foreach($manufacturers as $manufacturer) {
								// Additional check to ensure no empty names
								if (!in_array($manufacturer['id'], $seen_ids) && 
									!empty($manufacturer['name']) && 
									trim($manufacturer['name']) !== '') {
									$seen_ids[] = $manufacturer['id'];
									$unique_manufacturers[] = $manufacturer;
								}
							}
							
							// Sort by name
							if (!empty($unique_manufacturers)) {
								usort($unique_manufacturers, function($a, $b) {
									return strcmp($a['name'], $b['name']);
								});
							}
							
							$manufacturer_list = $unique_manufacturers;
						}
					}
					
					// Cache the result (even if empty)
					$this->cache->set($cache_key, $manufacturer_list);
				} else {
					$manufacturer_list = $cached_manufacturers;
				}				

				// Get category image
				$category_image = '';
				if ($category['image']) {
					$this->load->model('tool/image');
					$category_image = $this->model_tool_image->resize($category['image'], 440, 495);
				}
				
				// Load custom fields for category
				$custom_fields = $this->model_catalog_custom_fields->getCustomFieldsByRoute('catalog/category');
				$custom_field_values = $this->model_catalog_custom_fields->getCategoryCustomFieldValues($category['category_id'], 'catalog/category');
				
			// Process custom field values and add them to category data
			$category_custom_fields = array();
			$category_images = array(); // Array to store the 3 images
			$category_links = array(); // Array to store links for images (field_id => link)
			
			// Load image model for resizing
			$this->load->model('tool/image');
			
			foreach ($custom_fields as $group) {
				foreach ($group['fields'] as $field) {
					$field_id = $field['input_id'];
					$field_name = $field['name'];
					$field_type = $field['type'];
					
					// Find the value for this field
					$field_value = '';
					if (isset($custom_field_values[$group['group_id']])) {
						foreach ($custom_field_values[$group['group_id']]['fields'] as $value_field) {
							if ($value_field['input_id'] == $field_id) {
								// For Upload type fields, get value from any language (non-multi-lang)
								if ($field_type == 'Upload') {
									// Upload fields are non-multi-lang, so get the first available value
									$value_key = strtolower($field_type);
									$field_value = $value_field['values'][$value_key];
								} else {
									// Get value in current language or fallback to language 1 or 0
									$value_key = strtolower($field_type);
									if ($value_field['language_id'] == $this->config->get('config_language_id')) {
										$field_value = $value_field['values'][$value_key];
									} elseif (!$field_value && $value_field['language_id'] == 1) {
										$field_value = $value_field['values'][$value_key];
									} elseif (!$field_value && $value_field['language_id'] == 0) {
										$field_value = $value_field['values'][$value_key];
									}
								}
								break;
							}
						}
					}
					
					// Process Upload type fields (images)
					if ($field_type == 'Upload' && !empty($field_value) && is_file(DIR_IMAGE . $field_value)) {
						// Resize image and add to category_images array
						$resized_image = $this->model_tool_image->resize($field_value, 224, 280);
						$category_images[$field_id] = array(
							'image' => $resized_image,
							'original' => $field_value,
							'link' => '' // Will be filled later if link exists
						);
					}
					
					// Process Text type fields that are links (field IDs 4, 5, 6 for menu banner links)
					if ($field_type == 'Text' && !empty($field_value) && in_array($field_id, array(4, 5, 6))) {
						// Store link with its field_id
						$category_links[$field_id] = $field_value;
					}						// Decode HTML entities for HTML type fields
						if ($field_type == 'HTML' && !empty($field_value)) {
							$field_value = html_entity_decode($field_value, ENT_QUOTES, 'UTF-8');
						}
						
						// Add to category custom fields array with field ID as index
						$category_custom_fields['custom_field_' . $field_id] = $field_value;
						
						// Also add field metadata for reference
						// Handle field name (can be array with language IDs or string)
						if (is_array($field_name)) {
							$field_name_display = isset($field_name[$this->config->get('config_language_id')]) ? $field_name[$this->config->get('config_language_id')] : (isset($field_name[1]) ? $field_name[1] : (isset($field_name[0]) ? $field_name[0] : ''));
						} else {
							$field_name_display = $field_name;
						}
				$category_custom_fields['custom_field_' . $field_id . '_name'] = $field_name_display;
				$category_custom_fields['custom_field_' . $field_id . '_type'] = $field_type;
				$category_custom_fields['custom_field_' . $field_id . '_group'] = $group['group_name'];
			}
		}
		
		// Associate links with images
		// Image field_id 1 -> Link field_id 4
		// Image field_id 2 -> Link field_id 5
		// Image field_id 3 -> Link field_id 6
		$link_mapping = array(
			1 => 4,
			2 => 5,
			3 => 6
		);
		
		foreach ($link_mapping as $image_field_id => $link_field_id) {
			if (isset($category_images[$image_field_id]) && isset($category_links[$link_field_id])) {
				$category_images[$image_field_id]['link'] = $category_links[$link_field_id];
			}
		}
		
		// Convert to indexed array and limit to 3 images maximum
		$category_images = array_values($category_images);
		$category_images = array_slice($category_images, 0, 3);				$data['categories'][] = array(
					'name'     => html_entity_decode($category['name'], ENT_QUOTES, 'UTF-8'),
					'children' => $children_data,
					'column'   => $category['column'] ? $category['column'] : 1,
					'href'     => $this->url->link('product/category', 'path=' . $category['category_id']),
					'manufacturer_list' => $manufacturer_list,
					'image'    => $category_image,
					'custom_fields' => $category_custom_fields,
					'custom_images' => $category_images, // Array of up to 3 images from custom fields
				);
			}
		}

		$data['categories'][] = array(
			'name'     =>  $this->language->get('text_offers'),
			'children' => '',
			'column'   => 1,
			'href'     => $this->url->link('product/special'),
			'manufacturer_list' => '',
			'image'    => '',
			'custom_fields' => '',
			'custom_images' => '', // Array of up to 3 images from custom fields
		); 

		// Load theme settings for menu type and header info pages
		$this->load->model('setting/setting');
		
		// Get current theme directory dynamically
		$theme_directory = $this->config->get('config_theme');
		if ($theme_directory == 'default') {
			$theme_directory = $this->config->get('theme_default_directory');
		}
		$theme_setting_key = 'theme_' . $theme_directory;
		
		$theme_settings = $this->model_setting_setting->getSetting($theme_setting_key);
		$data['theme_menu_type'] = isset($theme_settings[$theme_setting_key . '_menu_type']) ? $theme_settings[$theme_setting_key . '_menu_type'] : 'drawer';

		// Store logo
		if (is_file(DIR_IMAGE . $this->config->get('config_logo'))) {
			$data['logo'] = $this->config->get('config_store_url') . 'image/' . $this->config->get('config_logo');
		} else {
			$data['logo'] = '';
		}

		// Header information pages links
		$data['header_info_pages'] = array();

		if (!empty($theme_settings[$theme_setting_key . '_header_info_pages']) && is_array($theme_settings[$theme_setting_key . '_header_info_pages'])) {
			$this->load->model('catalog/information');

			foreach ($theme_settings[$theme_setting_key . '_header_info_pages'] as $information_id) {
				$information_info = $this->model_catalog_information->getInformation($information_id);

				if ($information_info) {
					$data['header_info_pages'][] = array(
						'title' => $information_info['title'],
						'href'  => $this->url->link('information/information', 'information_id=' . (int)$information_id)
					);
				}
			}
		}

		return $this->load->view('common/menu', $data);
	}
}
