<?php
class ModelUniversalFeedGoogleMerchant extends Model {

    public function writeHeader($fh, $config) {
        fwrite($fh, '<?xml version="1.0"?><rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">'.
            '<channel>'.
            '<title><![CDATA['.$this->config->get('config_name').']]></title>'.
            '<link><![CDATA['.$this->config->get('config_url').']]></link>' . "\n");
    }

    public function writeFooter($fh) {
        fwrite($fh, '</channel></rss>');
    }

    public function writeBody($fh, $config) {

        ini_set('display_errors', 0);
        $config['filter_store'] = $this->config->get('config_store_id');

        $products = $this->model_universal_feed_driver_product->getItems($config);

        //$products = $this->model_tool_universal_feed->getProducts($config);

        $price_modifier = !empty($config['price_modifier']) ? $config['price_modifier'] : 1;
        $currency = !empty($config['currency']) ? $config['currency'] : 'USD';
        $gtin = !empty($config['gtin']) ? $config['gtin'] : '';

        $row = 0;
        $save_count = 0;

        foreach ($products as $product) { //var_dump($product); die();
            // fix issues of some special chars in descriptions
            $product['description'] = preg_replace('~[^\P{Cc}\r\n]+~u', '', $product['description']);

            $this->session->data['ufeed_lastItem'] = $product['product_id'];
            $output = '<item>';
            $output .= '<g:id><![CDATA[' . htmlentities($product['model'], ENT_QUOTES, 'UTF-8', 0) . '-' . $product['product_id'] . ']]></g:id>';
            $output .= '<g:title><![CDATA[' . htmlentities($product['name'], ENT_QUOTES, 'UTF-8', 0) . ']]></g:title>';
            $output .= '<g:description><![CDATA[' . $this->model_tool_universal_feed->truncate($this->model_tool_universal_feed->sanitize($product['description']), 5000) . ']]></g:description>';
            $output .= '<g:link><![CDATA[' . $this->url->link('product/product', 'product_id=' . $product['product_id']) . ']]></g:link>';

            if ($product['image']) {
                $output .= '<g:image_link><![CDATA[' . $this->model_tool_image->resize($product['image_path'], 250, 250) . ']]></g:image_link>';
            } else {
                $output .= '<g:image_link><![CDATA[' . $this->model_tool_image->resize('no_image.jpg', 250, 250) . ']]></g:image_link>';
            }

            $output .= '<g:condition>new</g:condition>'; // new, used, refurbished

            $stock = $product['quantity'] ? 'in stock' : 'out of stock';
            $output .= '<g:availability>' . $stock . '</g:availability>'; // preorder, in stock, out of stock

            if (empty($config['price_tax'])) {
                $price = $this->currency->format($this->tax->calculate(($product['special'] ? $product['special'] : $product['price']) * $price_modifier, $product['tax_class_id']), $currency, false, false);
            } else {
                $price = $this->currency->format(($product['special'] ? $product['special'] : $product['price']) * $price_modifier, $currency, false, false);
            }

            $output .= '<g:price>' . $price . ' ' . $currency . '</g:price>';
            $output .= '<g:shipping_weight>' . $this->weight->format($product['weight'], false) . ' ' . $this->weight->getUnit($product['weight_class_id']). '</g:shipping_weight>';

            if (!empty($config['shipping'])) {
                foreach ($config['shipping'] as $shipping) {
                    $shipping_data = explode(':', $shipping);

                    if (count($shipping_data) != 4) continue;

                    $output .= '<g:shipping>';
                    $output .= '<g:country>'.$shipping_data[0].'</g:country>';
                    $output .= '<g:region>'.$shipping_data[1].'</g:region>';
                    $output .= '<g:service>'.$shipping_data[2].'</g:service>';
                    $output .= '<g:price>'.$shipping_data[3].'</g:price>';
                    $output .= '</g:shipping>';
                }
            }

            //<!-- 2 of the following 3 attributes are required fot this item according to the Unique Product Identifier Rules -->
            $has_identifier = 0;

            if (!empty($product[$gtin])) {
                $has_identifier++;
                $output .= '<g:gtin>' . $product[$gtin] . '</g:gtin>';
            }

            if ($product['manufacturer']) {
                $has_identifier++;
                //$output .= '<g:brand><![CDATA[' . htmlentities($product['manufacturer'], ENT_QUOTES, 'UTF-8', 0) . ']]></g:brand>';
                $output .= '<g:brand>Deercase</g:brand>';
            }

            if ($product['mpn']) {
                $has_identifier++;
                $output .= '<g:mpn>' . $product['mpn'] . '</g:mpn>';
            }

            if ($has_identifier < 2) {
                $output .= '<g:identifier_exists>TRUE</g:identifier_exists>';
            }

            if($this->config->get('config_product_adult')){
                $output .= '<g:adult>FALSE</g:adult>';
            }

            $category = $this->getGoogleCategory($product['product_id']);

            if (!empty($category['id'])) {
                $output .= '<g:google_product_category>' . $category['id'] . '</g:google_product_category>';
            }

            if (!empty($category['id'])) {
                //$product['product_category'] = explode('|', $product['product_category']);
                //$output .= '<g:product_type><![CDATA[' . htmlspecialchars($product['product_category'], ENT_QUOTES, 'UTF-8', 0) . ']]></g:product_type>';
                $output .= '<g:product_type><![CDATA[' . $this->db->escape($product['product_category']) . ']]></g:product_type>';
            }

            $images = $this->model_tool_universal_feed->getProductImages($product['product_id']);

            foreach ($images as $i => $image) {
                $output .= '<g:additional_image_link><![CDATA[' . $this->model_tool_image->resize($image['image'], 250, 250) . ']]></g:additional_image_link>' ."\n";
                if ($i >= 9) break;
            }

            $output .= '</item>' . "\n";

            fwrite($fh, $output);

            $row++;
        }

        // return false when no more products
        return !empty($output);
    }

    public function getTotalItems($data = array()) {
        return $this->model_universal_feed_driver_product->getTotalItems($data);
    }

    private function getGoogleCategory($product_id) {

        $gcats = array();
        $categories = $this->db->query("SELECT c.google_merchant_id, cd.name FROM ps_product_to_category p2c 
        LEFT JOIN ps_category c ON (p2c.category_id = c.category_id) 
        LEFT JOIN ps_category_description cd ON (c.category_id = cd.category_id) AND cd.language_id = " . $this->config->get('config_language_id') . " 
        WHERE product_id = '" . (int)$product_id . "'")->rows;

        /* $sql = "SELECT cp.category_id AS category_id, GROUP_CONCAT(cd1.name ORDER BY cp.level SEPARATOR '&nbsp;&nbsp;&gt;&nbsp;&nbsp;') AS name, c1.parent_id, c1.sort_order FROM ps_category_path cp
         LEFT JOIN ps_category c1 ON (cp.category_id = c1.category_id)
         LEFT JOIN ps_category c2 ON (cp.path_id = c2.category_id)
         LEFT JOIN ps_category_description cd1 ON (cp.path_id = cd1.category_id)
         LEFT JOIN ps_category_description cd2 ON (cp.category_id = cd2.category_id)
         WHERE cd1.language_id = '" . (int)$this->config->get('config_language_id') . "' AND cd2.language_id = '" . (int)$this->config->get('config_language_id') . "'";*/

        foreach($categories as $category) {
            if (!empty($category['google_merchant_id'])) {
                return array(
                    'id' => $category['google_merchant_id'],
                    'name' => $category['name'],
                );
            }
        }
    }
}