<?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 AskforaquotemodulcreatecartModuleFrontController extends ModuleFrontController
{

    public function run()
    {
        parent::init();
        parent::initHeader();
        parent::initContent();
        $quote_module_token = Tools::getValue('quote_token');
        if ($quote_module_token != md5(sha1(_COOKIE_KEY_.'askforaquotemodul'))) {
            die;
        }
        $obsummary = array();
        $result = array();
        $result['has_error'] = 0;
        $td_id_quote = (int) Tools::getValue('td_id_quote');
        $quote_ob = $this->module->getCustomerQuote($td_id_quote);
        $this->module->setCurrencyQuote($td_id_quote);
        $currency = $this->module->findQuoteCurrencyById($td_id_quote);
        $id_currency = $currency->id;
        
        $currency_default = new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'));
        /////////////////
        $row_product = Tools::getValue('row_product');
        
        $td_id_customer = (int) Tools::getValue('td_id_customer');
        $this->context->smarty->assign('td_id_customer', $td_id_customer);
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $jslanguageid = (int) Tools::getValue('jslanguageid');
        $id_lang = empty($quote_ob['id_lang']) ? $jslanguageid : $quote_ob['id_lang'];
        // kiem tra xem language nay co active ko
        $l_IDs = Language::getLanguages(true, false, true);
        if (!in_array($id_lang, $l_IDs)) {
            $id_lang = (int) $l_IDs[0];
        }
        $id_shop = Tools::getValue('jsshopid');
        $this->context->shop->id = $id_shop;
        $id_guest_new = 0;
        if (empty($td_id_customer) && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
            // website ko cho Guest checkout
            $result['has_error'] = 1;
            $result['errors'][] = $this->module->l('Your website does not allow to checkout as a Guest.');
            echo Tools::jsonEncode($result);
            return false;
        }
        if (empty($td_id_customer)) {
            // checkout for Guest
            $guest = new Guest();
            $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
            $acceptLanguage = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
            $guest->accept_language = $this->getLanguage($acceptLanguage);
            $guest->id_operating_system = $this->getOs($userAgent);
            $guest->id_web_browser = $this->getBrowser($userAgent);
            $guest->id_operating_system = 0;
            $guest->id_customer = 0;
            $guest->javascript = 0;
            $guest->screen_resolution_x = 0;
            $guest->screen_resolution_y = 0;
            $guest->screen_color = 0;
            $guest->sun_java = 0;
            $guest->adobe_flash = 0;
            $guest->adobe_director = 0;
            $guest->apple_quicktime = 0;
            $guest->real_player = 0;
            $guest->windows_media = 0;
            $guest->mobile_theme = Context::getContext()->getMobileDevice();
            $guest->add();
            $id_guest_new = $guest->id;
            // tạo mới 1 khách hàng cho Guest
            $customer = new Customer();
            $data = $this->module->getCustomerQuote($td_id_quote);
            $customer->firstname = $data['first_name'];
            $customer->lastname = $data['last_name'];
            $customer->email = $data['email'];
            $customer->passwd = Tools::encrypt(Tools::passwdGen(8, 'RANDOM'));
            $customer->is_guest = 1;
            $customer->id_guest = $id_guest_new;
            if (!$customer->add()) {
                $result['has_error'] = 1;
                $result['errors'][] = $this->module->l('Can not create a customer for Guest.');
                echo Tools::jsonEncode($result);
                return false;
            }
            $td_id_customer = $customer->id;
        }
        $customer = new Customer($td_id_customer);
        $cart = new Cart();
        $date_now = date('Y-m-d H:i:s');
        if ($customer->is_guest) {
            $cart->id_guest = $id_guest_new;
            $cart->secure_key = md5($date_now);
        } else {
            $cart->secure_key = $customer->secure_key;
            $addresses = $customer->getAddresses((int) $id_lang);
            if (isset($addresses[0])) {
                $cart->id_address_invoice = (int) $addresses[0]['id_address'];
                $cart->id_address_delivery = (int) $addresses[0]['id_address'];
            }
        }
        $cart->id_customer = $td_id_customer;
        $cart->id_guest = $id_guest_new;
        $cart->id_shop_group = $this->context->shop->id_shop_group;
        $cart->id_lang = (int) $id_lang;
        $cart->id_currency = (int) $id_currency;
        $cart->recyclable = 0;
        $cart->gift = 0;
        $cart->add();
        $cart->setNoMultishipping();
        $id_cart = (int) $cart->id;
        if (empty($id_cart) || $id_cart == 0) {
            $result['has_error'] = 1;
            $result['errors'][] = $this->module->l('It have an error while creating a Cart');
            echo Tools::jsonEncode($result);
            return false;
        }
        $products = $this->convertToArrayRowProduct($row_product, 1);
        if (Configuration::get('PS_CATALOG_MODE') && !defined('_PS_ADMIN_DIR_')) {
            define('_PS_ADMIN_DIR_', '');
        }
        foreach ($products as $product) {
            $qty = (int) $product['quantity'];
            $id_product = (int) $product['id_product'];
            $id_product_attribute = (int) $product['id_combination'];
            // cập nhật cho phép thêm sản phẩm stock = 0 vào cart
            $sql = 'UPDATE '._DB_PREFIX_.'stock_available SET out_of_stock = 1 WHERE id_product='.(int) $id_product;
            $db->query($sql);
            // thêm sản phẩm vào Cart
            $cart->updateQty($qty, $id_product, $id_product_attribute, null, 'up');
            // cập nhật giá đúng giá Quote, ko phụ thuộc giá sản phẩm
            $default_price = Tools::convertPriceFull($product['price_product'], $currency, $currency_default);
            SpecificPrice::deleteByIdCart($cart->id, $id_product, $id_product_attribute);
            $specific_price = new SpecificPrice();
            $specific_price->id_cart = (int)$cart->id;
            $specific_price->id_shop = 0;
            $specific_price->id_shop_group = 0;
            $specific_price->id_currency = 0;
            $specific_price->id_country = 0;
            $specific_price->id_group = 0;
            $specific_price->id_customer = (int) $td_id_customer;
            $specific_price->id_product = (int) $id_product;
            $specific_price->id_product_attribute = (int) $id_product_attribute;
            $specific_price->price = (float) $default_price;
            $specific_price->from_quantity = 1;
            $specific_price->reduction = 0;
            $specific_price->reduction_type = 'amount';
            $specific_price->from = '0000-00-00 00:00:00';
            $specific_price->to = '0000-00-00 00:00:00';
            $specific_price->add();
        }
        $cart->update();
        $obsummary = $this->module->getQuoteCartSummary($id_cart);
        $result['args']['id_cart'] = $cart->id;
        $result['args']['id_customer'] = $cart->id_customer;
        $result['args']['obcart'] = $obsummary;
        $result['args']['oldprice'] = array();
        $this->genBoxaddress();
        $ba_dir = 'askforaquotemodul/views/templates/admin/boxaddress.tpl';
        $result['template'] = $this->context->smarty->fetch(_PS_MODULE_DIR_ . $ba_dir);
        echo Tools::jsonEncode($result);
    }
    public static function deleteAllSpecificPriceHasCart($id_product, $id_product_attribute = false)
    {
        $db = Db::getInstance();
        // lay tat ca id_cart_created dang cho thanh toan
        $sql = 'SELECT id_cart_create FROM ' . _DB_PREFIX_ . 'product_quote_dbboo ';
        $sql .= ' WHERE id_cart_create > 0 AND (id_order_create = 0 OR id_order_create IS NULL)';
        $id_carts = $db->executeS($sql);
        $id_carts2 = array();
        if (!empty($id_carts)) {
            foreach ($id_carts as $item) {
                $id_carts2[] = (int) $item['id_cart_create'];
            }
        }
        $sql ='DELETE FROM `'._DB_PREFIX_.'specific_price`';
        $sql .=    ' WHERE id_product = '.(int)$id_product;
        $sql .=    ' AND id_cart > 0 ';
        $sql .=    ' AND id_product_attribute = '.(int)$id_product_attribute;
        if (!empty($id_carts2)) {
            $sql_part = implode(",", $id_carts2);
            $sql .=    ' AND id_cart NOT IN ('.$sql_part.')';
        }
        return $db->execute($sql);
    }
    public function genBoxaddress()
    {
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $array_address = array();
        $id_delivery = Tools::getValue('id_delivery');
        $id_invoice = Tools::getValue('id_invoice');
        $td_id_customer = Tools::getValue('td_id_customer');
        $id_lang = Tools::getValue('jslanguageid');
        if ($td_id_customer != 0) {
            $obcustomer = new Customer($td_id_customer);
            $ar_address = $obcustomer->getAddresses($id_lang);
            if (!empty($ar_address)) {
                $id_delivery = $ar_address[0]['id_address'];
                $id_invoice = $ar_address[0]['id_address'];
            }
        }
        $sql_delivery = 'SELECT * FROM ' . _DB_PREFIX_ . 'address WHERE id_address=\''.(int) $id_delivery.'\'';
        $data_delivery = $db->ExecuteS($sql_delivery);
        $array_address['delivery']['td_popup__address_alias'] = @$data_delivery[0]['alias'];
        $array_address['delivery']['td_popup__address_first_name'] = @$data_delivery[0]['firstname'];
        $array_address['delivery']['td_popup__address_last_name'] = @$data_delivery[0]['lastname'];
        $array_address['delivery']['td_popup__address_company'] = @$data_delivery[0]['company'];
        $array_address['delivery']['td_popup__address_adres1'] = @$data_delivery[0]['address1'];
        $array_address['delivery']['td_popup__address_adres2'] = @$data_delivery[0]['address2'];
        $array_address['delivery']['td_popup__address_city'] = @$data_delivery[0]['city'];
        $array_address['delivery']['td_popup__address_state'] = '';
        if (!empty(@$data_delivery[0]['id_state'])) {
            $namestate = State::getNameById((int)@$data_delivery[0]['id_state']);
            $array_address['delivery']['td_popup__address_state'] = $namestate;
        }
        $array_address['delivery']['td_popup__address_zip_code'] = @$data_delivery[0]['postcode'];
        $id_countryde = (int)@$data_delivery[0]['id_country'];
        $array_address['delivery']['td_popup__address_country'] = Country::getNameById($id_lang, $id_countryde);
        $array_address['delivery']['td_popup__address_home_phone'] = @$data_delivery[0]['phone'];
        $array_address['delivery']['td_popup__address_mobile_phone'] = @$data_delivery[0]['phone_mobile'];
        $array_address['delivery']['id_address'] = $id_delivery;
        
        $sql_invoice = 'SELECT * FROM ' . _DB_PREFIX_ . 'address WHERE id_address=\''.(int) $id_invoice.'\'';
        $data_invoice = $db->ExecuteS($sql_invoice);
        $array_address['invoice']['td_popup__address_alias'] = @$data_invoice[0]['alias'];
        $array_address['invoice']['td_popup__address_first_name'] = @$data_invoice[0]['firstname'];
        $array_address['invoice']['td_popup__address_last_name'] = @$data_invoice[0]['lastname'];
        $array_address['invoice']['td_popup__address_company'] = @$data_invoice[0]['company'];
        $array_address['invoice']['td_popup__address_adres1'] = @$data_invoice[0]['address1'];
        $array_address['invoice']['td_popup__address_adres2'] = @$data_invoice[0]['address2'];
        $array_address['invoice']['td_popup__address_city'] = @$data_invoice[0]['city'];
        $array_address['invoice']['td_popup__address_state'] = '';
        if (!empty(@$data_invoice[0]['id_state'])) {
            $namestate = State::getNameById((int)@$data_invoice[0]['id_state']);
            $array_address['invoice']['td_popup__address_state'] = $namestate;
        }
        $array_address['invoice']['td_popup__address_zip_code'] = @$data_invoice[0]['postcode'];
        $id_countryin = (int)@$data_invoice[0]['id_country'];
        $array_address['invoice']['td_popup__address_country'] = Country::getNameById($id_lang, $id_countryin);
        $array_address['invoice']['td_popup__address_home_phone'] = @$data_invoice[0]['phone'];
        $array_address['invoice']['td_popup__address_mobile_phone'] = @$data_invoice[0]['phone_mobile'];
        $array_address['invoice']['id_address'] = $id_invoice;
        $sql = 'SELECT id_address FROM ' . _DB_PREFIX_ . 'address ';
        $sql .= 'WHERE id_customer="'.$td_id_customer.'" AND active="1"';
        $arr_id_address = $db->ExecuteS($sql);
        $arr_id_address_formatted = array();
        if (!empty($arr_id_address)) {
            foreach ($arr_id_address as $value_aid) {
                $arr_id_address_formatted[] = $value_aid['id_address'];
            }
        }
        $address_ids = implode(',', $arr_id_address_formatted);
        $this->genOptionAlias($address_ids);
        
        $this->context->smarty->assign('array_address', $array_address);
        $this->context->smarty->assign('address_ids', $address_ids);
    }
    
    public function genOptionAlias($address_ids)
    {
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $data_option = array();
        if (!empty($address_ids)) {
            $sql = 'SELECT id_address, alias FROM ' . _DB_PREFIX_ . 'address WHERE id_address IN ('.$address_ids.')';
            $sql .= ' AND id_customer > 0 ';
            $data_option = $db->ExecuteS($sql);
        }
        $this->context->smarty->assign('data_option', $data_option);
    }
    
    public function getLanguage($acceptLanguage)
    {
        $langsArray = array();
        preg_match_all('/([a-z]{2}(-[a-z]{2})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/', $acceptLanguage, $array);
        if (count($array[1])) {
            $langsArray = array_combine($array[1], $array[4]);
            foreach ($langsArray as $lang => $val) {
                if ($val === '') {
                    $langsArray[$lang] = 1;
                }
            }
            arsort($langsArray, SORT_NUMERIC);
        }
        return (count($langsArray) ? key($langsArray) : '');
    }
    public function getOs($userAgent)
    {
        $osArray = array(
            'Windows 8' => 'Windows NT 6.2',
            'Windows 7' => 'Windows NT 6.1',
            'Windows Vista' => 'Windows NT 6.0',
            'Windows XP' => 'Windows NT 5',
            'MacOsX' => 'Mac OS X',
            'Android' => 'Android',
            'Linux' => 'X11'
        );
        foreach ($osArray as $k => $value) {
            if (strstr($userAgent, $value)) {
                $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
                SELECT `id_operating_system`
                FROM `'._DB_PREFIX_.'operating_system` os
                WHERE os.`name` = \''.pSQL($k).'\'');

                return $result['id_operating_system'];
            }
        }
        return null;
    }
    public function getBrowser($userAgent)
    {
        $browserArray = array(
            'Chrome' => 'Chrome/',
            'Safari' => 'Safari',
            'Safari iPad' => 'iPad',
            'Firefox' => 'Firefox/',
            'Opera' => 'Opera',
            'IE 11' => 'Trident',
            'IE 10' => 'MSIE 10',
            'IE 9' => 'MSIE 9',
            'IE 8' => 'MSIE 8',
            'IE 7' => 'MSIE 7',
            'IE 6' => 'MSIE 6'
        );
        foreach ($browserArray as $k => $value) {
            if (strstr($userAgent, $value)) {
                $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
                SELECT `id_web_browser`
                FROM `'._DB_PREFIX_.'web_browser` wb
                WHERE wb.`name` = \''.pSQL($k).'\'');

                return $result['id_web_browser'];
            }
        }
        return null;
    }
    public function convertToArrayRowProduct($row_product, $pq_check = 0)
    {
        $result = array();
        $row_product = ltrim($row_product, '|');
        $row_product = explode('|', $row_product);
        $total_price = 0;
        foreach ($row_product as $key_row_product => $value_row_product) {
            $value_row_product = explode('-', $value_row_product);
            foreach ($value_row_product as $key_vrp => $value_vrp) {
                if ($key_vrp == 0) {
                    $result[$key_row_product]['id_product'] = $value_vrp;
                }
                if ($key_vrp == 1) {
                    $result[$key_row_product]['id_combination'] = $value_vrp;
                }
                if ($key_vrp == 2) {
                    $result[$key_row_product]['price_product'] = Tools::ps_round($value_vrp, 4);
                }
                if ($key_vrp == 3) {
                    $result[$key_row_product]['quantity'] = $value_vrp;
                }
                if ($key_vrp == 4) {
                    $result[$key_row_product]['total_price_product'] = Tools::ps_round($value_vrp, 4);
                    $total_price += (float) Tools::ps_round($value_vrp, 4);
                }
            }
        }
        if ($pq_check == 0) {
            $result['total_price'] = $total_price;
            $result['total_tax'] = 0;
        }
        return $result;
    }
}
