<?php
set_time_limit(10000); 
class ControllerToolXmlparser extends Controller {
	public function index() {
		$this->log->write('Старт');
		  $last_date = $this->config->get('xmlparser_date');
		//$last_date = '';
		$file = DIR_UPLOAD . 'ostatki.xml';
		$feed_date = date("d.m.Y H:i:s", filemtime($file));
		
		if ($feed_date != $last_date) {
			$this->log->write('У фида время ок');
			$products_proc = 0;
			$products_skipped = 0;
			$products_nf = 0;
			$query = $this->db->query("TRUNCATE " . DB_PREFIX . "product_to_warehouse");
			$query = $this->db->query("UPDATE " . DB_PREFIX . "product SET quantity = '0'");
			$xml_warehouses = array();
			
			$xml = simplexml_load_file($file);
			$this->log->write('НАчинаем перебор товаров');
			if ($xml->Товар) {
				foreach ($xml->Товар as $product) {

					$model     = trim((string)$product['Артикул']);
					$quantity  = (int)$product['ОбщийОстаток'];
					$id        = trim((string)$product['Код']);
					$price_raw = (float)str_replace(',', '.', $product['Цена']);
					$currency  = trim((string)$product['Валюта']);

					if ($currency == 'грн') {
						$currency = str_replace('грн', 'UAH', $currency);
					} else {
						$currency = mb_strtoupper($currency);
					}

					// $this->db->query("UPDATE " . DB_PREFIX . "product SET upc = '" . $this->db->escape($id) . "' WHERE model = '" . $this->db->escape($model) . "' AND (upc IS NULL OR upc = '')");

					$this->db->query("UPDATE " . DB_PREFIX . "product SET upc = '" . $this->db->escape($id) . "' WHERE model = '" . $this->db->escape($model) . "' AND (upc = model OR upc IS NULL OR upc = '')");
					
					$product_query = $this->db->query("SELECT product_id, unique_price FROM " . DB_PREFIX . "product WHERE upc = '" . $this->db->escape($id) . "'");

					if ($product_query->num_rows) {
						$product_id = $product_query->row['product_id'];
						$sql = "UPDATE " . DB_PREFIX . "product SET quantity = '" . (int)$quantity . "', model = '" . $this->db->escape($model) . "'";

						if (!$product_query->row['unique_price']) {
							$price = $this->getMultiplierPrice($price_raw, $currency);
							$sql .= ", price = '" . (float)$price . "'";
						}

						$sql .= " WHERE product_id = '" . (int)$product_id . "'";
						
						$query = $this->db->query($sql);
						
						if ($product->Остаток) {
							foreach ($product->Остаток as $warehouse) {
								$warehouse_id = (int)$warehouse['СкладКод'];
								$warehouse_name = trim((string)$warehouse['Склад']);
								$warehouse_quantity = (int)$warehouse['Кво'];
								if (!isset($xml_warehouses[$warehouse_id])) {
									$xml_warehouses[$warehouse_id] = $warehouse_name;
								}
								$query = $this->db->query("INSERT IGNORE INTO " . DB_PREFIX . "product_to_warehouse SET product_id = '" . (int)$product_id . "', warehouse_id = '" . (int)$warehouse_id . "', quantity = '" . (int)$warehouse_quantity . "'");
							}
						}
						$products_proc++;
					} else {
						$products_nf++;
					}
				}
				
				foreach ($xml_warehouses as $warehouse_id => $name) {
					$query = $this->db->query("INSERT IGNORE INTO " . DB_PREFIX . "warehouse SET warehouse_id = '" . (int)$warehouse_id . "', name = '" . $this->db->escape($name) . "'");
				}
				
				$this->log->write('Обработка фида завершена. Обработано товаров: ' . $products_proc . '. Не найдено товаров: ' . $products_nf . '. Время выполнения:' . (microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]));
				
				$config = $this->getSetting('xmlparser');
				
				$config['xmlparser_date'] = $feed_date;
				
				$this->editSetting('xmlparser', $config);
			}
		} else {
			$this->log->write('Обработка фида отменена. Фид был обработан ранее.');
		}
	}
	
	private function getMultiplierPrice($price_raw = 0, $currency = 'EUR') {
		if ($currency != 'EUR') {
			$price = $this->currency->convert($price_raw, $currency, 'EUR');
		} else {
			$price = $price_raw;
		}
		
		$multiplier = 1;
		
		if (!empty($this->config_price_multiplier)) {
			$set_multipliers = explode(';',$this->config_price_multiplier);
			foreach ($set_multipliers as $set_multiplier) {
				$miltiplier_data = explode(':',$set_multiplier);
				if ($price >= (int)$miltiplier_data[0]) {
					$multiplier = (float)$miltiplier_data[1];
					break;
				}
			}
		}
		
		if ($currency != 'UAH') {
			$result = $this->currency->convert($price_raw, $currency, 'UAH') * $multiplier;
		} else {
			$result = $price_raw * $multiplier;
		}
		
		return $result;
	}
	
	private function getSetting($code, $store_id = 0) {
		$setting_data = array();

		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'");

		foreach ($query->rows as $result) {
			if (!$result['serialized']) {
				$setting_data[$result['key']] = $result['value'];
			} else {
				$setting_data[$result['key']] = json_decode($result['value'], true);
			}
		}

		return $setting_data;
	}

	private function editSetting($code, $data, $store_id = 0) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'");

		foreach ($data as $key => $value) {
			if (substr($key, 0, strlen($code)) == $code) {
				if (!is_array($value)) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
				} else {
					$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'");
				}
			}
		}
	}
}