<?php

class ControllerFeedGoogleBase extends Controller
{

    public function index()
    {

        if ($this->config->get('google_base_status')) {

            ini_set('memory_limit', '256m');
            ini_set('max_execution_time', '900');

            $output = '<?xml version="1.0" encoding="UTF-8" ?>';
            $output .= '<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">';
            $output .= '<channel>';
            $output .= '<title>' . $this->config->get('config_name') . '</title>';
            $output .= '<description>' . $this->config->get('config_meta_description') . '</description>';
            $output .= '<link>' . $this->url->link('', '', 'SSL', false) . '</link>';

            $this->load->helper('ftr_geral');

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

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

            $this->load->dmodel('tool/image');

            $this->load->type('tipocomum');

            $store_code = $this->config->get('google_store_code');

            $products = $this->model_catalog_product->getProductsGoogleBase();

            foreach ($products as $product) {
                if ((trim(strip_tags($product['description'])) != "") && (trim($product['image']) != "")) {
                    $output .= '<item>';
                    $output .= '<title>' . substr(htmlspecialchars($product['name'], ENT_QUOTES, 'UTF-8'), 0, 65) . '</title>';
                    $output .= '<link>' . htmlspecialchars(str_replace('&amp;', '&', $this->url->link('product/product', 'product_id=' . $product['product_id']))) . '</link>';
                    $output .= '<description>' . htmlspecialchars(str_replace(array('&nbsp;', '&amp;'), array(' ', '&'), strip_tags($this->utf8_for_xml($product['description'])))) . '</description>';
                    $output .= '<g:condition>new</g:condition>';

                    if ($product['manufacturer'] != '') {
                        $output .= '<g:brand>' . htmlspecialchars($product['manufacturer'], ENT_QUOTES, 'UTF-8') . '</g:brand>';
                    }

                    if (ftr_geral::isEAN8($product['codigo_barra'])) {
                        $output .= '<g:gtin>' . $product['codigo_barra'] . '</g:gtin>';
                    }

                    if (ftr_geral::isEAN12($product['codigo_barra'])) {
                        $output .= '<g:gtin>' . $product['codigo_barra'] . '</g:gtin>';
                    }

                    if (ftr_geral::isEAN13($product['codigo_barra'])) {
                        $output .= '<g:gtin>' . $product['codigo_barra'] . '</g:gtin>';
                    }

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

                    if (($product['codigo_barra'] == '') && ($product['mpn'] == '')) {
                        $output .= '<g:identifier_exists>false</g:identifier_exists>';
                    }

                    $output .= '<g:id>' . $product['product_id'] . '</g:id>';

                    if (isset($product['id_grade']) && $product['id_grade'] > 0) {
                        $output .= '<g:item_group_id>' . $product['id_grade'] . '</g:item_group_id>';
                    }

                    if ($product['image']) {
                        $image = $this->dmodel_tool_image->getImageLink($product['image']);
                        $output .= '<g:image_link>' . $image . '</g:image_link>';
                    }

                    if (!empty($product['other_images'])) {
                        $other_images_array = [];
                        $other_images = explode(',', $product['other_images']);
                        foreach ($other_images as $other_image){
                            $other_images_array[] = $this->dmodel_tool_image->getImageLink($other_image);
                        }
                        $other_images_str = implode(',', $other_images_array);
                        $output .= '<g:additional_image_link>' . $other_images_str . '</g:additional_image_link>';
                    }

                    if (!empty($product['sub_category_google_category_id'])) {
                        $output .= '<g:google_product_category>' . $product['sub_category_google_category_id'] . '</g:google_product_category>';
                    } else if (!empty($product['category_google_category_id'])){
                        $output .= '<g:google_product_category>' . $product['category_google_category_id'] . '</g:google_product_category>';
                    }

                    $currencies = array('USD', 'EUR', 'GBP');

                    if (in_array($this->currency->getCode(), $currencies)) {
                        $currency_code = $this->currency->getCode();
                        $currency_value = $this->currency->getValue();
                    } else {
                        $currency_code = 'USD';
                        $currency_value = $this->currency->getValue('USD');
                    }

                    $output .= '<g:price>' . $this->currency->format($product['valor_product'], $currency_code, $currency_value, false) . ' BRL</g:price>';

                    if($product['sub_category_id']){
                        $output .= '<g:product_type>';
                        $output .= $product['dept_id'] ? $product['dept_name'].' > '. $product['category_name'] : $product['category_name'];
                        $output .= ' > '.$product['sub_category_name']. '</g:product_type>';
                    }

                    if($product['category_id']){
                        $output .= '<g:product_type>';
                        $output .= $product['dept_id'] ? $product['dept_name'].' > '. $product['category_name'] : $product['category_name'];
                        $output .= '</g:product_type>';
                    }

                    if($product['dept_id']){
                        $output .= '<g:product_type>' . $product['dept_name'].'</g:product_type>';
                    }

                    if (in_array(Type_DsDn::Tp_Sim, [$product['dept_prod_maior_idade'],$product['category_prod_maior_idade'],$product['sub_category_prod_maior_idade']])) {
                        $output .= '<g:adult>yes</g:adult>';
                    }


                    $output .= '<g:quantity>' . ($product['quantity'] > 0 ? $product['quantity'] : 0) . '</g:quantity>';
                    $output .= '<g:upc>' . $product['upc'] . '</g:upc>';
                    $output .= '<g:weight>' . $this->weight->format($product['weight'], $product['weight_class_id']) . '</g:weight>';

                    $stock = '';
                    if ($product['quantity'] > 0) {
                        $stock = 'in stock';
                    } else {
                        $stock = 'out of stock';
                    }

                    $output .= '<g:availability>' . $stock . '</g:availability>';

                    if (isset($store_code) && strlen($store_code) != 0) {
                        $output .= '<g:store_code>'. $store_code .'</g:store_code>';
                    }

                    $output .= '</item>';
                }
            }

            $output .= '</channel>';
            $output .= '</rss>';

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

    protected function getPath($parent_id, $current_path = '')
    {
        $category_info = $this->model_catalog_category->getCategory($parent_id);

        if ($category_info) {
            if (!$current_path) {
                $new_path = $category_info['category_id'];
            } else {
                $new_path = $category_info['category_id'] . '_' . $current_path;
            }

            $path = $this->getPath($category_info['parent_id'], $new_path);

            if ($path) {
                return $path;
            } else {
                return $new_path;
            }
        }
    }

    protected function isEAN8($upccode)
    {// também conhecido como GTIN
        $odd_sum = $even_sum = 0;
        if (strlen($upccode) != 8) return FALSE;
        $chars = str_split($upccode);
        for ($i = 0; $i < 7; $i++) {
            if ($i % 2 == 0) {
                $odd_sum += $chars[$i] * 3;
            } else {
                $even_sum += $chars[$i];
            }
        }
        $total_sum = $even_sum + $odd_sum;

        $modulo10 = $total_sum % 10;
        $check_digit = 10 - $modulo10;
        return (int)$chars[7] === $check_digit;
    }

    protected function utf8_for_xml($string)
    {
        return preg_replace ('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $string);
    }

}
