<?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 AskforaquotemodulmyquotedetailModuleFrontController extends ModuleFrontController
{
    public function initContent()
    {
        parent::init();
        parent::initHeader();
        parent::initContent();
        require_once(_PS_MODULE_DIR_ . "askforaquotemodul/libs/mpdf/vendor/autoload.php");
        if (Tools::version_compare(_PS_VERSION_, '1.7', '>=')) {
            $this->ps_cipherTool = new PhpEncryption(_NEW_COOKIE_KEY_);
        } else {
            $this->ps_cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
        }
        

        $id_quote_cus = Tools::getValue('id_quote');
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $customer = $this->context->customer->id;
        $sql_quote_dbboo = 'SELECT * FROM ' . _DB_PREFIX_ . 'product_quote_dbboo WHERE';
        $sql_quote_dbboo .= ' id_quote like "' . (int) $id_quote_cus . '"';
        $tb_quote_dbboo = $db->ExecuteS($sql_quote_dbboo, true, false);
        
        // redirect to My account if no quote
        $link = new Link();
        $link_to_home = $link->getPageLink('index');
        if (empty($tb_quote_dbboo)) {
            Tools::redirectAdmin($link_to_home);
        } else {
            $id_customer_tmp = (int) $tb_quote_dbboo[0]['id_customer'];
            $is_guest = false;
            $c = new Customer($id_customer_tmp);
            if ($id_customer_tmp == 0 || $c->isGuest()) {
                $is_guest = true;
            }
            if (!$is_guest && $customer != $id_customer_tmp) {
                $link_to_account = $link->getPageLink('my-account');
                Tools::redirectAdmin($link_to_account);
            }
        }
        $soucrce_checkk = $tb_quote_dbboo[0]['source_check'];
        $soucrce_check = Tools::getValue('soucrce');
        if ($soucrce_checkk == $soucrce_check && !empty($tb_quote_dbboo)) {
            $option_price_total = Configuration::get('Option_price_total');
            $shop_name = Configuration::get('PS_SHOP_NAME');
            $add_1 = Configuration::get('PS_SHOP_ADDR1');
            $add_2 = Configuration::get('PS_SHOP_ADDR2');
            $city_shop = Configuration::get('PS_SHOP_CITY');
            $state_shop =Configuration::get('PS_SHOP_STATE');
            $zip_shop = Configuration::get('PS_SHOP_CODE');
            $country_shop = Configuration::get('PS_SHOP_COUNTRY');
            $phone_shop = Configuration::get('PS_SHOP_PHONE');
            $option_order_date = Configuration::get('Option_order_date');
            $language_site = $this->context->cookie->id_lang;
            $date_now_h_i_s = date('Y-m-d H:i:s');
            
            $id_quote_format_pdf = $this->module->getIDQuoteformatted($id_quote_cus);
            $sign_currency_quote = (int)$tb_quote_dbboo[0]['id_currency'];
            $obj_currency = new Currency($sign_currency_quote);
            $tb_quote_dbboo[0]['sign'] = $obj_currency->sign;
            $check_idcustomer = Count($tb_quote_dbboo);
            $export = Tools::getValue('export');

            $link = new Link();
            $link_myaccount_seo = $link->getPageLink('my-account', true, null);
            $link_myquote_seo = $link->getModuleLink('askforaquotemodul', 'myquotecustomer');
            if ($check_idcustomer == 0) {
                Tools::redirectAdmin($link_myaccount_seo);
            } else {
                $total_price_quote = (float) $tb_quote_dbboo[0]['total_pri'];
                $tax_cost = (float) $tb_quote_dbboo[0]['tax_cost'];
                $shipping_cost = (float) $tb_quote_dbboo[0]['shipping_cost'];
                $id_cr_quote = (int) $tb_quote_dbboo[0]['id_currency'];
                $tb_quote_dbboo[0]['price_full'] = Tools::displayPrice($total_price_quote, $id_cr_quote);
                $tb_quote_dbboo[0]['shipping_cost'] = Tools::displayPrice($shipping_cost, $id_cr_quote);
                $tb_quote_dbboo[0]['tax_cost'] = Tools::displayPrice($tax_cost, $id_cr_quote);
                $ud_mess = 'UPDATE ' . _DB_PREFIX_ . 'message_dbboo SET status = "1" ';
                $ud_mess .= 'where id_quote like "' . (int) $id_quote_cus . '" and type = "1"';
                $db->query($ud_mess);

                $ud_pro_mess_adm = 'UPDATE ' . _DB_PREFIX_ . 'cus_message_dbboo SET so_luong_mes = "0"';
                $ud_pro_mess_adm .= 'where id_quote like "' . (int) $id_quote_cus . '"';
                $db->query($ud_pro_mess_adm);

                $count_sp = 'SELECT COUNT(*) FROM ' . _DB_PREFIX_ . 'product_quote_detail where id_quote like "';
                $count_sp .= (int) $id_quote_cus . '"';
                $this->context->smarty->assign("link_img_pdf", __PS_BASE_URI__);
                $count_product = $db->Executes($count_sp, true, false);
                $product_Qty_view = $count_product[0]['COUNT(*)'];
                $this->context->smarty->assign("count", $product_Qty_view);
                
                if ($product_Qty_view > 0) {
                    $sql_quote_detail = 'SELECT * FROM ' . _DB_PREFIX_ . 'product_quote_detail where id_quote like "';
                    $sql_quote_detail .= (int) $id_quote_cus . '"';
                    $sql_quote_detail .= 'ORDER BY position ASC, id_product ASC, id_combination ASC';
                    $product_quote = $db->ExecuteS($sql_quote_detail, true, false);
                    $linkimages = new Link();
                    foreach ($product_quote as $key_link => $value_link) {
                        $id_currency_quote = (int)$value_link['id_currency'];
                        $obj_currency = new Currency($id_currency_quote);
                        $id_pro_quote = (int) $value_link['id_product'];
                        $link_product = $linkimages->getProductLink($id_pro_quote);
                        $product_quote[$key_link]['link_product'] = $link_product;
                        $product_priii = $product_quote[$key_link]['product_pri'];
                        $total_priii = $product_quote[$key_link]['total_pri'];
                        $product_price = Tools::displayPrice($product_priii, $id_currency_quote);
                        $total_pr_price = Tools::displayPrice($total_priii, $id_currency_quote);
                        $product_quote[$key_link]['product_pri'] = $product_price;
                        $product_quote[$key_link]['total_pri'] = $total_pr_price;
                        $product_quote[$key_link]['sign'] = $obj_currency->sign;
                        $product_quote[$key_link]['cache_is_pack'] = Pack::isPack((int)$id_pro_quote);
                        // since 1.0.39+
                        $price_incl_tax = $value_link['product_pri_incl_tax'];
                        $total_price_incl_tax = $value_link['total_pri_incl_tax'];
                        $price_incl_tax = Tools::displayPrice($price_incl_tax, $id_currency_quote);
                        $total_price_incl_tax = Tools::displayPrice($total_price_incl_tax, $id_currency_quote);
                        $product_quote[$key_link]['price_incl_tax'] = $price_incl_tax;
                        $product_quote[$key_link]['total_price_incl_tax'] = $total_price_incl_tax;
                    }
                    $this->context->smarty->assign("tb_detail", $product_quote);
                }
                
                $link_myquotedetail_seo = $link->getModuleLink('askforaquotemodul', 'myquotedetail', array(
                    'id_quote' => $id_quote_cus,
                    'export' => 1,
                   ));
                $dp_imess = 'Select * from '. _DB_PREFIX_ .'message_dbboo where id_quote';
                $dp_imess .= ' like "'. (int) $id_quote_cus .'"';
                $detail_mess = $db->ExecuteS($dp_imess, true, false);
                if (!empty($detail_mess)) {
                    $id_lang_q = (int) $tb_quote_dbboo[0]['id_lang'];
                    foreach ($detail_mess as &$mess) {
                        $mess['date_send_format'] = $this->displayDate($mess['date_send'], $id_lang_q);
                        $mess['date_send_format_2'] = Tools::displayDate($mess['date_send'], null, true);
                    }
                }
                $this->context->smarty->assign('shop_name', $shop_name);
                $this->context->smarty->assign("add_1", $add_1);
                $this->context->smarty->assign('add_2', $add_2);
                $this->context->smarty->assign("city_shop", $city_shop);
                $this->context->smarty->assign("state_shop", $state_shop);
                $this->context->smarty->assign("zip_shop", $zip_shop);
                $this->context->smarty->assign("country_shop", $country_shop);
                $this->context->smarty->assign("phone_shop", $phone_shop);
                $this->context->smarty->assign("option_order_date", $option_order_date);
                $this->context->smarty->assign("id_quote_format_pdf", $id_quote_format_pdf);
                $this->context->smarty->assign('tb_quote_dbboo', $tb_quote_dbboo);
                $this->context->smarty->assign('option_price_total', $option_price_total);
                $this->context->smarty->assign("detail_mess", $detail_mess);
                $this->context->smarty->assign("link_myquotedetail_seo", $link_myquotedetail_seo);
                $this->context->smarty->assign("link_myquote_seo", $link_myquote_seo);
                if (Tools::isSubmit('file_pdf_name')) {
                    $id_lang_quote = $tb_quote_dbboo[0]['id_lang'];
                    $arr_language = Language::getLanguages(false);
                    $date_format_lang = $this->displayDate($date_now_h_i_s, $id_lang_quote);
                    $quote_date = $this->displayDate($tb_quote_dbboo[0]['date_quote'], $id_lang_quote);
                    $this->context->smarty->assign("date_format_lang", $date_format_lang);
                    $zero = Tools::displayPrice('0', $id_cr_quote);
                    $this->context->smarty->assign("zero", $zero);
                    $link_subtotal = _PS_MODULE_DIR_ . 'askforaquotemodul/views/templates/front/subtotalfrontpdf.tpl';
                    $link_tbproduct = _PS_MODULE_DIR_ . 'askforaquotemodul/views/templates/front/tbproductfrontpdf.tpl';
                    $messagespdff = _PS_MODULE_DIR_ . 'askforaquotemodul/views/templates/admin/messagespdf.tpl';
                    $subtotal_quote = $this->context->smarty->fetch($link_subtotal);
                    $tbproduct_quote = $this->context->smarty->fetch($link_tbproduct);
                    $messagespdf = $this->context->smarty->fetch($messagespdff);
                    foreach ($arr_language as $key => $value_lang) {
                        $value_lang;
                        $array_id_language = $arr_language[$key]['id_lang'];
                        if ($array_id_language == $language_site) {
                            $array_language_iso_code = $arr_language[$key]['iso_code'];
                            $content_pdf_lang = Configuration::get('label_pdf_'.$array_language_iso_code);
                            $pdf_adm = $this->ps_cipherTool->decrypt($content_pdf_lang);
                            $pdf_adm = str_replace("[shop_name]", $shop_name, $pdf_adm);
                            $pdf_adm = str_replace("[quote_ID]", $id_quote_format_pdf, $pdf_adm);
                            $pdf_adm = str_replace("[quote_id]", $id_quote_format_pdf, $pdf_adm);
                            $pdf_adm = str_replace("[quote_date]", $quote_date, $pdf_adm);
                            $pdf_adm = str_replace("[shop_add1]", $add_1, $pdf_adm);
                            $pdf_adm = str_replace("[shop_add2]", $add_2, $pdf_adm);
                            $pdf_adm = str_replace("[shop_city]", $city_shop, $pdf_adm);
                            $pdf_adm = str_replace("[shop_state]", $state_shop, $pdf_adm);
                            $pdf_adm = str_replace("[shop_zip]", $zip_shop, $pdf_adm);
                            $pdf_adm = str_replace("[shop_country]", $country_shop, $pdf_adm);
                            $pdf_adm = str_replace("[shop_phone]", $phone_shop, $pdf_adm);
                            $pdf_adm = str_replace("[first_name]", $tb_quote_dbboo[0]['first_name'], $pdf_adm);
                            $pdf_adm = str_replace("[last_name]", $tb_quote_dbboo[0]['last_name'], $pdf_adm);
                            $pdf_adm = str_replace("[company_name]", $tb_quote_dbboo[0]['company_name'], $pdf_adm);
                            $ca = $tb_quote_dbboo[0]['company_address'];
                            $pdf_adm = str_replace("[company_address]", $ca, $pdf_adm);
                            $pdf_adm = str_replace("[phone]", $tb_quote_dbboo[0]['phone'], $pdf_adm);
                            $pdf_adm = str_replace("[email]", $tb_quote_dbboo[0]['email'], $pdf_adm);
                            $pdf_adm = str_replace("[product_table]", $tbproduct_quote, $pdf_adm);
                            $pdf_adm = str_replace("[subtotal]", $subtotal_quote, $pdf_adm);
                            $pdf_adm = str_replace("[messages]", $messagespdf, $pdf_adm);
                            $pdf_adm = str_replace("[order_date]", $option_order_date, $pdf_adm);
                            $pdf_adm = str_replace("[gen_pdf_date]", $date_format_lang, $pdf_adm);
                            $pdf_adm = $this->module->stripBreakLinePDF($pdf_adm);

                            $config = array();
                            $mpdf = new \Mpdf\Mpdf($config);
                            $pdf_quote = $pdf_adm;
                            $mpdf->AddPage();
                            $mpdf->WriteHTML($pdf_quote);
                            $file = $this->module->getPDFFileName($id_quote_cus);
                            $mpdf->Output($file, 'D');
                        }
                    }
                }
                if ($export == 1) {
                    $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
                    $list_product_quote = 'Select id_currency,link_img,product_name,reference,combination,';
                    $list_product_quote .= 'product_pri,product_qty';
                    $list_product_quote.= ',total_pri from ' . _DB_PREFIX_ . 'product_quote_detail';
                    $list_product_quote .= ' where id_quote like "'. (int) $id_quote_cus . '"';
                    $list_product_quote .= 'ORDER BY position ASC, id_product ASC, id_combination ASC';
                    $list_product = $db->ExecuteS($list_product_quote, true, false);
                    foreach ($list_product as $key_l => $value_list) {
                        $value_list;
                        $id_currency_quote_ex = (int)$list_product[$key_l]['id_currency'];
                        $obj_currency = new Currency($id_currency_quote_ex);
                        $product_priiii = $list_product[$key_l]['product_pri'];
                        $total_priiiii = $list_product[$key_l]['total_pri'];
                        $product_price = Tools::displayPrice($product_priiii, $id_currency_quote_ex);
                        $total_pr_price = Tools::displayPrice($total_priiiii, $id_currency_quote_ex);
                        $list_product[$key_l]['product_pri'] = $product_price;
                        $list_product[$key_l]['total_pri'] = $total_pr_price;
                        unset($list_product[$key_l]['id_currency']);
                    }
                    $columns_product_quote_detail = 'select COLUMN_NAME from Information_schema.columns where ';
                    $columns_product_quote_detail .= 'TABLE_NAME like "' . _DB_PREFIX_ . 'product_quote_detail"';
                    $colums_name = $db->ExecuteS($columns_product_quote_detail, true, false);
                    $list_colum = array();
                    $total = array();
                    $list_product_key = array_keys($list_product[0]);
                    for ($i = 1; $i < count($list_product_key); $i++) {
                        $total[$i] = '';
                    }
                    $total_price_quote_dp = Tools::displayPrice($total_price_quote, $id_cr_quote);
                    $total['total_price_quote'] = $total_price_quote_dp;
                    $list_product[] = $total;
                    foreach ($colums_name as $key_col => $value_col) {
                        $value_col;
                        foreach ($list_product_key as $key => $value) {
                            $value;
                            if ($colums_name[$key_col]['COLUMN_NAME'] == $list_product_key[$key]) {
                                $list_colum[] = $colums_name[$key_col]['COLUMN_NAME'];
                            }
                        }
                    }
                    $list_colum = str_replace("link_img", "Images", $list_colum);
                    $list_colum = str_replace("product_name", "Product Name", $list_colum);
                    $list_colum = str_replace("reference", "Product Reference", $list_colum);
                    $list_colum = str_replace("combination", "Combination", $list_colum);
                    $list_colum = str_replace("product_pri", "Price", $list_colum);
                    $list_colum = str_replace("product_qty", "Quantity", $list_colum);
                    $list_colum = str_replace("total_pri", "Total Price", $list_colum);
                    
                    header('Content-type: text/csv');
                    header('Content-Disposition: attachment;filename="ExportProduct ' . date('Y-m-d H:i') . '.csv"');
                    header('Pragma: no-cache');
                    header('Expires: 0');
                    $file = fopen('php://output', 'w');
                    fputcsv($file, $list_colum);
                    foreach ($list_product as $row) {
                        fputcsv($file, $row);
                    }
                    exit();
                }
                $this->context->controller->addJS(_PS_MODULE_DIR_ . 'askforaquotemodul/views/js/showquotedetail.js');
                $this->context->smarty->assign("logged", $this->context->customer->logged);
                if (Tools::version_compare(_PS_VERSION_, '1.7', '>=')) { // for PrestaShop 1.7+
                    $this->context->controller->addCSS(_PS_MODULE_DIR_ . 'askforaquotemodul/views/css/style17.css');
                    $tpl_1 = _PS_MODULE_DIR_.'askforaquotemodul/views/templates/front/quotedetailcustomer.tpl';
                    $html = $this->context->smarty->fetch($tpl_1);
                    $this->context->smarty->assign("html", $html);
                    $this->setTemplate('module:askforaquotemodul/views/templates/front/content.tpl');
                } else {
                    $this->context->controller->addCSS(_PS_MODULE_DIR_ . 'askforaquotemodul/views/css/style_new.css');
                    $this->setTemplate('quotedetailcustomer.tpl');
                }
            }
        } else {
            $link = new Link();
            $link_to_account = $link->getPageLink('my-account');
            Tools::redirectAdmin($link_to_account);
        }
    }
    public function displayDate($date, $id_lang = null)
    {
        if (!$date || !($time = strtotime($date))) {
            return $date;
        }
        if ($date == '0000-00-00 00:00:00' || $date == '0000-00-00') {
            return '';
        }
        if (!Validate::isDate($date)) {
            return $date;
        }
        if ($id_lang == null) {
            $id_lang = $this->order->id_lang;
        }
        $context = Context::getContext();
        $lang = empty($id_lang) ? $context->language : new Language($id_lang);
        $date_format = $lang->date_format_lite;
        return date($date_format, $time);
    }
}
