<?php
//include "config.php";
//include "system/library/db/mysqli.php";
//include "system/library/db.php";
//include "system/library/log.php";
class ControllerToolLidyanaXml extends Controller
{
    public function index()
    {
    $db = new DB('MySQLi', 'localhost',DB_USERNAME, DB_PASSWORD, DB_DATABASE);

    header("Content-type: text/xml; charset=utf-8");

    //$products_count = $db->query("SELECT MAX(product_id) as product_id FROM ps_product WHERE lidyana = 1 ")->row['product_id'];

    $products_count = $db->query("SELECT COUNT(product_id) AS product_id FROM ps_product WHERE lidyana = 1")->row['product_id'];

    $page_row = round($products_count / 30000);
    if($page_row==0 && $products_count>0) {
        $page_row = 1;
    }
    $limit = 30000;

    $products_id_betweens = array();
    for ($i = 1; $i <= $page_row; $i++) {
        $products_id_betweens[$i] = array(
            'from' => $i == 1 ? 0 : ($limit * $i) - $limit,
            'to' => $limit * $i
        );
    }


    for ($i = 1; $i <= $page_row; $i++) {
        echo $i . "\n";
       $output = '<?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>DeerCase</title>' . "\n" .
            '<description></description>' . "\n" .
            '<link>http://www.deercase.com/</link>' . "\n";



        $sql = " WHERE lidyana = 1 AND product_id BETWEEN " . (int) $products_id_betweens[$i]['from'] . " AND " . (int) $products_id_betweens[$i]['to'];
        $products = $db->query("SELECT product_id FROM ps_product " . $sql)->rows;

        $price_modifier = 1;
        $currency = 'TRY';


        $row = 0;

        foreach ($products as $product){
           // echo $product['product_id'] . "\n";

            $select = 'p.product_id, p.model, p.status, p.price, p.product_showcase, p.lidyana, p.quantity, p.tax_class_id, p.image, m.name as manufacturer, pd.name, pd.href, pd.description, pd.meta_description, c.category_id, c.google_merchant_id ';
            $special = ", (SELECT price FROM ps_product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '1' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special";

            $sql = "SELECT " . $select . $special . " FROM ps_product p";
            $sql .= " LEFT JOIN ps_manufacturer m ON (p.manufacturer_id = m.manufacturer_id)";
            $sql .= " LEFT JOIN ps_product_description pd ON (p.product_id = pd.product_id)";
            $sql .=  " LEFT JOIN ps_product_to_category p2c ON (p.product_id = p2c.product_id)";
            $sql .=  " LEFT JOIN ps_category c ON (p2c.category_id = c.category_id)";

           // $not_in = " AND p.model NOT IN ('cl048','cl025','cl035','cl029','cl037','aq32','vs055','vs033','vs036','PY0053','mr064','mr063','mr062','cl044','cl021','cl034','cl024','cl013','cl032','cl038','cl037','cl033','cl052','cl004','cl023','aq32','lms098','lms102','lms045','lms101','lms103','lms059','lms033','vs040') ";

            $sql .= " WHERE pd.language_id = 1 AND p.product_id = '". $product['product_id'] ."' ";

            $item = $db->query($sql)->row;

            //var_dump($sql); die();

            if($item) {
                //var_dump($item); die();

                // 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']);

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

                $description = '';
                if ($item['meta_description']) {
                    $description = $item['meta_description'];
                } elseif ($item['description']) {
                    $description = $item['description'];
                } else {
                    $description = $item['name'];
                }

                //195749
                $output .= '<title><![CDATA[ ' . $item['name'] . ' ]]></title>' . "\n";
                $output .= '<link><![CDATA[ ' . HTTPS_SERVER . $item['href'] . ' ]]></link>' . "\n";
                $output .= '<description><![CDATA[ ' . htmlentities($description, ENT_QUOTES, 'UTF-8') . ' ]]></description>' . "\n";
                $output .= '<g:brand><![CDATA[ Deercase ]]></g:brand>' . "\n";
                $output .= '<g:condition><![CDATA[ new ]]></g:condition>' . "\n";
                $output .= '<g:id><![CDATA[ ' . $product['product_id'] . ' ]]></g:id>' . "\n";
                $output .= '<g:image_link><![CDATA[ ' . HTTPS_SERVER . 'image/' . $item['image'] . ' ]]></g:image_link>' . "\n";
                //$output .= '<g:mpn><![CDATA[ ' . $item['model'] . ' ]]></g:mpn>' . "\n";

                $output .= '<g:quantity><![CDATA[ ' . $item['quantity'] . ' ]]></g:quantity>' . "\n";
                $output .= '<g:availability><![CDATA[ ' . ($item['quantity'] ? 'in stock' : 'out of stock') . ' ]]></g:availability>' . "\n";
                //$output .= '<g:upc><![CDATA[ ' . $item['model'] . ' ]]></g:upc>' . "\n";
                $output .= '<g:weight><![CDATA[ 0.00 ]]></g:weight>' . "\n";
                $output .= '<g:google_product_category><![CDATA[ ' . $item['google_merchant_id'] . ' ]]></g:google_product_category>' . "\n";
                $output .= '<g:fb_product_category><![CDATA[ ' . $item['google_merchant_id'] . ' ]]></g:fb_product_category>' . "\n";

                //visibility
                //color

                if ($item['product_showcase']) {
                    if ($item['product_showcase']) {
                        $output .= '<custom_label_3><![CDATA[ published ]]></custom_label_3>' . "\n";
                    } else {
                        $output .= '<custom_label_3><![CDATA[ hidden ]]></custom_label_3>' . "\n";
                    }

                } else {
                    $output .= '<custom_label_3><![CDATA[ hidden ]]></custom_label_3>' . "\n";
                }

                //Attribute
                $attribute = $db->query("SELECT ad.name FROM ps_product_attribute pa LEFT JOIN ps_attribute_description ad ON (pa.attribute_id = ad.attribute_id) WHERE ad.language_id = 1 AND product_id = '" . $product['product_id'] . "' ")->row;
                //var_dump($attribute['name']);
                if ($attribute['name']) {
                    $sonuc = strpos($attribute['name'], " ");
                    // var_dump($sonuc);
                    if ($sonuc === false) {
                        $color = $attribute['name'];
                    } else { //var_dump($attribute['name']); die();
                        $color = end(explode(" ", $attribute['name']));
                    }


                    $output .= '<color><![CDATA[ ' . $color . ' ]]></color>' . "\n";
                }

                $custom_label_0 = '';
                $category_path = $db->query("SELECT cd.name FROM ps_product_to_category p2c LEFT JOIN ps_category_description cd ON (p2c.category_id = cd.category_id) WHERE p2c.product_id = '" . $product['product_id'] . "'")->rows;
                foreach ($category_path as $key => $path) {
                    if($key != 2){
                        $custom_label_0 .= ' > ' . $path['name'];
                    }
                }

                $custom_label_0 = substr($custom_label_0, 3, strlen($custom_label_0));

                $output .= '<custom_label_0><![CDATA[ ' . $custom_label_0 . ' ]]></custom_label_0>' . "\n";

                $custom_label_1 = end($category_path)['name'];

                $output .= '<custom_label_1><![CDATA[ ' . $custom_label_1 . ' ]]></custom_label_1>' . "\n";

                $output .= '<custom_label_2><![CDATA[ ' . $item['model'] . ' ]]></custom_label_2>' . "\n";


                $output .= '<g:product_type><![CDATA[ ' . $custom_label_0 . ' > ' . $custom_label_1 . ' ]]></g:product_type>' . "\n";

                //var_dump($custom_label_1); die();

                if ((float)$item['special']) {

                    if (false) {
                        $output .= '<g:sale_price><![CDATA[ ' . ($this->format($this->calculate($item['special'] * $price_modifier, $item['tax_class_id']), $currency, false, false) . ' ' . $currency) . ' ]]></g:sale_price>' . "\n";
                    } else {
                        $output .= '<g:sale_price><![CDATA[ ' . ($this->format($item['special'] * $price_modifier, $currency, false, false) . ' ' . $currency) . ' ]]></g:sale_price>' . "\n";
                    }

                    $output .= '<g:tax_calc_for_sale_price><![CDATA[ ' . ($this->format($this->getTax($item['special'], $item['tax_class_id']), $currency, false, false)) . ' ]]></g:tax_calc_for_sale_price>' . "\n";
                    $output .= '<g:taxed_sale_price><![CDATA[ ' . ($this->format($this->calculate($item['special'], $item['tax_class_id']), $currency, false, false)) . ' ]]></g:taxed_sale_price>' . "\n";

                }

                if (empty($item['price'])) {
                    $output .= '<g:price><![CDATA[ ' . ($this->format($this->calculate($item['price'] * $price_modifier, $item['tax_class_id']), $currency, false, false) . ' ' . $currency) . ' ]]></g:price>' . "\n";
                } else {
                    $output .= '<g:price><![CDATA[ ' . ($this->format($this->calculate($item['price'] * $price_modifier, $item['tax_class_id']), $currency, false, false) . ' ' . $currency) . ' ]]></g:price>' . "\n";
                }


                $output .= '<g:tax_calc_for_price><![CDATA[ ' . ($this->format($this->getTax($item['price'], $item['tax_class_id']), $currency, false, false)) . ' ]]></g:tax_calc_for_price>' . "\n";
                $output .= '<g:taxed_price><![CDATA[ ' . ($this->format($this->calculate($item['price'], $item['tax_class_id']), $currency, false, false)) . ' ]]></g:taxed_price>' . "\n";

                $additional_images = explode('|', $this->getProductImages($product['product_id'], 1, false, $db));

                if($additional_images){
                    foreach ($additional_images as $additional_image) {

                        //https://i.deercase.com/image/repository/neon/NEON08/NEON08-APPLE-IPHONE_6_PLUS-NEON-NEON_VIOLET-2.jpg
                        $additional_image = str_replace('https://www.', 'https://i.', $additional_image);
                        //var_dump($additional_image); die();
                        $output .= '<g:additional_image_link><![CDATA[ ' . $additional_image . ' ]]> </g:additional_image_link>' . "\n";
                    }
                }


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

            }

        }

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

        $rss_xml = new SimpleXMLElement($output);
        $dom = new DomDocument();
        $dom->loadXML($rss_xml->asXML());
        $dom->formatOutput = true;
        //output xml

        //echo $dom->saveXML();

        //$dom->save('upload/xml/facebook_feed/facebook_feed_'. $i .'.xml');
        $dom->save('upload/xml/lidyana/lidyana_'. $i .'.xml');

        // echo $output;

        }
    }
    function getProductImages($product_id, $full_path, $asArray = false, $db) {
        $query = $db->query("SELECT image FROM ps_product_image WHERE product_id = '" . (int)$product_id . "' ORDER BY sort_order ASC");

        if ($asArray) {
            $res = array();

            foreach ($query->rows as &$row) {
                if ($row['image']) {
                    $res[] = HTTPS_SERVER.'image/'.$row['image'];
                }
            }

            return $res;
        }

        $res = '';

        foreach ($query->rows as &$row) {
            if ($row['image']) {
                $res .= $res ? '|' : '';

                if ($full_path) {
                    $res .= HTTPS_SERVER .'image/'.$row['image'];
                } else {
                    $res .= $row['image'];
                }
            }
        }

        return $res;
    }

    function format($number, $currency, $value = '', $format = true) {


        $symbol_left = '';
        $symbol_right = '₺';
        $decimal_place = 2;

        if (!$value) {
            $value = 1.000000;
        }
        //echo (float)$number;
        $amount = $value ? (float)$number * $value : (float)$number;

        $amount = round($amount, (int)$decimal_place);

        if (!$format) {
            return $amount;
        }

        $string = '';

        if ($symbol_left) {
            $string .= $symbol_left;
        }

        $string .= number_format($amount, (int)$decimal_place, ',', '.');

        if ($symbol_right) {
            $string .= $symbol_right;
        }

        return $string;
    }

    function getRates($value, $tax_class_id)
    {

        $tax_rates[2][1] = array(
            'tax_rate_id' => 1,
            'name' => 'KDV (%8)',
            'rate' => 8.0000,
            'type' => 'P',
            'priority' => 2
        );

        $tax_rates[1][2] = array(
            'tax_rate_id' => 2,
            'name' => 'KDV (%18)',
            'rate' => 18.0000,
            'type' => 'P',
            'priority' => 2
        );

        $tax_rate_data = array();

        if (isset($tax_rates[$tax_class_id])) {
            foreach ($tax_rates[$tax_class_id] as $tax_rate) {
                if (isset($tax_rate_data[$tax_rate['tax_rate_id']])) {
                    $amount = $tax_rate_data[$tax_rate['tax_rate_id']]['amount'];
                } else {
                    $amount = 0;
                }

                if ($tax_rate['type'] == 'F') {
                    $amount += $tax_rate['rate'];
                } elseif ($tax_rate['type'] == 'P') {
                    $amount += ($value / 100 * $tax_rate['rate']);
                }

                $tax_rate_data[$tax_rate['tax_rate_id']] = array(
                    'tax_rate_id' => $tax_rate['tax_rate_id'],
                    'name' => $tax_rate['name'],
                    'rate' => $tax_rate['rate'],
                    'type' => $tax_rate['type'],
                    'amount' => $amount
                );
            }
        }

        return $tax_rate_data;
    }

    function getTax($value, $tax_class_id)
    {
        $amount = 0;
        $tax_rates = $this->getRates($value, $tax_class_id);
        foreach ($tax_rates as $tax_rate) {
            $amount += $tax_rate['amount'];
        }
        return $amount;
    }

    function calculate($value, $tax_class_id, $calculate = true, $add_fee = false, $product_id = FALSE)
    {

        if ($add_fee == true) {
            $customer_group_id = 1;
            $value = $this->getExtraFee($value, $customer_group_id, $product_id);
        }

        if ($tax_class_id && $calculate) {
            $amount = 0;

            $tax_rates = $this->getRates($value, $tax_class_id);

            foreach ($tax_rates as $tax_rate) {
                if ($calculate != 'P' && $calculate != 'F') {
                    $amount += $tax_rate['amount'];
                } elseif ($tax_rate['type'] == $calculate) {
                    $amount += $tax_rate['amount'];
                }
            }

            return $value + $amount;
        } else {
            return $value;
        }
    }

}
?>