<?php
/**
* 2007-2020 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@buy-addons.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    Buy-Addons <contact@buy-addons.com>
*  @copyright 2007-2020 PrestaShop SA
*  @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
* @since 1.6
*/

class AskforaquotemoduladdproductnewquoteModuleFrontController extends ModuleFrontController
{
    public function run()
    {
        $quote_module_token = Tools::getValue('quote_token');
        if ($quote_module_token != md5(sha1(_COOKIE_KEY_.'askforaquotemodul'))) {
            die;
        } else {
            parent::init();
            parent::initContent();
            $info_product = array();
            $id_tax = array();
            $rate_tax = array();
            $rate_of_tax = array();
            $quantityy = array();
            $attr_couple = array();
            $quantity = array();
            
            $id_shop = Tools::getValue('jsshopid');
            $baan = Tools::getValue('baan');
            $td_id_quote = (int) Tools::getValue('td_id_quote');
            $this->context->shop->id = $id_shop;
            // update currency for this Quote
            $currency_default = $this->module->findQuoteCurrencyById($td_id_quote);
            $context = Context::getContext();
            $context->currency = $currency_default;

            $sign_def = $currency_default->sign;
            
            $td_pri_pro_havetax_max_fixed = Tools::getValue('td_pri_pro_havetax_max_fixed');
            $td_pri_pro_havetax_max_fixed = str_replace($sign_def, "", $td_pri_pro_havetax_max_fixed);
            $td_pri_pro_havetax_min_fixed = Tools::getValue('td_pri_pro_havetax_min_fixed');
            $td_pri_pro_havetax_min_fixed = str_replace($sign_def, "", $td_pri_pro_havetax_min_fixed);
            $id_product = Tools::getValue('id_product_e');
            $id_attrbute_pro = (int) Tools::getValue('combi_product_e');
            $qty_product = Tools::getValue('qty_product_e');
            if (empty($qty_product) or $qty_product == "0") {
                $qty_product = "1";
            }
            $total_price_old = Tools::getValue('total_priceee');
            $qty_all_pro = Tools::getValue('qty_all_pro');
            $id_customer = Tools::getValue('id_customer');
            
            $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
            $id_lang = $this->context->language->id;
            $id_currency = $this->context->currency->id;
            $product = new Product($id_product, true, $id_lang);
            $link_rew = $product->link_rewrite;
            $linkimages = new Link();
            if (empty($id_attrbute_pro)) {
                $id_image_attr = 'Select id_image from '._DB_PREFIX_.'image';
                $id_image_attr .= ' where id_product = "'.$id_product.'"';
                $id_image_attribute = $db->ExecuteS($id_image_attr, true, false);
            } else {
                $id_image_attr = 'Select id_image from '._DB_PREFIX_.'product_attribute_image';
                $id_image_attr .= ' where id_product_attribute like "'.$id_attrbute_pro.'"';
                $id_image_attribute = $db->ExecuteS($id_image_attr, true, false);
                if (empty($id_image_attribute)) {
                    $id_image_attr = 'Select id_image from '._DB_PREFIX_.'image';
                    $id_image_attr .= ' where id_product like "'.$id_product.'"';
                    $id_image_attribute = $db->ExecuteS($id_image_attr, true, false);
                }
            }
            if (Tools::version_compare(_PS_VERSION_, '1.7', '>=')) {
                $type_img = ImageType::getFormattedName('cart');
            } else {
                $type_img = ImageType::getFormatedName('cart');
            }
            if (!empty($id_image_attribute)) {
                $link_img = $linkimages->getImageLink($link_rew, $id_image_attribute[0]['id_image'], $type_img);
            } else {
                $link_img = '' . Tools::getServerName() . '' . __PS_BASE_URI__ . '';
                $link_img .= 'modules/askforaquotemodul/views/img/noimg.png';
            }
            $link_images = Tools::getShopProtocol() . $link_img;
            $sql_sku = 'Select reference from '._DB_PREFIX_.'product';
            $sql_sku .= ' where id_product = "'.$id_product.'"';
            $sku_product = $db->getRow($sql_sku, true, false);
            $sku_product['reference'] = Tools::safeOutput($sku_product['reference']);
            $sql_name = 'Select name from '._DB_PREFIX_.'product_lang';
            $sql_name .= ' where id_product = "'.$id_product.'"';
            $name_product = $db->getRow($sql_name, true, false);
            $name_product['name'] = Tools::safeOutput($name_product['name']);
            if (empty($id_attrbute_pro)) {
                $pri_pro = Product::getPriceStatic((int) $id_product, false, null, 6, null, false, true, $qty_product);
                $total_price = $pri_pro * $qty_product; // no tax
                $total_price_new = $total_price + $total_price_old; // no tax
                $quantity = StockAvailable::getQuantityAvailableByProduct($id_product, $id_attrbute_pro, $id_shop);
                $combination = '';
            } else {
                $product_attr = $product->getAttributeCombinationsById($id_attrbute_pro, $id_lang);
                if (!empty($product_attr[0]['reference'])) {
                    $sku_product['reference'] = Tools::safeOutput($product_attr[0]['reference']);
                }
                $id_a = (int) $id_attrbute_pro;
                $q = (int) $qty_product;
                $pri_pro = Product::getPriceStatic((int) $id_product, false, $id_a, 4, null, false, true, $q);
                $total_price = $pri_pro * $qty_product;
                $total_price_new = $total_price + $total_price_old;
                $attr_couple_array = array();
                foreach ($product_attr as $value) {
                    $quantity = $value['quantity'];
                    $group_name_attr = $value['group_name'];
                    $attribute_name_attr = $value['attribute_name'];
                    $attr_couple = $group_name_attr . ": " . $attribute_name_attr;
                    $attr_couple_array[] = $attr_couple;
                }
                $combination = implode(', ', $attr_couple_array);
            }
            $sign_def = $currency_default->sign;
            $adminControllers='index.php?controller=AdminProducts';
            $batokenan='&token='.Tools::getValue('batokencus');
            $url_id_product='&id_product='.$id_product.'&updateproduct';
            $link_pro = $adminControllers.$batokenan.$url_id_product;
            ////////////////////////////////////////// about of product tax(min and max)
            $sql = 'select id_tax from ' . _DB_PREFIX_ . 'product AS a INNER JOIN ' . _DB_PREFIX_ . 'tax_rule AS b ON ';
            $sql .= 'a.id_tax_rules_group = b.id_tax_rules_group WHERE id_product = ' . $id_product . '';
            $name_tax_pro = $db->executeS($sql);
            foreach ($name_tax_pro as $value) {
                $id_tax[] = $value['id_tax'];
            }
            $id_tax = implode(",", $id_tax);
            if (empty($id_tax)) {
                $id_tax = '\'\'';
            }
            $sql_id_tax = 'SELECT rate FROM ' . _DB_PREFIX_ . 'tax WHERE id_tax in (' . pSQL($id_tax) . ')';
            $sql_id_tax .= ' and active = "1"';
            $rate = $db->executeS($sql_id_tax);
            foreach ($rate as $value1) {
                $rate_tax[] = $value1['rate'];
            }
            sort($rate_tax);
            $rate_length = count($rate_tax);
            $rate_tax_min = 0;
            $rate_tax_max = 0;
            if ($rate_length <= '1') {
                if ($rate_length == 0) {
                    $rate_tax[] = 0;
                }
                $pri_pro_havetax_min = '0.00' + $td_pri_pro_havetax_min_fixed;
                $td_pri_pro_havetax_min_fixed = $pri_pro_havetax_min;
                $pri_pro_havetax_max = $rate_tax[0] / '100' * $pri_pro + $td_pri_pro_havetax_max_fixed;
                $td_pri_pro_havetax_max_fixed = $pri_pro_havetax_max;
                $rate_tax_max = $rate_tax[0];
            } else {
                for ($x = 0; $x < $rate_length; $x++) {
                    $rate_of_tax[] = $rate_tax[$x];
                }
                $rate_tax_min = array_shift($rate_of_tax);
                $pri_pro_havetax_min = $rate_tax_min / '100' * $pri_pro;
                $pri_pro_havetax_min = $pri_pro_havetax_min  + $td_pri_pro_havetax_min_fixed;
                $rate_tax_max = array_pop($rate_of_tax);
                $pri_pro_havetax_max = $rate_tax_max / '100' * $pri_pro;
                $pri_pro_havetax_max = $pri_pro_havetax_max + $td_pri_pro_havetax_max_fixed;
                $td_pri_pro_havetax_max_fixed = $pri_pro_havetax_max;
                $td_pri_pro_havetax_min_fixed = $pri_pro_havetax_min;
                if ($rate_tax_min == $rate_tax_max) {
                    $pri_pro_havetax_min = '0.00' + $td_pri_pro_havetax_min_fixed;
                }
            }
            $td_pri_pro_havetax_min_fixed = Tools::displayPrice($td_pri_pro_havetax_min_fixed, $id_currency);
            $td_pri_pro_havetax_max_fixed = Tools::displayPrice($td_pri_pro_havetax_max_fixed, $id_currency);
            $check_pack = 'SELECT cache_is_pack FROM ' . _DB_PREFIX_ . 'product ';
            $check_pack .= ' WHERE id_product = ' . (int) $id_product;
            $checking = $db->executeS($check_pack);
            if ($checking[0]['cache_is_pack'] == 1) {
                $sql_select_pro_pack = 'SELECT * FROM ' . _DB_PREFIX_ . 'pack ';
                $sql_select_pro_pack .= ' WHERE id_product_pack = '.(int) $id_product;
                $pro_pack = $db->executeS($sql_select_pro_pack);
                foreach ($pro_pack as $key => $value) {
                    $qty = $value['quantity'];
                    $combinationn = '';
                    $quantityy[] = $value['quantity'];
                    $attr_couple = array();
                    $product = new Product($value['id_product_item'], false, $id_lang);
                    $id_product_attribute_item = $value['id_product_attribute_item'];
                    $product_attr = $product->getAttributeCombinationsById($id_product_attribute_item, $id_lang);
                    foreach ($product_attr as $value) {
                        $group_name_attr = $value['group_name'];
                        $attribute_name_attr = $value['attribute_name'];
                        $attr_couple[] = $group_name_attr . ": " . $attribute_name_attr;
                    }
                    $combinationn = implode(',', $attr_couple);
                    $combination[$key] = $product->name.': '.$combinationn. $this->module->l(' x ').$qty;
                    if (!empty($combinationn)) {
                        $combination[$key] = $product->name.': '.$combinationn. $this->module->l(' x ').$qty;
                    } else {
                        $combination[$key] = $product->name. $this->module->l(' x ').$qty;
                    }
                }
                $combination = implode("\n", $combination);
                $info_product['pro_pack'] = $pro_pack;
                $info_product['quantityy'] = $quantityy;
            }
            $combination = Tools::safeOutput($combination);
            if ($baan == 1) {
                $this->addProduct($combination, $pri_pro, $id_attrbute_pro);
            }

            $info_product['cache_is_pack'] = $checking[0]['cache_is_pack'];
            $info_product['td_pri_pro_havetax_max_fixed'] = $td_pri_pro_havetax_max_fixed;
            $info_product['td_pri_pro_havetax_min_fixed'] = $td_pri_pro_havetax_min_fixed;
            $info_product['pri_pro_havetax_min'] = $pri_pro_havetax_min;
            $info_product['pri_pro_havetax_max'] = $pri_pro_havetax_max;
            $info_product['rate_tax_min'] = $rate_tax_min;
            $info_product['rate_tax_max'] = $rate_tax_max;
            $info_product['total_price_old'] = $total_price_old;
            $info_product['total_price_new'] = $total_price_new;
            $info_product['id_product'] = (int) $id_product;
            $info_product['id_attrbute_pro'] = $id_attrbute_pro;
            $info_product['qty_product'] = $qty_product;
            $info_product['link_images'] = Tools::safeOutput($link_images);
            $info_product['sku_product'] = $sku_product;
            $info_product['name_product'] = $name_product;
            $info_product['total_price'] = $total_price;
            $info_product['pri_pro'] = $pri_pro;
            $info_product['combination'] = $combination;
            $info_product['sign_def'] = Tools::safeOutput($sign_def);
            $info_product['link_pro'] = Tools::safeOutput($link_pro);
            $info_product['qty_all_pro'] = $qty_all_pro;
            $info_product['id_customer'] = $id_customer;
            $info_product['quantity_max'] = $quantity;
            $info_product['id_quote'] = $td_id_quote;
            echo Tools::jsonEncode($info_product);
        }
    }
    public function addProduct($combination, $pri_pro, $id_attrbute_pro)
    {
        $combination = Tools::htmlentitiesDecodeUTF8($combination);
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $id_product = (int) Tools::getValue('id_product_e');
        $id_lang = (int) $this->context->language->id;
        $id_currency = (int) $this->context->currency->id;
        $product = new Product($id_product, false, $id_lang);
        $td_id_quote = (int) Tools::getValue('td_id_quote');
        $qty_product = (int) Tools::getValue('qty_product_e');
        if (empty($qty_product) or $qty_product == "0") {
            $qty_product = "1";
        }
        $sql_sku = 'SELECT reference FROM '._DB_PREFIX_.'product';
        $sql_sku .= ' WHERE id_product = "'.$id_product.'"';
        $sku_product = $db->ExecuteS($sql_sku, true, false);
        $reference = $sku_product[0]['reference'];
        if (!empty($id_attrbute_pro)) {
            $product_attr = $product->getAttributeCombinationsById($id_attrbute_pro, $id_lang);
            if (!empty($product_attr[0]['reference'])) {
                $reference = Tools::safeOutput($product_attr[0]['reference']);
            }
        }
        $image = new Image();
        $dp_image = $image->getImages($id_lang, $id_product);
        $link_rew = $product->link_rewrite;
        $linkimages = new Link();
        if ($dp_image == null) {
            $link_img = '' . Tools::getServerName() . '' . __PS_BASE_URI__ . '';
            $link_img .= 'modules/askforaquotemodul/views/img/noimg.png';
        } else {
            $id_img = Product::getCover($id_product);
            $id_img = $id_img['id_image'];
            if (!isset($id_img)) {
                $id_img = 0;
            }
            $imagetype =  '';
            if (Tools::version_compare(_PS_VERSION_, '1.7', '>=')) { // for PrestaShop 1.7+
                $imagetype = ImageType::getFormattedName('cart');
            } else {
                $imagetype = ImageType::getFormatedName('cart');
            }
            $link_img = $linkimages->getImageLink($link_rew, $id_img, $imagetype);
        }
        $link_img_full = Tools::getShopProtocol() . $link_img;
        
        $sql_check = 'SELECT id_product,id_combination,product_qty FROM ' . _DB_PREFIX_ . 'product_quote_detail';
        $sql_check .= ' WHERE id_quote = '.(int) $td_id_quote;
        $check_pro = $db->executeS($sql_check);
        $a = 0;
        foreach ($check_pro as $value) {
            if ($value['id_product'] == $id_product && (int)$value['id_combination'] == $id_attrbute_pro) {
                $a = 1;
                $sql = 'UPDATE ' . _DB_PREFIX_ . 'product_quote_detail';
                $sql .= ' set product_qty = product_qty + "' . (int) $qty_product . '", ';
                $sql .= 'total_pri=product_qty*product_pri where id_quote = "'. (int) $td_id_quote . '" and ';
                $sql .= 'id_product = "'.(int) $id_product . '" and id_combination = "' . (int) $id_attrbute_pro . '"';
                $db->query($sql);
                break;
            } else {
                $a = 0;
            }
        }
        $total_pri = $pri_pro * $qty_product;
        if ($a == 0) {
            $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'product_quote_detail';
            $sql .= '(id_quote,id_currency,id_lang,link_img,id_product,product_name,reference,';
            $sql .= 'id_combination,combination,product_pri,product_qty,total_pri) values("';
            $sql .= (int) $td_id_quote . '","' . (int) $id_currency . '",';
            $sql .= '"' . (int) $id_lang . '","' . pSQL($link_img_full) . '","';
            $sql .= (int) $id_product . '","' . pSQL($product->name) . '","';
            $sql .= pSQL($reference) . '",';
            $sql .= '"' . (int) $id_attrbute_pro . '","' . pSQL($combination) . '","' . (float)$pri_pro . '",';
            $sql .= '"' . (int) $qty_product . '","' . (float)$total_pri . '")';
            $db->query($sql);
        }
        $select_total_pri = 'SELECT total_pri FROM ' . _DB_PREFIX_ . 'product_quote_dbboo where id_quote like "';
        $select_total_pri .= (int) $td_id_quote . '"';
        $total_pri_old = $db->ExecuteS($select_total_pri, true, false);
        $t = $total_pri + $total_pri_old[0]['total_pri'];
        $update_total_pri = 'UPDATE ' . _DB_PREFIX_ . 'product_quote_dbboo SET total_pri="' . (float)$t . '"';
        $update_total_pri .= 'where id_quote like "' . (int) $td_id_quote . '"';
        $db->query($update_total_pri);
        return true;
    }
}
