<?php
class ModelCatalogProduct extends Model {

    public function addProduct($data) {

        $this->db->query("INSERT INTO " . DB_PREFIX . "product SET 
        model = '" . $this->db->escape($data['model']) . "'
        , sku = '" . $this->db->escape($data['sku']) . "'
        , upc = '" . $this->db->escape($data['upc']) . "'
        , ean = '" . $this->db->escape($data['ean']) . "'
        , jan = '" . $this->db->escape($data['jan']) . "'
        , isbn = '" . $this->db->escape($data['isbn']) . "'
        , mpn = '" . $this->db->escape($data['mpn']) . "'
        , location = '" . $this->db->escape($data['location']) . "'
        , quantity = '" . (int)$data['quantity'] . "'
        , minimum = '" . (int)$data['minimum'] . "'
        , subtract = '" . (int)$data['subtract'] . "'
        , stock_status_id = '" . (int)$data['stock_status_id'] . "'
        , date_available = '" . $this->db->escape($data['date_available']) . "'
        , manufacturer_id = '" . (int)$data['manufacturer_id'] . "'
        , shipping = '" . (int)$data['shipping'] . "'
        , price = '" . (float)$data['price'] . "'
        , points = '" . (int)$data['points'] . "'
        , weight = '" . (float)$data['weight'] . "'
        , weight_class_id = '" . (int)$data['weight_class_id'] . "'
        , length = '" . (float)$data['length'] . "'
        , width = '" . (float)$data['width'] . "'
        , height = '" . (float)$data['height'] . "'
        , length_class_id = '" . (int)$data['length_class_id'] . "'
        , status = '" . (int)$data['status'] . "'
        , tax_class_id = '" . (int)$data['tax_class_id'] . "'
        , sort_order = '" . (int)$data['sort_order'] . "'
        , date_added = NOW()");

        $product_id = $this->db->getLastId();

        // Saving remote Image, if URL given.
        if (isset($data['image']) || !empty($data['image_url'])) {
            $image = $this->model_tool_image->saveRemoteImage( $data['image_url']);
            if(is_file(DIR_IMAGE . $image)) {
                $data['image'] = $image;
            }
            $this->db->query("UPDATE " . DB_PREFIX . "product SET image = '" . $this->db->escape($data['image']) . "' WHERE product_id = '" . (int)$product_id . "'");
        }

        foreach ($data['product_description'] as $language_id => $value) {
            $this->db->query("INSERT INTO " . DB_PREFIX . "product_description SET product_id = '" . (int)$product_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "', description = '" . $this->db->escape($value['description']) . "', tag = '" . $this->db->escape($value['tag']) . "', meta_title = '" . $this->db->escape($value['meta_title']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', meta_keyword = '" . $this->db->escape($value['meta_keyword']) . "'");
        }

        if (isset($data['product_store'])) {
            foreach ($data['product_store'] as $store_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_store SET product_id = '" . (int)$product_id . "', store_id = '" . (int)$store_id . "'");
            }
        }

        if (isset($data['product_attribute'])) {
            foreach ($data['product_attribute'] as $product_attribute) {
                if ($product_attribute['attribute_id']) {
                    foreach ($product_attribute['product_attribute_description'] as $language_id => $product_attribute_description) {
                        $this->db->query("INSERT INTO " . DB_PREFIX . "product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$product_attribute['attribute_id'] . "', language_id = '" . (int)$language_id . "', text = '" . $this->db->escape($product_attribute_description['text']) . "'");
                    }
                }
            }
        }

        if (isset($data['product_option'])) {
            foreach ($data['product_option'] as $product_option) {
                if ($product_option['type'] == 'select' || $product_option['type'] == 'radio' || $product_option['type'] == 'checkbox' || $product_option['type'] == 'image') {
                    if (isset($product_option['product_option_value'])) {
                        $this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET product_id = '" . (int)$product_id . "', option_id = '" . (int)$product_option['option_id'] . "', required = '" . (int)$product_option['required'] . "'");

                        $product_option_id = $this->db->getLastId();

                        foreach ($product_option['product_option_value'] as $product_option_value) {
                            $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET 
                              product_option_id = '" . (int)$product_option_id . "'
                            , product_id = '" . (int)$product_id . "'
                            , option_id = '" . (int)$product_option['option_id'] . "'
                            , option_value_id = '" . (int)$product_option_value['option_value_id'] . "'
                            , quantity = '" . (int)$product_option_value['quantity'] . "'
                            , subtract = '" . (int)$product_option_value['subtract'] . "'
                            , price = '" . (float)$product_option_value['price'] . "'
                            , price_prefix = '" . $this->db->escape($product_option_value['price_prefix']) . "'
                            , points = '" . (int)$product_option_value['points'] . "'
                            , points_prefix = '" . $this->db->escape($product_option_value['points_prefix']) . "'
                            , weight = '" . (float)$product_option_value['weight'] . "'
                            , weight_prefix = '" . $this->db->escape($product_option_value['weight_prefix']) . "'
                            , description = '" . $this->db->escape($product_option_value['description']) . "'
                            , article = '" . $this->db->escape($product_option_value['article']) . "'
                            ");
                        }
                    }
                } else {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET 
                      product_id = '" . (int)$product_id . "'
                    , option_id = '" . (int)$product_option['option_id'] . "'
                    , value = '" . $this->db->escape($product_option['value']) . "'
                    , required = '" . (int)$product_option['required'] . "'");
                }
            }
        }

        if (isset($data['product_discount'])) {
            foreach ($data['product_discount'] as $product_discount) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_discount SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$product_discount['customer_group_id'] . "', quantity = '" . (int)$product_discount['quantity'] . "', priority = '" . (int)$product_discount['priority'] . "', price = '" . (float)$product_discount['price'] . "', date_start = '" . $this->db->escape($product_discount['date_start']) . "', date_end = '" . $this->db->escape($product_discount['date_end']) . "'");
            }
        }

        if (isset($data['product_special'])) {
            foreach ($data['product_special'] as $product_special) {

                $product_special['date_start'] = $product_special['date_start'] ? $product_special['date_start'] : "1970-01-01";
                $product_special['date_end'] = $product_special['date_end'] ? $product_special['date_end'] : "9999-12-31";

                $this->db->query("INSERT INTO " . DB_PREFIX . "product_special 
                SET product_id = '" . (int)$product_id . "'
                , customer_group_id = '" . (int)$product_special['customer_group_id'] . "'
                , priority = '" . (int)$product_special['priority'] . "'
                , price = '" . (float)$product_special['price'] . "'
                , date_start = '".$this->db->escape($product_special['date_start'])."'
                , date_end = '".$this->db->escape($product_special['date_end'])."'");
            }
        }

        if (isset($data['product_image'])) {
            foreach ($data['product_image'] as $product_image) {

                if (!empty($product_image['image_url'])) {
                    $image = $this->model_tool_image->saveRemoteImage($product_image['image_url']);
                    if (is_file(DIR_IMAGE . $image)) {
                        $product_image['image'] = $image;
                    }
                }


                $this->db->query("INSERT INTO " . DB_PREFIX . "product_image SET product_id = '" . (int)$product_id . "', image = '" . $this->db->escape($product_image['image']) . "', sort_order = '" . (int)$product_image['sort_order'] . "'");

                $product_image_id = $this->db->getLastId();

                if ($product_image['description']) {
                    foreach ($product_image['description'] as $language_id => $description) {
                        $this->db->query("INSERT INTO " . DB_PREFIX . "product_image_description SET product_image_id = '" . (int)$product_image_id . "', language_id = '" . (int)$language_id . "', description='" . $this->db->escape($description['description']) . "', product_id='" . (int)$product_id . "'");
                    }
                }
            }
        }


        // Update content meta - delete, if empty!
        $this->model_catalog_content->updateContentMeta($product_id, 'product', $data['content_meta']);

        if (isset($data['product_download'])) {
            foreach ($data['product_download'] as $download_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_download SET product_id = '" . (int)$product_id . "', download_id = '" . (int)$download_id . "'");
            }
        }

        if (isset($data['product_category'])) {
            foreach ($data['product_category'] as $category_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_category SET product_id = '" . (int)$product_id . "', category_id = '" . (int)$category_id . "'");
            }
        }

        if (isset($data['product_filter'])) {
            foreach ($data['product_filter'] as $filter_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_filter SET product_id = '" . (int)$product_id . "', filter_id = '" . (int)$filter_id . "'");
            }
        }

        if (isset($data['product_related'])) {
            foreach ($data['product_related'] as $related_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");
            }
        }

        if (isset($data['product_backway'])) {
            foreach ($data['product_backway'] as $related_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$related_id . "', related_id = '" . (int)$product_id . "'");
            }
        }

        if (isset($data['product_group_id'])) {
            $sql = "INSERT INTO " . DB_PREFIX . "product_to_product "
                   . "SET product_group_id='" . (int)$data['product_group_id'] . "', "
                   . "product_id='" . (int)$product_id . "', "
                   . "default_id=0";
            $this->db->query($sql);
        } elseif (isset($data['product'])) {
            $sql = "INSERT INTO " . DB_PREFIX . "product_to_product "
                   . "SET product_id='" . (int)$product_id . "', "
                   . "default_id=0";

            $this->db->query($sql);

            $product_group_id = $this->db->getLastId();

            $sql = "INSERT INTO " . DB_PREFIX . "product_to_product "
                   . "SET product_group_id='" . (int)$product_group_id . "', "
                   . "product_id='" . (int)$data['product'] . "', "
                   . "default_id=1";
            $this->db->query($sql);
        }


        if (isset($data['product_reward'])) {
            foreach ($data['product_reward'] as $customer_group_id => $product_reward) {
                if ((int)$product_reward['points'] > 0) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "product_reward SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$customer_group_id . "', points = '" . (int)$product_reward['points'] . "'");
                }
            }
        }

        if (isset($data['product_layout'])) {
            foreach ($data['product_layout'] as $store_id => $layout_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_layout SET product_id = '" . (int)$product_id . "', store_id = '" . (int)$store_id . "', layout_id = '" . (int)$layout_id . "'");
            }
        }

        if (isset($data['seo_keywords']) && $data['seo_keywords']) {
            foreach ($data['seo_keywords'] as $language_id => $keyword) {
                if (empty($keyword)) {
                    $keyword = $this->seourl->uniqueSeoKeyword($this->seourl->seoURL($data['product_description'][$language_id]['name']), $language_id);
                } else {
                    $keyword = $this->seourl->uniqueSeoKeyword($this->seourl->seoURL($keyword), $language_id);
                }
                $this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $this->db->escape($keyword) . "', language_id = '" . (int)$language_id . "'");
            }
        }

        if (isset($data['keyword']) && $data['keyword']) {

            $this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $this->db->escape($data['keyword']) . "'");
        }

        if (isset($data['product_recurring'])) {
            foreach ($data['product_recurring'] as $recurring) {
                $this->db->query("INSERT INTO `" . DB_PREFIX . "product_recurring` 
                SET `product_id` = " . (int)$product_id . "
                , customer_group_id = " . (int)$recurring['customer_group_id'] . "
                , `recurring_id` = " . (int)$recurring['recurring_id']);
            }
        }

        $this->cache->delete('product');

        return $product_id;
    }

    public function editProduct($product_id, $data) {

        $this->load->model('catalog/content');
        $this->db->query("UPDATE " . DB_PREFIX . "product SET model = '" . $this->db->escape($data['model']) . "'
        , sku = '" . $this->db->escape($data['sku']) . "', upc = '" . $this->db->escape($data['upc']) . "'
        , ean = '" . $this->db->escape($data['ean']) . "'
        , jan = '" . $this->db->escape($data['jan']) . "'
        , isbn = '" . $this->db->escape($data['isbn']) . "'
        , mpn = '" . $this->db->escape($data['mpn']) . "'
        , location = '" . $this->db->escape($data['location']) . "'
        , quantity = '" . (int)$data['quantity'] . "'
        , minimum = '" . (int)$data['minimum'] . "'
        , subtract = '" . (int)$data['subtract'] . "'
        , stock_status_id = '" . (int)$data['stock_status_id'] . "'
        , date_available = '" . $this->db->escape($data['date_available']) . "'
        , manufacturer_id = '" . (int)$data['manufacturer_id'] . "'
        , shipping = '" . (int)$data['shipping'] . "'
        , price = '" . (float)$data['price'] . "'
        , points = '" . (int)$data['points'] . "'
        , weight = '" . (float)$data['weight'] . "'
        , weight_class_id = '" . (int)$data['weight_class_id'] . "'
        , length = '" . (float)$data['length'] . "'
        , width = '" . (float)$data['width'] . "'
        , height = '" . (float)$data['height'] . "'
        , length_class_id = '" . (int)$data['length_class_id'] . "'
        , status = '" . (int)$data['status'] . "'
        , tax_class_id = '" . (int)$data['tax_class_id'] . "'
        , sort_order = '" . (int)$data['sort_order'] . "'
        , date_modified = NOW() WHERE product_id = '" . (int)$product_id . "'");


        // Saving remote Image, if URL given.
        if (isset($data['image']) || !empty($data['image_url'])) {
            $image = $this->model_tool_image->saveRemoteImage( $data['image_url']);
            if(is_file(DIR_IMAGE . $image)) {
                $data['image'] = $image;
            }
            $this->db->query("UPDATE " . DB_PREFIX . "product SET 
            image = '" . $this->db->escape($data['image']) . "' 
            , image_url = '" . $this->db->escape($data['image_url']) . "' 
            WHERE product_id = '" . (int)$product_id . "'");

        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");

        foreach ($data['product_description'] as $language_id => $value) {
            $this->db->query("INSERT INTO " . DB_PREFIX . "product_description SET "
                             . "product_id = '" . (int)$product_id . "'"
                             . ", language_id = '" . (int)$language_id . "'"
                             . ", name = '" . $this->db->escape($value['name']) . "'"
                             . ", description = '" . $this->db->escape($value['description']) . "'"
                             . ", tag = '" . $this->db->escape($value['tag']) . "'"
                             . ", meta_title = '" . $this->db->escape($value['meta_title']) . "'"
                             . ", meta_description = '" . $this->db->escape($value['meta_description']) . "'"
                             . ", admin_description = '" . $this->db->escape($value['admin_description']) . "'"
                             . ", meta_keyword = '" . $this->db->escape($value['meta_keyword']) . "'");
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_store WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_store'])) {
            foreach ($data['product_store'] as $store_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_store SET product_id = '" . (int)$product_id . "', store_id = '" . (int)$store_id . "'");
            }
        }

        // Product Group - add, edit, update, fix empties. - START

        if (isset($data['product_group_id']) && $data['product_group_id']) {
            $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_product WHERE product_group_id = '" . (int)$data['product_group_id'] . "'");
            $product_group_id = $data['product_group_id'];
        } else {
            $max = $this->db->query("SELECT MAX(product_group_id) as group_id FROM `" . DB_PREFIX . "product_to_product`");
            $product_group_id = $max->row['group_id'] + 1;
        }


        if (!empty($data['product_group'])) {
            foreach ($data['product_group'] as $product_group) {
                $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_product WHERE "
                                 . "product_id = '" . (int)$product_group['product_id'] . "'");

                $this->db->query("REPLACE INTO " . DB_PREFIX . "product_to_product
						SET product_group_id = '" . (int)$product_group_id . "',
						product_id = '" . (int)$product_group['product_id'] . "',
						default_id = '" . (int)(isset($data['main_product_id']) && $data['main_product_id'] == $product_group['product_id'] ? 1 : 0) . "'");
                isset($data['main_product_id']) && $data['main_product_id'] == $product_group['product_id'] ? $main_product_id = 1 : '';
            }

            // Add the current product itself to the product group:
            // And - if there was NO main product - set this one as Main.
            $this->db->query("REPLACE INTO " . DB_PREFIX . "product_to_product
						SET product_group_id = '" . (int)$product_group_id . "',
						product_id = '" . (int)$product_id . "',
						default_id = '" . (!empty($main_product_id) ? '0' : '1') . "'");
        } else {
            // if there is NO product group, then just remove THIS product from any group
            $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_product WHERE product_id = '" . (int)$product_id . "'");
            // AND - fix DEFAULT product - set at least ONE
            // TODO: write it shorter :)
            $sql = "update " . DB_PREFIX . "product_to_product p2p1, (select * from "
                   . DB_PREFIX . "product_to_product p2p1 "
                   . "where not exists (select * from " . DB_PREFIX . "product_to_product p2p2 "
                   . "where `default_id` > 0 and p2p2.product_group_id = p2p1.product_group_id ) "
                   . "group by p2p1.product_group_id) p2p3 set p2p1.default_id=1 "
                   . "where p2p3.product_id = p2p1.product_id";
            $this->db->query($sql);
        }

        // after all group changes, we must  'fix' groups which does not have any "default" product:
        $this->db->query("update " . DB_PREFIX . "product_to_product set default_id = 1 where product_id in
			(select  product_id from ( SELECT distinct product_id  FROM `" . DB_PREFIX . "product_to_product` p
				where not EXISTS (select * from  `" . DB_PREFIX . "product_to_product` where default_id = 1  and product_group_id = p.product_group_id  )
				GROUP by product_group_id ) as temporaryName )");

        // now, delete ALL product_to_product, which have only one product (so - pointing to itself:
        $this->db->query("delete from `" . DB_PREFIX . "product_to_product` "
                         . "where product_id in  (select product_id from "
                         . "(SELECT product_id FROM `" . DB_PREFIX . "product_to_product` "
                         . "group by `product_group_id` having count(product_id) < 2) as temporaryName  )");
        // Product Group - add, edit, update, fix empties. END

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "'");

        if (!empty($data['product_attribute'])) {
            foreach ($data['product_attribute'] as $product_attribute) {
                if ($product_attribute['attribute_id']) {
                    // Removes duplicates
                    $this->db->query("DELETE FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "' AND attribute_id = '" . (int)$product_attribute['attribute_id'] . "'");

                    foreach ($product_attribute['product_attribute_description'] as $language_id => $product_attribute_description) {
                        $this->db->query("INSERT INTO " . DB_PREFIX . "product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$product_attribute['attribute_id'] . "', language_id = '" . (int)$language_id . "', text = '" . $this->db->escape($product_attribute_description['text']) . "'");
                    }
                }
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_option_value WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_option'])) {
            foreach ($data['product_option'] as $product_option) {
                if ($product_option['type'] == 'select' || $product_option['type'] == 'radio' || $product_option['type'] == 'checkbox' || $product_option['type'] == 'image' || $product_option['type'] == 'custom') {
                    if (isset($product_option['product_option_value'])) {
                        $this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET 
                        product_option_id = '" . (int)$product_option['product_option_id'] . "'
                        , product_id = '" . (int)$product_id . "'
                        , option_id = '" . (int)$product_option['option_id'] . "'
                        , required = '" . (int)$product_option['required'] . "'");

                        $product_option_id = $this->db->getLastId();

                        foreach ($product_option['product_option_value'] as $product_option_value) {

                            $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET "
                                             . "product_option_value_id = '" . (int)$product_option_value['product_option_value_id'] . "'"
                                             . ", product_option_id = '" . (int)$product_option_id . "'"
                                             . ", product_id = '" . (int)$product_id . "'"
                                             . ", option_id = '" . (int)$product_option['option_id'] . "'"
                                             . ", option_value_id = '" . (int)$product_option_value['option_value_id'] . "'"
                                             . ", quantity = '" . (int)$product_option_value['quantity'] . "'"
                                             . ", subtract = '" . (int)$product_option_value['subtract'] . "'"
                                             . ", price = '" . (float)$product_option_value['price'] . "'"
                                             . ", price_prefix = '" . $this->db->escape($product_option_value['price_prefix']) . "'"
                                             . ", points = '" . (int)$product_option_value['points'] . "'"
                                             . ", points_prefix = '" . $this->db->escape($product_option_value['points_prefix']) . "'"
                                             . ", weight = '" . (float)$product_option_value['weight'] . "'"
                                             . ", weight_prefix = '" . $this->db->escape($product_option_value['weight_prefix']) . "'"
                                             . ", description = '" . $this->db->escape($product_option_value['description']) . "'"
                                             . ", article = '" . $this->db->escape($product_option_value['article']) . "'"

                            );
                        }
                    }
                } else {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET "
                                     . "product_option_id = '" . (int)$product_option['product_option_id'] . "' "
                                     . ", product_id = '" . (int)$product_id . "'"
                                     . ", option_id = '" . (int)$product_option['option_id'] . "'"
                                     . ", value = '" . $this->db->escape($product_option['value']) . "'"
                                     . ", required = '" . (int)$product_option['required'] . "'");
                }
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_discount'])) {
            foreach ($data['product_discount'] as $product_discount) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_discount SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$product_discount['customer_group_id'] . "', quantity = '" . (int)$product_discount['quantity'] . "', priority = '" . (int)$product_discount['priority'] . "', price = '" . (float)$product_discount['price'] . "', date_start = '" . $this->db->escape($product_discount['date_start']) . "', date_end = '" . $this->db->escape($product_discount['date_end']) . "'");
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "'");



        if (isset($data['product_special'])) {
            foreach ($data['product_special'] as $product_special) {
                $product_special['date_start'] = $product_special['date_start'] ? $product_special['date_start'] : "1970-01-01";
                $product_special['date_end'] = $product_special['date_end'] ? $product_special['date_end'] : "9999-12-31";

                $this->db->query("INSERT INTO " . DB_PREFIX . "product_special 
                SET product_id = '" . (int)$product_id . "'
                , customer_group_id = '" . (int)$product_special['customer_group_id'] . "'
                , priority = '" . (int)$product_special['priority'] . "'
                , price = '" . (float)$product_special['price'] . "'
                , date_start = '".$this->db->escape($product_special['date_start'])."'
                , date_end = '".$this->db->escape($product_special['date_end'])."'");
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_image_description WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_image'])) {
            foreach ($data['product_image'] as $product_image) {


                if (!empty($product_image['image_url'])) {
                    $image = $this->model_tool_image->saveRemoteImage($product_image['image_url']);
                    if (is_file(DIR_IMAGE . $image)) {
                        $product_image['image'] = $image;
                    }
                }


                $this->db->query("INSERT INTO " . DB_PREFIX . "product_image SET product_id = '" . (int)$product_id . "'
                , image = '" . $this->db->escape($product_image['image']) . "'
                , image_url = '" . $this->db->escape($product_image['image_url']) . "'
                , sort_order = '" . (int)$product_image['sort_order'] . "'");

                $product_image_id = $this->db->getLastId();

                if ($product_image['description']) {
                    foreach ($product_image['description'] as $language_id => $description) {
                        $sql = "INSERT INTO " . DB_PREFIX . "product_image_description SET product_image_id = '" . (int)$product_image_id . "', language_id = '" . (int)$language_id . "', description='" . $this->db->escape($description['description']) . "', product_id='" . (int)$product_id . "'";
                        $this->db->query($sql);
                    }
                }
            }
        }


        // $this->db->query("DELETE FROM " . DB_PREFIX . "content_meta WHERE content_type = 'product' AND content_id = '" . (int)$product_id . "'");
        if (isset($data['content_meta'])) {
            $this->model_catalog_content->updateContentMeta($product_id, 'product', $data['content_meta']);
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_download WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_download'])) {
            foreach ($data['product_download'] as $download_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_download SET product_id = '" . (int)$product_id . "', download_id = '" . (int)$download_id . "'");
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_category'])) {
            foreach ($data['product_category'] as $category_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_category SET product_id = '" . (int)$product_id . "', category_id = '" . (int)$category_id . "'");
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_filter WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_filter'])) {
            foreach ($data['product_filter'] as $filter_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_filter SET product_id = '" . (int)$product_id . "', filter_id = '" . (int)$filter_id . "'");
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE related_id = '" . (int)$product_id . "'");


        if (isset($data['product_related'])) {
            foreach ($data['product_related'] as $related_id) {
                $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "' AND related_id = '" . (int)$related_id . "'");
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");
            }
        }

        if (isset($data['product_backway'])) {
            foreach ($data['product_backway'] as $related_id) {
                $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$related_id . "' AND related_id = '" . (int)$product_id . "'");
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$related_id . "', related_id = '" . (int)$product_id . "'");
            }
        }

        //Delete "incorrect" relations
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "' AND related_id = '" . (int)$product_id . "'");

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_reward WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_reward'])) {
            foreach ($data['product_reward'] as $customer_group_id => $value) {
                if ((int)$value['points'] > 0) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "product_reward SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$customer_group_id . "', points = '" . (int)$value['points'] . "'");
                }
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_layout WHERE product_id = '" . (int)$product_id . "'");

        if (isset($data['product_layout'])) {
            foreach ($data['product_layout'] as $store_id => $layout_id) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_layout SET product_id = '" . (int)$product_id . "', store_id = '" . (int)$store_id . "', layout_id = '" . (int)$layout_id . "'");
            }
        }

        $this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . (int)$product_id . "'");

        if ($data['seo_keywords']) {
            foreach ($data['seo_keywords'] as $language_id => $keyword) {
                if (empty($keyword)) {
                    $keyword = $this->seourl->uniqueSeoKeyword($this->seourl->seoURL($data['product_description'][$language_id]['name']), $language_id);
                } else {
                    $keyword = $this->seourl->uniqueSeoKeyword($this->seourl->seoURL($keyword), $language_id); //Arnis1
                }
                $this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $this->db->escape($keyword) . "', language_id = '" . (int)$language_id . "'");
            }
        }

        if ($data['keyword']) {
            $this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $this->db->escape($data['keyword']) . "'");
        }

        $this->db->query("DELETE FROM `" . DB_PREFIX . "product_recurring` WHERE product_id = " . (int)$product_id);

        if (isset($data['product_recurring'])) {
            foreach ($data['product_recurring'] as $product_recurring) {
                $this->db->query("INSERT INTO `" . DB_PREFIX . "product_recurring` SET `product_id` = " . (int)$product_id . ", customer_group_id = " . (int)$product_recurring['customer_group_id'] . ", `recurring_id` = " . (int)$product_recurring['recurring_id']);
            }
        }

        $this->cache->delete('product');

        return $product_id;
    }

    public function copyProduct($product_id) {
        $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "product p WHERE p.product_id = '" . (int)$product_id . "'");

        if ($query->num_rows) {
            $data = $query->row;

            $data['sku'] = '';
            $data['upc'] = '';
            $data['viewed'] = '0';
            $data['keyword'] = '';
            $data['status'] = '0';


            $data['product_attribute'] = $this->getProductAttributes($product_id);
            $data['product_description'] = $this->getProductDescriptions($product_id);

            foreach ($data['product_description'] as &$product) {
                $product['name'] .= " - (copy)";
            }

            $data['product_discount'] = $this->getProductDiscounts($product_id);
            $data['product_filter'] = $this->getProductFilters($product_id);
            $data['product_image'] = $this->getProductImages($product_id);

            $data['product_option'] = $this->getProductOptions($product_id);
            $data['product_related'] = $this->getProductRelated($product_id);
            $data['product_backway'] = $this->getProductRelatedBackway($product_id);
            $data['product_reward'] = $this->getProductRewards($product_id);
            $data['product_special'] = $this->getProductSpecials($product_id);
            $data['product_category'] = $this->getProductCategories($product_id);
            $data['product_download'] = $this->getProductDownloads($product_id);
            $data['product_layout'] = $this->getProductLayouts($product_id);
            $data['product_store'] = $this->getProductStores($product_id);
            $data['product_recurrings'] = $this->getRecurrings($product_id);

            return $this->addProduct($data);
        }
    }

    public function deleteProduct($product_id) {
        $this->db->query("DELETE FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_filter WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_option_value WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE related_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_reward WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_download WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_layout WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_to_store WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_recurring WHERE product_id = " . (int)$product_id);
        $this->db->query("DELETE FROM " . DB_PREFIX . "review WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "coupon_product WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "content_meta WHERE content_type = 'product' and content_id = '" . (int)$product_id . "'");

        $this->cache->delete('product');
    }

    public function getProduct($product_id) {
        $query = $this->db->query("SELECT DISTINCT p.*"
                                  . ", pd.*"
                                  . ", p2p.product_group_id"
                                  . ", p2p.default_id"
                                  . ", (SELECT keyword FROM " . DB_PREFIX . "url_alias "
                                  . "WHERE query = 'product_id=" . (int)$product_id . "' limit 1) AS keyword FROM " . DB_PREFIX . "product p "
                                  . "LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) "
                                  . "LEFT JOIN " . DB_PREFIX . "product_to_product p2p ON (p.product_id = p2p.product_id) "
                                  . "WHERE p.product_id = '" . (int)$product_id . "' AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
        if($query->num_rows){
            $query->row['product_categories'] = $this->getProductCategories($product_id);
        }
        return $query->row;
    }

    public function getProducts($data = array()) {

        $sql = "SELECT p.*, pd.*, p2p.product_group_id, p2p.default_id FROM " . DB_PREFIX . "product p "
               . "LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) "
               . "LEFT JOIN " . DB_PREFIX . "product_to_product p2p ON (p.product_id = p2p.product_id) "
               . "WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";

        if (!empty($data['filter_name'])) {
            $sql .= " AND ( pd.name LIKE '%" . $this->db->escape(str_replace('&quot;', '"', $data['filter_name'])) . "%'";
            $sql .= " OR p.model LIKE '" . $this->db->escape($data['filter_name']) . "%')";
        }

        if (!empty($data['filter_model'])) {
            $sql .= " AND p.model LIKE '%" . $this->db->escape($data['filter_model']) . "%'";
        }

        if (isset($data['filter_price']) && !is_null($data['filter_price'])) {
            $sql .= " AND p.price LIKE '" . $this->db->escape($data['filter_price']) . "%'";
        }

        if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
            $sql .= " AND p.quantity = '" . (int)$data['filter_quantity'] . "'";
        }

        if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
            $sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
        }

        if (isset($data['filter_added']) && $data['filter_added']) {
            $sql .= " AND p.product_id NOT IN (" . $data['filter_added'] . ")";
        }

        if (isset($data['product_group_id']) && $data['product_group_id']) {
            $sql .= " AND p2p.product_group_id=" . (int)$data['product_group_id'];
        }

        if (isset($data['filter_not_grouped']) && $data['filter_not_grouped']) {
            $sql .= " AND p2p.product_group_id is null";
        }

        if (isset($data['default_product']) && empty($data['filter_name']) && empty($data['filter_model'])) {
            $sql .= " AND (p2p.default_id IS NULL OR p2p.default_id > 0 )";
        }

        if (isset($data['filter_image']) && !is_null($data['filter_image'])) {
            if ($data['filter_image'] == 1) {
                $sql .= " AND (p.image IS NOT NULL AND p.image <> '' AND p.image <> 'no_image.png')";
            } else {
                $sql .= " AND (p.image IS NULL OR p.image = '' OR p.image = 'no_image.png')";
            }
        }

        $sql .= " GROUP BY p.product_id";

        $sort_data = array(
            'pd.name',
            'p.model',
            'p.price',
            'p.quantity',
            'p.status',
            'p.sort_order'
        );

        if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
            $sql .= " ORDER BY " . $data['sort'];
        } else {
            $sql .= " ORDER BY pd.name";
        }

        if (isset($data['order']) && ($data['order'] == 'DESC')) {
            $sql .= " DESC";
        } else {
            $sql .= " ASC";
        }

        if (isset($data['start']) || isset($data['limit'])) {
            if (empty($data['start']) || $data['start'] < 0) {
                $data['start'] = 0;
            }

            if ($data['limit'] < 1) {
                $data['limit'] = 20;
            }

            $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }
        $query = $this->db->query($sql);
        return $query->rows;
    }

    /* Product groups */

    public function getProductGroup($product_id) {
        $sql = "SELECT p.*, (SELECT keyword FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . (int)$product_id . "' limit 1) AS keyword, p2p.product_group_id, p2p.default_id FROM " . DB_PREFIX . "product p";
        $sql .= " LEFT JOIN " . DB_PREFIX . "product_to_product p2p ON (p.product_id = p2p.product_id) ";
        $sql .= " WHERE p.product_id=" . $product_id;
        $query = $this->db->query($sql);

        return $query->row;
    }

    public function getProductsByCategoryId($category_id) {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) 
        LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id)
         WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p2c.category_id = '" . (int)$category_id . "' 
         ORDER BY pd.product_id ASC");

        return $query->rows;
    }

    public function getProductDescriptions($product_id) {
        $product_description_data = array();

        //$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");
        $query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_description_data[$result['language_id']] = array(
                'name'              => $result['name'],
                'description'       => $result['description'],
                'admin_description' => $result['admin_description'],
                'meta_title'        => $result['meta_title'],
                'meta_description'  => $result['meta_description'],
                'meta_keyword'      => $result['meta_keyword'],
                'tag'               => $result['tag']
            );
        }

        return $product_description_data;
    }

    public function getProductCategories($product_id) {
        $product_category_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_category_data[] = $result['category_id'];
        }

        return $product_category_data;
    }

    public function getProductFilters($product_id) {
        $product_filter_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_filter WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_filter_data[] = $result['filter_id'];
        }

        return $product_filter_data;
    }

    public function getProductAttributes($product_id) {
        $product_attribute_data = array();

        $product_attribute_query = $this->db->query("SELECT attribute_id FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "' GROUP BY attribute_id");

        foreach ($product_attribute_query->rows as $product_attribute) {
            $product_attribute_description_data = array();

            $product_attribute_description_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "' AND attribute_id = '" . (int)$product_attribute['attribute_id'] . "'");

            foreach ($product_attribute_description_query->rows as $product_attribute_description) {
                $product_attribute_description_data[$product_attribute_description['language_id']] = array(
                    'text' => $product_attribute_description['text'] );
            }

            $product_attribute_data[] = array(
                'attribute_id'                  => $product_attribute['attribute_id'],
                'product_attribute_description' => $product_attribute_description_data
            );
        }

        return $product_attribute_data;
    }

    public function getProductOptions($product_id) {
        $product_option_data = array();

        $product_option_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "product_option` po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN `" . DB_PREFIX . "option_description` od ON (o.option_id = od.option_id) WHERE po.product_id = '" . (int)$product_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.sort_order, po.product_option_id");

        foreach ($product_option_query->rows as $product_option) {
            $product_option_value_data = array();

            $product_option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) WHERE pov.product_option_id = '" . (int)$product_option['product_option_id'] . "' ORDER BY ov.sort_order, pov.product_option_value_id");

            foreach ($product_option_value_query->rows as $product_option_value) {
                $product_option_value_data[] = array(
                    'product_option_value_id' => $product_option_value['product_option_value_id'],
                    'option_value_id'         => $product_option_value['option_value_id'],
                    'quantity'                => $product_option_value['quantity'],
                    'subtract'                => $product_option_value['subtract'],
                    'price'                   => $product_option_value['price'],
                    'price_prefix'            => $product_option_value['price_prefix'],
                    'points'                  => $product_option_value['points'],
                    'points_prefix'           => $product_option_value['points_prefix'],
                    'weight'                  => $product_option_value['weight'],
                    'weight_prefix'           => $product_option_value['weight_prefix'],
                    'description'           => !empty($product_option_value['description']) ? $product_option_value['description'] : '', //WIP: custom fields! Must be organized!
                    'article'           => $product_option_value['article'], //WIP: custom fields! Must be organized!
                );
            }

            $product_option_data[] = array(
                'product_option_id'    => $product_option['product_option_id'],
                'product_option_value' => $product_option_value_data,
                'option_id'            => $product_option['option_id'],
                'name'                 => $product_option['name'],
                'type'                 => $product_option['type'],
                'value'                => $product_option['value'],
                'required'             => $product_option['required'],
            );
        }

        return $product_option_data;
    }

    public function getProductOptionValue($product_id, $product_option_value_id) {
        $query = $this->db->query("SELECT pov.option_value_id, ovd.name, pov.quantity, pov.subtract, pov.price, pov.price_prefix, pov.points, pov.points_prefix, pov.weight, pov.weight_prefix FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_id = '" . (int)$product_id . "' AND pov.product_option_value_id = '" . (int)$product_option_value_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "'");

        return $query->row;
    }

    public function getProductImages($product_id) {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "' ORDER BY sort_order ASC");
        $product_images = array();
        foreach ($query->rows as $product_image) {

            $product_images[] = array(
                'product_image_id' => $product_image['product_image_id'],
                'product_id'       => $product_image['product_id'],
                'image'            => $product_image['image'],
                'image_url'            => $product_image['image_url'],
                'sort_order'       => $product_image['sort_order'],
                'description'      => $this->getProductImageDescriptions($product_image['product_image_id']),
            );
        }
        return $product_images;
    }

    public function getProductImageDescriptions($product_image_id) {
        $sql = "SELECT * FROM " . DB_PREFIX . "product_image_description WHERE product_image_id = '" . (int)$product_image_id . "'";
        $query = $this->db->query($sql);
        $descriptions = array();
        foreach ($query->rows as $row) {
            $descriptions[$row['language_id']] = $row;
        }
        return $descriptions;
    }

    public function getProductDiscounts($product_id) {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "' ORDER BY quantity, priority, price");

        return $query->rows;
    }

    public function getProductSpecials($product_id) {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' ORDER BY priority, price");

        return $query->rows;
    }

    public function getProductRewards($product_id) {
        $product_reward_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_reward WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_reward_data[$result['customer_group_id']] = array( 'points' => $result['points'] );
        }

        return $product_reward_data;
    }

    public function getProductDownloads($product_id) {
        $product_download_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_download WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_download_data[] = $result['download_id'];
        }

        return $product_download_data;
    }

    public function getProductStores($product_id) {
        $product_store_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_store WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_store_data[] = $result['store_id'];
        }

        return $product_store_data;
    }

    public function getProductLayouts($product_id) {
        $product_layout_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_layout WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_layout_data[$result['store_id']] = $result['layout_id'];
        }

        return $product_layout_data;
    }

    public function getProductRelated($product_id) {
        $product_related_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_related_data[] = $result['related_id'];
        }

        return $product_related_data;
    }

    public function getProductRelatedBackway($product_id) {
        $product_related_data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_related WHERE related_id = '" . (int)$product_id . "'");

        foreach ($query->rows as $result) {
            $product_related_data[] = $result['product_id'];
        }

        return $product_related_data;
    }

    public function getRecurrings($product_id) {
        $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "product_recurring` WHERE product_id = '" . (int)$product_id . "'");

        return $query->rows;
    }

    public function getTotalProducts($data = array()) {
        $sql = "SELECT COUNT(DISTINCT p.product_id) AS total FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)";

        $sql .= " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";

        if (!empty($data['filter_name'])) {
            $sql .= " AND pd.name LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
        }

        if (!empty($data['filter_model'])) {
            $sql .= " AND p.model LIKE '%" . $this->db->escape($data['filter_model']) . "%'";
        }

        if (isset($data['filter_price']) && !is_null($data['filter_price'])) {
            $sql .= " AND p.price LIKE '" . $this->db->escape($data['filter_price']) . "%'";
        }

        if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
            $sql .= " AND p.quantity = '" . (int)$data['filter_quantity'] . "'";
        }

        if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
            $sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
        }

        if (isset($data['filter_image']) && !is_null($data['filter_image'])) {
            if ($data['filter_image'] == 1) {
                $sql .= " AND (p.image IS NOT NULL AND p.image <> '' AND p.image <> 'no_image.png')";
            } else {
                $sql .= " AND (p.image IS NULL OR p.image = '' OR p.image = 'no_image.png')";
            }
        }

        if (empty($data['filter_name']) && empty($data['filter_model'])) {
            $sql .= " AND not exists (select p2p.product_id from `" . DB_PREFIX . "product_to_product` p2p where p2p.product_id = p.product_id and p2p.default_id = 0)";
        }

        $query = $this->db->query($sql);

        return $query->row['total'];
    }

    public function getTotalProductsByTaxClassId($tax_class_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE tax_class_id = '" . (int)$tax_class_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByStockStatusId($stock_status_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE stock_status_id = '" . (int)$stock_status_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByWeightClassId($weight_class_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE weight_class_id = '" . (int)$weight_class_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByLengthClassId($length_class_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE length_class_id = '" . (int)$length_class_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByDownloadId($download_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product_to_download WHERE download_id = '" . (int)$download_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByManufacturerId($manufacturer_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByAttributeId($attribute_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product_attribute WHERE attribute_id = '" . (int)$attribute_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByOptionId($option_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product_option WHERE option_id = '" . (int)$option_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByProfileId($recurring_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product_recurring WHERE recurring_id = '" . (int)$recurring_id . "'");

        return $query->row['total'];
    }

    public function getTotalProductsByLayoutId($layout_id) {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product_to_layout WHERE layout_id = '" . (int)$layout_id . "'");

        return $query->row['total'];
    }

    public function getSeoUrl($product_id) {
        $seo_keywords = array();
        $sql = "SELECT * from " . DB_PREFIX . "url_alias WHERE query='product_id=" . $product_id . "'";
        $query = $this->db->query($sql);
        foreach ($query->rows as $row) {
            $seo_keywords[$row['language_id']] = array(
                'seo_keyword' => $row['keyword']
            );
        }
        return $seo_keywords;
    }

    public function getProductsAutocompleteFS($data) {

        $where = " WHERE pd.language_id = " . (int)$this->config->get('config_language_id') . " " ;
        if($data['filter_name']) {
            $where .= " AND MATCH(pd.name) AGAINST('*" . $this->db->escape($data['filter_name']) . "*'  IN BOOLEAN MODE ) ";
        }
        $sql = " SELECT DISTINCT 
          pd.product_id
          , pd.name
          , pd.product_id as model
          FROM " . DB_PREFIX . "product_description pd 
          $where LIMIT 100";

        $query = $this->db->query($sql);
        return $query->rows;
    }



}