<?php
set_time_limit(0);

class ModelUniversalFeedFacebook extends Model
{

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

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

    public function writeBody($fh, $config)
    {
        $log = new Log("FacebookWriteBody.txt");
        $log->write("Start");
        $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 $item) {
            // fix issues of some special chars in descriptions
            $item['description'] = preg_replace('~[^\P{Cc}\r\n]+~u', '', $item['description']);
            $item['meta_description'] = preg_replace('~[^\P{Cc}\r\n]+~u', '', $item['meta_description']);

            $this->session->data['ufeed_lastItem'] = $item['product_id'];

            $line = array(
                'title' => substr($item['name'], 0, 149), // 150 chars max for title in facebook feed
                'link' => $this->url->link('product/product', 'product_id=' . $item['product_id']),
                'description' => $item['meta_description'] ? $item['meta_description'] : $item['name'],
                'g:brand' => 'Deercase',
                'g:condition' => 'new',
                'g:id' => $item['product_id'],
                'g:image_link' => $item['image'],
                'g:mpn' => $item['model'],
                'g:product_type' => $item['product_category'],
                'g:quantity' => $item['quantity'],
                'g:availability' => $item['quantity'] ? 'in stock' : 'out of stock',
                'g:upc' => $item['upc'],
                'g:weight' => $this->weight->format($item['weight'], $item['weight_class_id']),
            );

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

            if (!empty($category['id'])) {
                $line['g:google_product_category'] = $category['id'];
            }

            if ((float)$item['special']) {
                //$price = $this->tax->calculate($item['special'] * $price_modifier, $item['tax_class_id']);
                if (empty($config['price_tax'])) {
                    $line['g:sale_price'] = $this->currency->format($this->tax->calculate($item['special'] * $price_modifier, $item['tax_class_id']), $currency, false, false) . ' ' . $currency;
                } else {
                    $line['g:sale_price'] = $this->currency->format($item['special'] * $price_modifier, $currency, false, false) . ' ' . $currency;
                }
                $line['g:tax_calc_for_sale_price'] = $this->currency->format($this->tax->getTax($item['special'], $item['tax_class_id']), $currency, false, false);
                $line['g:taxed_sale_price'] = $this->currency->format($this->tax->calculate($item['special'], $item['tax_class_id']), $currency, false, false);
            }

            //$price = $this->tax->calculate($item['price'] * $price_modifier, $item['tax_class_id']);
            if (empty($config['price_tax'])) {
                $line['g:price'] = $this->currency->format($this->tax->calculate($item['price'] * $price_modifier, $item['tax_class_id']), $currency, false, false) . ' ' . $currency;
            } else {
                $line['g:price'] = $this->currency->format($item['price'] * $price_modifier, $currency, false, false) . ' ' . $currency;
            }
            $line['g:tax_calc_for_price'] = $this->currency->format($this->tax->getTax($item['price'], $item['tax_class_id']), $currency, false, false);
            $line['g:taxed_price'] = $this->currency->format($this->tax->calculate($item['price'], $item['tax_class_id']), $currency, false, false);

            $additional_images = explode('|', $item['additional_images']);

            $line['g:additional_image_link'] = array();
            foreach ($additional_images as $additional_image) {
                $line['g:additional_image_link'] = $additional_image;
            }

            $output = '<item>';

            foreach ($line as $k => $v) {
                if ($v) {
                    $output .= '<' . $k . '><![CDATA[' . html_entity_decode($v, ENT_QUOTES) . ']]></' . $k . '>';
                } else {
                    $output .= '<' . $k . '/>';
                }
            }

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

            fwrite($fh, $output);

            $row++;
        }

        $log->write("Stop");

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

    private function getGoogleCategory($product_id)
    {
        $gcats = array();
        $categories = $this->db->query("SELECT c.google_merchant_id, cd.name FROM " . DB_PREFIX . "product_to_category p2c LEFT JOIN " . DB_PREFIX . "category c ON (p2c.category_id = c.category_id) LEFT JOIN " . DB_PREFIX . "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;

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

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