<?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 AskforaquotemodulsearchvoucherModuleFrontController extends ModuleFrontController
{
    public function run()
    {
        $quote_module_token = Tools::getValue('quote_token');
        if ($quote_module_token != md5(sha1(_COOKIE_KEY_.'askforaquotemodul'))) {
            die;
        }
        $action = pSQL(Tools::getValue('action'));
        switch ($action) {
            case 'search':
                return $this->searchVoucher();
            case 'add':
                return $this->addVoucher();
            case 'delete':
                return $this->deleteVoucher();
        }
        return true;
    }
    public function searchVoucher()
    {
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        $id_lang = $this->context->language->id;
        $search_code = Tools::getValue('td_seach_voucher');
        $cart_vouchers = array();
        $id_cart = (int) Tools::getValue('td_id_cart');

        $cart = new Cart($id_cart);
        $cart_rules = $cart->getCartRules();
        if (!empty($cart_rules)) {
            foreach ($cart_rules as $rule) {
                $cart_vouchers[] = (int) $rule['id_cart_rule'];
            }
        }
        $sql = 'SELECT * FROM ' . _DB_PREFIX_ . 'cart_rule a inner join';
        $sql .= ' ' . _DB_PREFIX_ . 'cart_rule_lang b on a.id_cart_rule = b.id_cart_rule ';
        $sql .= 'WHERE  id_lang = "'.$id_lang.'" and (a.code LIKE "%'.pSQL($search_code).'%" OR ';
        $sql .= 'b.name LIKE "%'.pSQL($search_code).'%") AND ';
        $sql .= '(a.date_to >= \''.date('Y-m-d H:i:s', time()).'\') ';
        if (!empty($cart_vouchers)) {
            $vouchers_excl = implode(',', $cart_vouchers);
            $sql .= ' AND a.id_cart_rule NOT IN ('.$vouchers_excl.')';
        }
        $data_coupon = $db->ExecuteS($sql, true, false);
        echo Tools::jsonEncode($data_coupon);
    }
    public function addVoucher()
    {
        $id_quote = (int) Tools::getValue('td_id_quote');
        $this->module->setCurrencyQuote($id_quote);
        $id_cart = (int) Tools::getValue('td_id_cart');
        $id_cart_rule = (int) Tools::getValue('id_voucher');
        $errors = array();
        $response = array(
            'has_error' => 0,
            'errors' => array()
        );
        if (!empty($id_cart)) {
            $cart = new Cart($id_cart);
            Context::getContext()->cart = $cart;
            $context = Context::getContext();
            if (empty($id_cart_rule) || !$cart_rule = new CartRule($id_cart_rule)) {
                $response['errors'][] = Tools::displayError('Invalid voucher.');
                $response['has_error'] = 1;
            } elseif ($err = $cart_rule->checkValidity($context)) {
                $errors[] = $err;
                $response['errors'][] = $err;
                $response['has_error'] = 1;
            }
            if (!count($response['errors'])) {
                if (!$cart->addCartRule((int)$cart_rule->id)) {
                    $response['errors'][] = Tools::displayError('Can\'t add the voucher.');
                    $response['has_error'] = 1;
                }
            }
        }
        echo Tools::jsonEncode($response);
    }
    public function deleteVoucher()
    {
        $id_cart = (int) Tools::getValue('td_id_cart');
        $id_voucher = (int) Tools::getValue('id_voucher');
        $cart = new Cart($id_cart);
        $cart->removeCartRule($id_voucher);
        return true;
    }
}
