<?php
/**
* 2007-2019 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-2019 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 AdminCheckDeliveryController extends ModuleAdminController
{
    public function run()
    {
        $quote_module_token = Tools::getValue('quote_token');
        if ($quote_module_token != md5(sha1(_COOKIE_KEY_.'askforaquotemodul'))) {
            die;
        }
        $td_id_quote = (int) Tools::getValue('td_id_quote');
        $this->module->setCurrencyQuote($td_id_quote);
   
        $td_id_customer = (int) Tools::getValue('td_id_customer');
        $customer = new Customer($td_id_customer);
        $id_cart = (int) Tools::getValue('id_cart');

        $json = array();
        $response = $this->updateDeliveryOptionList();
        $json['PS_GUEST_CHECKOUT_ENABLED'] = Configuration::get('PS_GUEST_CHECKOUT_ENABLED');
        $json['is_guest'] = $customer->is_guest;
        $json['boxshipping'] = $response['template'];
        $json['no_carrier'] = $response['no_carrier'];
        $json['boxvoucher'] = $this->getVourchersBox($id_cart);
        $json['summary_quotecart'] = $this->module->getQuoteCartSummary($id_cart);
        echo Tools::jsonEncode($json);
    }
    public function getVourchersBox($id_cart)
    {
        $cart = new Cart($id_cart);
        $this->context->smarty->assign('id_currency', $cart->id_currency);
        $this->context->smarty->assign('datacoupon', $cart->getCartRules());
        $tpl = 'askforaquotemodul/views/templates/admin/boxvoucher.tpl';
        $template = $this->context->smarty->fetch(_PS_MODULE_DIR_ . $tpl);
        return $template;
    }
    public function updateDeliveryOptionList()
    {
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $id_cart = (int) Tools::getValue('id_cart');
        $id_delivery = (int) Tools::getValue('id_delivery');
        $id_invoice = (int) Tools::getValue('id_invoice');
        $selected_ship = Tools::getValue('selected_ship');
        $free_shipping = (int) Tools::getValue('free_shipping');
        $cart = new Cart($id_cart);
        if (!$id_cart_rule = CartRule::getIdByCode('BO_ORDER_'.$cart->id)) {
            $cart_rule = new CartRule();
            $cart_rule->code = CartRule::BO_ORDER_CODE_PREFIX.$cart->id;
            $name = array(
                Configuration::get('PS_LANG_DEFAULT') => $this->l('Free Shipping', 'AdminTab', false, false)
            );
            $cart_rule->name = $name;
            $cart_rule->id_customer = (int)$cart->id_customer;
            $cart_rule->free_shipping = true;
            $cart_rule->quantity = 1;
            $cart_rule->quantity_per_user = 1;
            $cart_rule->minimum_amount_currency = (int)$cart->id_currency;
            $cart_rule->reduction_currency = (int)$cart->id_currency;
            $cart_rule->date_from = date('Y-m-d H:i:s', time());
            $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 36000);
            $cart_rule->active = 1;
            $cart_rule->add();
        } else {
            $cart_rule = new CartRule((int)$id_cart_rule);
        }
        $cart->removeCartRule((int)$cart_rule->id);
        if ($free_shipping == 1) {
            $cart->addCartRule((int)$cart_rule->id);
        }
        $id_currency = (int) $cart->id_currency;
        $cart->id_address_delivery = $id_delivery;
        $cart->id_address_invoice = $id_invoice;
        // đổi địa chỉ delivery của Cart
        $update_id_delivery = 'UPDATE ' . _DB_PREFIX_ . 'cart_product SET ';
        $update_id_delivery .= 'id_address_delivery = "'.$id_delivery.'" ';
        $update_id_delivery .= 'WHERE id_cart = "'.$id_cart.'"';
        $db->query($update_id_delivery);

        $cart->update();
        $delivery_option_list = $cart->getDeliveryOptionList();
        $result = array();
        $result['no_carrier'] = 0;
        $result['ob_carrier'] = array();
        
        if (!empty($delivery_option_list) && $id_delivery != 0) {
            foreach ($delivery_option_list[$id_delivery] as $key => $delivery_option) {
                $total_price_with_tax = (float) $delivery_option['total_price_with_tax'];
                $total_price_no_tax = (float) $delivery_option['total_price_without_tax'];
                // get Carrier Name
                $ar_carrier_name = array();
                foreach ($delivery_option['carrier_list'] as $carrier) {
                    $name = $carrier['instance']->name;
                    if ($delivery_option['unique_carrier']) {
                        $name .= ' - '.$carrier['instance']->delay[$this->context->employee->id_lang];
                    }
                    $ar_carrier_name[] = $name;
                }
                $carrier_name = implode(', ', $ar_carrier_name);
                if ($delivery_option['is_free'] == '1') {
                    $carrier_name .= ' ' . $this->l('(Free shipping!)');
                } else {
                    $carrier_name .= ' (' . Tools::displayPrice($total_price_no_tax, $id_currency) . ') ';
                }
                $result['ob_carrier'][$key]['carrier_name'] = $carrier_name;
                $result['ob_carrier'][$key]['total_price_with_tax'] = $total_price_with_tax;
                $result['ob_carrier'][$key]['total_price_without_tax'] = $total_price_no_tax;
                $total_shipping_tax = $total_price_with_tax - $total_price_no_tax;
                $result['ob_carrier'][$key]['total_shipping_tax'] = $total_shipping_tax;
                $result['ob_carrier'][$key]['is_free'] = $delivery_option['is_free'];
                if (!$cart->id_carrier || ($key == $selected_ship)) {
                    $cart->setDeliveryOption(array($id_delivery => $key));
                    $cart->update();
                }
            }
        } else {
            $result['no_carrier'] = 1;
        }
        $response = array();
        $this->context->smarty->assign('id_currency', $id_currency);
        $this->context->smarty->assign('id_carrier', $selected_ship);
        $this->context->smarty->assign('free_shipping', $free_shipping);
        $this->context->smarty->assign('result', $result['ob_carrier']);
        $ba_dir = 'askforaquotemodul/views/templates/admin/boxshipping.tpl';
        $response['template'] = $this->context->smarty->fetch(_PS_MODULE_DIR_ . $ba_dir);
        $response['no_carrier'] = $result['no_carrier'];
        return $response;
    }
}
