<?php

if (!defined('DIR_CORE')) {
	header('Location: static_pages/');
}

class ControllerResponsesExtensionPricecheckfeed extends AController {

	public function main() {

        //init controller data
        $this->extensions->hk_InitData($this,__FUNCTION__);

		if ($this->has_auth()) {
			die('This is for PriceCheck only');
		}

		$debug = !empty($this->request->get['debug']) ? true : false;
		$skip_stock_check = !empty($this->request->get['skip_stock_check']) ? 1 : 0;

		$_page = (int)$this->request->get['page'];
		$page = !empty($_page) ? $_page : 1;
		$_num_per_page = (int)$this->request->get['num_per_page'];
		$num_per_page = !empty($_num_per_page) ? $_num_per_page : 1000;

		$limit = $num_per_page;
		$offset = ($page - 1)*$num_per_page;

		if ($debug) {
			error_reporting(E_ALL);
			ini_set('display_errors', 1);
		}

		$this->loadModel('catalog/category');
		$this->loadModel('catalog/product');
		$this->loadModel('catalog/manufacturer');
		$this->loadModel('localisation/currency');
		$this->loadModel('tool/image');
		$this->loadModel('tool/seo_url');

		$include_tax = $this->config->get('entry_include_tax');
		$products = $this->model_catalog_product->getProducts(array('start'=>$offset,'limit'=>$limit));

		if ($debug) {
			var_dump($products);
		}

		$output = '<Offers>';
		foreach ($products as $product) {

			$stock_info = (int)$product['quantity'];
			if ($stock_info<=0 && !$skip_stock_check) {
				continue;
			}

			$output .= '<Offer>';

			$categories = $this->model_catalog_product->getCategories($product['product_id']);
			if ($debug) {
				var_dump($categories);
			}


			$cats = array();
			foreach ($categories as $category) {
				$category_info = $this->model_catalog_category->getCategory($category['category_id']);

				if ($category_info) {
					array_push($cats,$category_info['name']);
				}
			}
			$category = implode(" > ", $cats);
			$output .= '<Category><![CDATA['.html_entity_decode($category).']]></Category>';

			$productName = html_entity_decode($product['name']);
			$output .= '<ProductName><![CDATA[' . html_entity_decode($product['name']) . ']]></ProductName>';

			$product_manufacturer = '';
			if (isset($product['manufacturer_id'])) {
				$manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($product['manufacturer_id']);

				if ($manufacturer_info) {	
					$product_manufacturer = $manufacturer_info['name'];
				}
			}
			$output .= '<Manufacturer><![CDATA[' . html_entity_decode($product_manufacturer, ENT_QUOTES, 'UTF-8') . ']]></Manufacturer>';

			$output .= '<ModelNumber><![CDATA[' . $product['model'] . ']]></ModelNumber>';
			$output .= '<UPC><![CDATA[' . $product['upc'] . ']]></UPC>';
			$output .= '<ShopSKU><![CDATA[' . $product['product_id'] . ']]></ShopSKU>';
			$output .= '<OfferName><![CDATA[' . html_entity_decode($product['name']) . ']]></OfferName>';
			$output .= '<ProductLongDescription><![CDATA[' . html_entity_decode($product['description'], ENT_QUOTES, 'UTF-8') . ']]></ProductLongDescription>';

			if (isset($this->request->get['currency'])) {
				$currency = $this->request->get['currency'];
			} else {
				$currency = $this->currency->getCode();
			}

			if ($include_tax) {
				if ((float)$product['special']) {
					$output .= '<SalePrice><![CDATA[' . $this->formatPrice($this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id']), $currency, FALSE, TRUE)) . ']]></SalePrice>';
				}
				$output .= '<Price><![CDATA[' . $this->formatPrice($this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id']), $currency, FALSE, TRUE)) . ']]></Price>';
			} else {
				if ((float)$product['special']) {
					$output .= '<SalePrice><![CDATA[' . $this->formatPrice($this->currency->format($product['special'], $currency, FALSE, TRUE)) . ']]></SalePrice>';
				}
				$output .= '<Price><![CDATA[' . $this->formatPrice($this->currency->format($product['price'], $currency, FALSE, TRUE)) . ']]></Price>';
			}

			$output .= '<ProductURL><![CDATA['.$this->html->getSEOURL('product/product', '&product_id=' . $product['product_id']).']]></ProductURL>';

			$resource = new AResource('image');
			$image = $resource->getResourceAllObjects('products', $product['product_id'],null,1, false);
			if ($image) {
				$output .= '<ImageURL><![CDATA[' . $image['main_url'] . ']]></ImageURL>';
			}

			$output .= '<StockAvailability><![CDATA[' . ($stock_info ? 'In Stock' : 'Out Of Stock') . ']]></StockAvailability>';

			$output .= '<Weight><![CDATA[' . $product['weight']  . ']]></Weight>';

			$output .= '</Offer>';
		}
		$output .= '</Offers>';

		$this->response->addHeader('Content-Type: text/xml');
		$this->response->setOutput($output);
	}

	protected function has_auth() {
		if ($_SERVER['REMOTE_ADDR'] == gethostbyname('admin.pricecheck.co.za')) {
			return true;
		}
		if ($_SERVER['REMOTE_ADDR'] == gethostbyname('admin.pricecheck.com.ng')) {
			return true;
		}

		return false;
	}

	protected function formatPrice($money) {
		$money =   str_replace(',', '', $money);
		$money =   preg_replace('/^\\D*/', '', $money);
		return $money;
	}
}
